diff --git a/.idea/dictionaries/project_dictionary.xml b/.idea/dictionaries/project_dictionary.xml
index eb2cb8b9f3..3639be9c59 100644
--- a/.idea/dictionaries/project_dictionary.xml
+++ b/.idea/dictionaries/project_dictionary.xml
@@ -2,19 +2,24 @@
aaps
+ acked
actionstring
allowednumbers
androidaps
autosens
autosensdata
+ autosense
bage
+ basaliob
basals
bgcheck
+ bgsource
bolusing
carb
carbs
carbsreq
careportal
+ cellnovo
crashlytics
danar
danars
@@ -23,6 +28,7 @@
dexcom
dexdrip
enteredby
+ enteredinsulin
eveningoutpost
eversense
extendedbolus
@@ -32,12 +38,15 @@
gson
hmac
iage
+ insulet
iobtotal
+ libre
listdelimiter
localprofile
medtronic
mgdl
mmol
+ multiwave
netinsulin
netratio
nightscout
@@ -45,6 +54,7 @@
nsclient
okcancel
omnipod
+ openaps
oref
passcode
poctech
@@ -56,7 +66,9 @@
refresheventsfromnightscout
rileylink
roboelectric
+ sitechange
smscommunicator
+ sooil
soundid
splitted
superbolus
@@ -73,6 +85,9 @@
uart
wizzardpage
xdrip
+ ypso
+ ypsomed
+ ypsopump
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
index d08c3bf279..57f0a8f3ee 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,5 +1,5 @@
language: android
-jdk: oraclejdk8
+jdk: openjdk11
dist: trusty
env:
matrix:
diff --git a/app/build.gradle b/app/build.gradle
index 31d430687c..63b7948b91 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -111,7 +111,7 @@ android {
defaultConfig {
multiDexEnabled true
versionCode 1500
- version "2.8.2.1-dev-e"
+ version "2.8.2.1-dev-e4"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt
index 656bdae255..75ae0caa20 100644
--- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt
+++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt
@@ -1,35 +1,8 @@
package info.nightscout.androidaps
-import android.os.SystemClock
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
-import androidx.test.rule.ActivityTestRule
-import androidx.test.rule.GrantPermissionRule
-import info.nightscout.androidaps.data.Profile
-import info.nightscout.androidaps.interfaces.PluginBase
-import info.nightscout.androidaps.interfaces.PluginType
-import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
-import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
-import info.nightscout.androidaps.interfaces.ProfileFunction
-import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
-import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin
-import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin
-import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
-import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
-import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
-import info.nightscout.androidaps.plugins.source.RandomBgPlugin
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
-import info.nightscout.androidaps.utils.DateUtil
-import info.nightscout.androidaps.utils.extensions.isRunningTest
-import info.nightscout.androidaps.utils.sharedPreferences.SP
-import org.json.JSONObject
-import org.junit.Assert
-import org.junit.Before
-import org.junit.Rule
-import org.junit.Test
import org.junit.runner.RunWith
-import javax.inject.Inject
@LargeTest
@RunWith(AndroidJUnit4::class)
@@ -89,7 +62,7 @@ class RealPumpTest {
localProfilePlugin.numOfProfiles = 0
val singleProfile = LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, profile, "TestProfile")
localProfilePlugin.addProfile(singleProfile)
- val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, DateUtil.now())
+ val profileSwitch = profileFunction.prepareProfileSwitch(localProfilePlugin.createProfileStore(), "TestProfile", 0, 100, 0, dateUtil._now())
treatmentsPlugin.addToHistoryProfileSwitch(profileSwitch)
// Insulin
configBuilderPlugin.performPluginSwitch(insulinOrefUltraRapidActingPlugin, true, PluginType.INSULIN)
diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt
index bccdbbcb1a..b5b5974fee 100644
--- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt
+++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt
@@ -32,15 +32,20 @@ import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.activities.ProfileHelperActivity
import info.nightscout.androidaps.activities.SingleFragmentActivity
import info.nightscout.androidaps.activities.StatsActivity
+import info.nightscout.androidaps.database.entities.UserEntry.Action
+import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.databinding.ActivityMainBinding
import info.nightscout.androidaps.events.EventAppExit
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity
-import info.nightscout.androidaps.interfaces.ActivePluginProvider
+import info.nightscout.androidaps.interfaces.ActivePlugin
+import info.nightscout.androidaps.interfaces.Config
+import info.nightscout.androidaps.interfaces.IconsProvider
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
+import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
@@ -56,7 +61,6 @@ import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.isRunningRealPumpTest
import info.nightscout.androidaps.utils.locale.LocaleHelper
import info.nightscout.androidaps.utils.protection.ProtectionCheck
-import info.nightscout.androidaps.utils.resources.IconsProvider
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.tabs.TabPageAdapter
@@ -80,13 +84,14 @@ class MainActivity : NoSplashAppCompatActivity() {
@Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var nsSettingsStatus: NSSettingsStatus
@Inject lateinit var buildHelper: BuildHelper
- @Inject lateinit var activePlugin: ActivePluginProvider
+ @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var protectionCheck: ProtectionCheck
@Inject lateinit var iconsProvider: IconsProvider
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin
@Inject lateinit var config: Config
+ @Inject lateinit var uel: UserEntryLogger
private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
private var pluginPreferencesMenuItem: MenuItem? = null
@@ -316,6 +321,7 @@ class MainActivity : NoSplashAppCompatActivity() {
R.id.nav_exit -> {
aapsLogger.debug(LTag.CORE, "Exiting")
+ uel.log(Action.EXIT_AAPS, Sources.Aaps)
rxBus.send(EventAppExit())
finish()
System.runFinalization()
@@ -375,7 +381,7 @@ class MainActivity : NoSplashAppCompatActivity() {
if (!config.NSCLIENT && !config.PUMPCONTROL)
activePlugin.activeAPS.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) }
activePlugin.activeBgSource.let { fabricPrivacy.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) }
- fabricPrivacy.firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName)
+ fabricPrivacy.firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileSource.javaClass.simpleName)
activePlugin.activeSensitivity.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) }
activePlugin.activeInsulin.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) }
// Add to crash log too
diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt
index 4851452333..9731bf37d6 100644
--- a/app/src/main/java/info/nightscout/androidaps/MainApp.kt
+++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt
@@ -5,31 +5,38 @@ import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
+import android.os.Build
import com.j256.ormlite.android.apptools.OpenHelperManager
import dagger.android.AndroidInjector
import dagger.android.DaggerApplication
import info.nightscout.androidaps.database.AppRepository
+import info.nightscout.androidaps.database.entities.TherapyEvent
+import info.nightscout.androidaps.database.entities.UserEntry
+import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction
import info.nightscout.androidaps.database.transactions.VersionChangeTransaction
import info.nightscout.androidaps.db.CompatDBHelper
import info.nightscout.androidaps.db.DatabaseHelper
import info.nightscout.androidaps.db.StaticInjector
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent
+import info.nightscout.androidaps.interfaces.ConfigBuilder
+import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
+import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils
-import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.receivers.BTReceiver
import info.nightscout.androidaps.receivers.ChargingStateReceiver
import info.nightscout.androidaps.receivers.KeepAliveReceiver.KeepAliveManager
import info.nightscout.androidaps.receivers.NetworkChangeReceiver
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver
import info.nightscout.androidaps.utils.ActivityMonitor
+import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.locale.LocaleHelper.update
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
+import io.reactivex.rxkotlin.plusAssign
import net.danlew.android.joda.JodaTimeAndroid
import javax.inject.Inject
@@ -42,14 +49,15 @@ class MainApp : DaggerApplication() {
@Inject lateinit var activityMonitor: ActivityMonitor
@Inject lateinit var versionCheckersUtils: VersionCheckerUtils
@Inject lateinit var sp: SP
- @Inject lateinit var nsUpload: NSUpload
@Inject lateinit var config: Config
- @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
+ @Inject lateinit var configBuilder: ConfigBuilder
@Inject lateinit var keepAliveManager: KeepAliveManager
@Inject lateinit var plugins: List<@JvmSuppressWildcards PluginBase>
@Inject lateinit var compatDBHelper: CompatDBHelper
@Inject lateinit var repository: AppRepository
+ @Inject lateinit var dateUtil: DateUtil
@Inject lateinit var staticInjector: StaticInjector// TODO avoid , here fake only to initialize
+ @Inject lateinit var uel: UserEntryLogger
override fun onCreate() {
super.onCreate()
@@ -63,8 +71,9 @@ class MainApp : DaggerApplication() {
gitRemote = null
commitHash = null
}
- disposable.add(repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe())
- disposable.add(compatDBHelper.dbChangeDisposable())
+ disposable += repository.runTransaction(VersionChangeTransaction(BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, gitRemote, commitHash)).subscribe()
+ disposable += repository.runTransaction(InsertIfNewByTimestampTherapyEventTransaction(timestamp = dateUtil.now(), type = TherapyEvent.Type.NOTE, note = getString(info.nightscout.androidaps.core.R.string.androidaps_start).toString() + " - " + Build.MANUFACTURER + " " + Build.MODEL, glucoseUnit = TherapyEvent.GlucoseUnit.MGDL)).subscribe()
+ disposable += compatDBHelper.dbChangeDisposable()
registerActivityLifecycleCallbacks(activityMonitor)
JodaTimeAndroid.init(this)
aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME)
@@ -77,10 +86,10 @@ class MainApp : DaggerApplication() {
// Register all tabs in app here
pluginStore.plugins = plugins
- configBuilderPlugin.initialize()
- nsUpload.uploadAppStart()
- Thread { keepAliveManager.setAlarm(this) }.start()
+ configBuilder.initialize()
+ keepAliveManager.setAlarm(this)
doMigrations()
+ uel.log(UserEntry.Action.START_AAPS, UserEntry.Sources.Aaps)
}
private fun doMigrations() {
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt
index aed679673b..048b9c0d73 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt
@@ -8,13 +8,13 @@ import android.os.Bundle
import androidx.annotation.XmlRes
import androidx.preference.*
import dagger.android.support.AndroidSupportInjection
-import info.nightscout.androidaps.Config
+import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
-import info.nightscout.androidaps.data.Profile
+import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.interfaces.PluginBase
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt
index 34978739b6..e89e11a735 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt
+++ b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt
@@ -7,14 +7,16 @@ import android.text.TextWatcher
import android.view.Menu
import android.widget.PopupMenu
import info.nightscout.androidaps.R
-import info.nightscout.androidaps.data.Profile
+import info.nightscout.androidaps.data.ProfileSealed
+import info.nightscout.androidaps.data.PureProfile
import info.nightscout.androidaps.data.defaultProfile.DefaultProfile
import info.nightscout.androidaps.data.defaultProfile.DefaultProfileDPV
+import info.nightscout.androidaps.database.AppRepository
+import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch
import info.nightscout.androidaps.databinding.ActivityProfilehelperBinding
-import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.dialogs.ProfileViewerDialog
-import info.nightscout.androidaps.interfaces.ActivePluginProvider
-import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
+import info.nightscout.androidaps.extensions.toVisibility
+import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@@ -24,7 +26,6 @@ import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
-import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.stats.TddCalculator
import java.text.DecimalFormat
import javax.inject.Inject
@@ -39,8 +40,8 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
@Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var dateUtil: DateUtil
- @Inject lateinit var activePlugin: ActivePluginProvider
- @Inject lateinit var databaseHelper: DatabaseHelperInterface
+ @Inject lateinit var activePlugin: ActivePlugin
+ @Inject lateinit var repository: AppRepository
enum class ProfileType {
MOTOL_DEFAULT,
@@ -61,7 +62,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
private lateinit var profileList: ArrayList
private val profileUsed = arrayOf(0, 0)
- private lateinit var profileSwitch: List
+ private lateinit var profileSwitch: List
private val profileSwitchUsed = arrayOf(0, 0)
private lateinit var binding: ActivityProfilehelperBinding
@@ -85,10 +86,10 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
setOnMenuItemClickListener { item ->
binding.profiletype.setText(item.title)
when (item.itemId) {
- R.id.menu_default -> switchTab(tabSelected, ProfileType.MOTOL_DEFAULT)
- R.id.menu_default_dpv -> switchTab(tabSelected, ProfileType.DPV_DEFAULT)
- R.id.menu_current -> switchTab(tabSelected, ProfileType.CURRENT)
- R.id.menu_available -> switchTab(tabSelected, ProfileType.AVAILABLE_PROFILE)
+ R.id.menu_default -> switchTab(tabSelected, ProfileType.MOTOL_DEFAULT)
+ R.id.menu_default_dpv -> switchTab(tabSelected, ProfileType.DPV_DEFAULT)
+ R.id.menu_current -> switchTab(tabSelected, ProfileType.CURRENT)
+ R.id.menu_available -> switchTab(tabSelected, ProfileType.AVAILABLE_PROFILE)
R.id.menu_profileswitch -> switchTab(tabSelected, ProfileType.PROFILE_SWITCH)
}
true
@@ -98,7 +99,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
}
// Active profile
- profileList = activePlugin.activeProfileInterface.profile?.getProfileList() ?: ArrayList()
+ profileList = activePlugin.activeProfileSource.profile?.getProfileList() ?: ArrayList()
binding.availableProfileList.setOnClickListener {
PopupMenu(this, binding.availableProfileList).apply {
@@ -114,12 +115,12 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
}
// Profile switch
- profileSwitch = databaseHelper.getProfileSwitchData(dateUtil._now() - T.months(2).msecs(), true)
+ profileSwitch = repository.getEffectiveProfileSwitchDataFromTime(dateUtil.now() - T.months(2).msecs(), true).blockingGet()
binding.profileswitchList.setOnClickListener {
PopupMenu(this, binding.profileswitchList).apply {
var order = 0
- for (name in profileSwitch) menu.add(Menu.NONE, order, order++, name.customizedName)
+ for (name in profileSwitch) menu.add(Menu.NONE, order, order++, name.originalCustomizedName)
setOnMenuItemClickListener { item ->
binding.profileswitchList.setText(item.title)
profileSwitchUsed[tabSelected] = item.itemId
@@ -141,7 +142,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
profile?.let {
OKDialog.showConfirmation(this, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile), Runnable {
localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile " +
- dateUtil.dateAndTimeAndSecondsString(dateUtil._now())
+ dateUtil.dateAndTimeAndSecondsString(dateUtil.now())
.replace(".", "/")
))
rxBus.send(EventLocalProfileChanged())
@@ -210,11 +211,10 @@ 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())
- it.putString("customProfileUnits", profileFunction.getUnits())
+ it.putString("customProfile", profile0.jsonObject.toString())
+ it.putString("customProfile2", profile1.jsonObject.toString())
it.putString("customProfileName", getProfileName(ageUsed[0], tddUsed[0], weightUsed[0], pctUsed[0] / 100.0, 0) + "\n" + getProfileName(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1))
}
}.show(supportFragmentManager, "ProfileViewDialog")
@@ -227,14 +227,14 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
switchTab(0, typeSelected[0], false)
}
- private fun getProfile(age: Double, tdd: Double, weight: Double, basalPct: Double, tab: Int): Profile? =
+ private fun getProfile(age: Double, tdd: Double, weight: Double, basalPct: Double, tab: Int): PureProfile? =
try { // profile must not exist
when (typeSelected[tab]) {
- ProfileType.MOTOL_DEFAULT -> defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
- ProfileType.DPV_DEFAULT -> defaultProfileDPV.profile(age, tdd, basalPct, profileFunction.getUnits())
- ProfileType.CURRENT -> profileFunction.getProfile()?.convertToNonCustomizedProfile()
- ProfileType.AVAILABLE_PROFILE -> activePlugin.activeProfileInterface.profile?.getSpecificProfile(profileList[profileUsed[tab]].toString())
- ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].profileObject?.convertToNonCustomizedProfile()
+ ProfileType.MOTOL_DEFAULT -> defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
+ ProfileType.DPV_DEFAULT -> defaultProfileDPV.profile(age, tdd, basalPct, profileFunction.getUnits())
+ ProfileType.CURRENT -> profileFunction.getProfile()?.convertToNonCustomizedProfile(dateUtil)
+ ProfileType.AVAILABLE_PROFILE -> activePlugin.activeProfileSource.profile?.getSpecificProfile(profileList[profileUsed[tab]].toString())
+ ProfileType.PROFILE_SWITCH -> ProfileSealed.EPS(profileSwitch[profileSwitchUsed[tab]]).convertToNonCustomizedProfile(dateUtil)
}
} catch (e: Exception) {
null
@@ -242,11 +242,11 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
private fun getProfileName(age: Double, tdd: Double, weight: Double, basalSumPct: Double, tab: Int): String =
when (typeSelected[tab]) {
- ProfileType.MOTOL_DEFAULT -> if (tdd > 0) resourceHelper.gs(R.string.formatwithtdd, age, tdd) else resourceHelper.gs(R.string.formatwithweight, age, weight)
- ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt())
- ProfileType.CURRENT -> profileFunction.getProfileName()
+ ProfileType.MOTOL_DEFAULT -> if (tdd > 0) resourceHelper.gs(R.string.formatwithtdd, age, tdd) else resourceHelper.gs(R.string.formatwithweight, age, weight)
+ ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt())
+ ProfileType.CURRENT -> profileFunction.getProfileName()
ProfileType.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString()
- ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].customizedName
+ ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].originalCustomizedName
}
private fun storeValues() {
@@ -289,7 +289,7 @@ class ProfileHelperActivity : NoSplashAppCompatActivity() {
if (profileList.isNotEmpty())
binding.availableProfileList.setText(profileList[profileUsed[tabSelected]].toString())
if (profileSwitch.isNotEmpty())
- binding.profileswitchList.setText(profileSwitch[profileSwitchUsed[tabSelected]].customizedName)
+ binding.profileswitchList.setText(profileSwitch[profileSwitchUsed[tabSelected]].originalCustomizedName)
}
private fun setBackgroundColorOnSelected(tab: Int) {
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt
index 896506b93f..8edeccfebd 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt
+++ b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt
@@ -2,7 +2,8 @@ package info.nightscout.androidaps.activities
import android.os.Bundle
import info.nightscout.androidaps.R
-import info.nightscout.androidaps.database.entities.UserEntry.*
+import info.nightscout.androidaps.database.entities.UserEntry.Action
+import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.databinding.ActivityStatsBinding
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.utils.ActivityMonitor
@@ -32,7 +33,7 @@ class StatsActivity : NoSplashAppCompatActivity() {
binding.ok.setOnClickListener { finish() }
binding.reset.setOnClickListener {
OKDialog.showConfirmation(this, resourceHelper.gs(R.string.doyouwantresetstats)) {
- uel.log(Action.STAT_RESET)
+ uel.log(Action.STAT_RESET, Sources.Stats)
activityMonitor.reset()
recreate()
}
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt
index 5286afc33d..b7af9b8154 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt
+++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt
@@ -8,7 +8,7 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.defaultProfile.DefaultProfile
import info.nightscout.androidaps.databinding.ActivitySurveyBinding
import info.nightscout.androidaps.dialogs.ProfileViewerDialog
-import info.nightscout.androidaps.interfaces.ActivePluginProvider
+import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
@@ -24,12 +24,13 @@ import javax.inject.Inject
class SurveyActivity : NoSplashAppCompatActivity() {
@Inject lateinit var aapsLogger: AAPSLogger
- @Inject lateinit var activePlugin: ActivePluginProvider
+ @Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var tddCalculator: TddCalculator
@Inject lateinit var tirCalculator: TirCalculator
@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
@@ -40,7 +41,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
binding.id.text = InstanceId.instanceId()
- val profileStore = activePlugin.activeProfileInterface.profile
+ val profileStore = activePlugin.activeProfileSource.profile
val profileList = profileStore?.getProfileList() ?: return
binding.spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList)
@@ -68,11 +69,10 @@ 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())
- it.putString("customProfileUnits", profile.units)
+ it.putString("customProfile", runningProfile.toPureNsJson(dateUtil).toString())
+ it.putString("customProfile2", profile.jsonObject.toString())
it.putString("customProfileName", "Age: $age TDD: $tdd Weight: $weight")
}
}.show(supportFragmentManager, "ProfileViewDialog")
diff --git a/core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt
similarity index 96%
rename from core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt
rename to app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt
index 2b80598d6d..fa8b2774be 100644
--- a/core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt
+++ b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfile.kt
@@ -1,7 +1,10 @@
package info.nightscout.androidaps.data.defaultProfile
-import dagger.android.HasAndroidInjector
-import info.nightscout.androidaps.data.Profile
+import info.nightscout.androidaps.data.PureProfile
+import info.nightscout.androidaps.extensions.pureProfileFromJson
+import info.nightscout.androidaps.interfaces.GlucoseUnit
+import info.nightscout.androidaps.interfaces.Profile
+import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.Round
import org.json.JSONArray
import org.json.JSONObject
@@ -10,14 +13,14 @@ import javax.inject.Inject
import javax.inject.Singleton
@Singleton
-class DefaultProfile @Inject constructor(val injector: HasAndroidInjector) {
+class DefaultProfile @Inject constructor(val dateUtil: DateUtil) {
var oneToFive: TreeMap> = TreeMap()
var sixToEleven: TreeMap> = TreeMap()
var twelveToSeventeen: TreeMap> = TreeMap()
- var eighteenToTwentyfor: TreeMap> = TreeMap()
+ var eighteenToTwentyFour: TreeMap> = TreeMap()
- fun profile(age: Double, tdd: Double, weight: Double, units: String): Profile? {
+ fun profile(age: Double, tdd: Double, weight: Double, units: GlucoseUnit): PureProfile? {
val profile = JSONObject()
if (age >= 1 && age < 6) {
val _tdd = if (tdd == 0.0) 0.6 * weight else tdd
@@ -49,8 +52,8 @@ class DefaultProfile @Inject constructor(val injector: HasAndroidInjector) {
profile.put("timezone", TimeZone.getDefault().id)
profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units))))
profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units))))
- profile.put("units", units)
- return Profile(injector, profile, units)
+ profile.put("units", units.asText)
+ return pureProfileFromJson(profile, dateUtil)
}
init {
@@ -148,7 +151,7 @@ class DefaultProfile @Inject constructor(val injector: HasAndroidInjector) {
return array
}
- private fun singleValueArrayFromMmolToUnits(value: Double, sample: Array, units: String): JSONArray {
+ private fun singleValueArrayFromMmolToUnits(value: Double, sample: Array, units: GlucoseUnit): JSONArray {
val array = JSONArray()
array.put(JSONObject().put("time", "00:00").put("value", Profile.fromMmolToUnits(value + sample[0],units)).put("timeAsSeconds", 0 * 3600))
array.put(JSONObject().put("time", "06:00").put("value", Profile.fromMmolToUnits(value + sample[1],units)).put("timeAsSeconds", 6 * 3600))
diff --git a/core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt
similarity index 86%
rename from core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt
rename to app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt
index c7eb7959ab..78ed97b335 100644
--- a/core/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt
+++ b/app/src/main/java/info/nightscout/androidaps/data/defaultProfile/DefaultProfileDPV.kt
@@ -1,8 +1,11 @@
package info.nightscout.androidaps.data.defaultProfile
import dagger.android.HasAndroidInjector
-import info.nightscout.androidaps.data.Profile
-import info.nightscout.androidaps.utils.Round
+import info.nightscout.androidaps.data.PureProfile
+import info.nightscout.androidaps.extensions.pureProfileFromJson
+import info.nightscout.androidaps.interfaces.GlucoseUnit
+import info.nightscout.androidaps.interfaces.Profile
+import info.nightscout.androidaps.utils.DateUtil
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
@@ -10,13 +13,13 @@ import javax.inject.Inject
import javax.inject.Singleton
@Singleton
-class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector) {
+class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector, val dateUtil: DateUtil) {
var oneToFive = arrayOf(3.97, 3.61, 3.46, 3.70, 3.76, 3.87, 4.18, 4.01, 3.76, 3.54, 3.15, 2.80, 2.86, 3.21, 3.61, 3.97, 4.43, 4.96, 5.10, 5.50, 5.81, 6.14, 5.52, 5.10)
var sixToEleven = arrayOf(4.20, 4.27, 4.41, 4.62, 4.92, 5.09, 5.01, 4.47, 3.89, 3.33, 3.10, 2.91, 2.97, 3.08, 3.36, 3.93, 4.52, 4.76, 4.69, 4.63, 4.63, 4.47, 4.47, 4.31)
var twelveToEighteen = arrayOf(3.47, 3.80, 4.31, 4.95, 5.59, 6.11, 5.89, 5.11, 4.31, 3.78, 3.55, 3.39, 3.35, 3.39, 3.64, 3.97, 4.53, 4.59, 4.50, 4.00, 3.69, 3.39, 3.35, 3.35)
- fun profile(age: Double, tdd: Double, basalSumPct: Double, units: String): Profile? {
+ fun profile(age: Double, tdd: Double, basalSumPct: Double, units: GlucoseUnit): PureProfile? {
val basalSum = tdd * basalSumPct
val profile = JSONObject()
if (age >= 1 && age < 6) {
@@ -40,8 +43,8 @@ class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector) {
profile.put("timezone", TimeZone.getDefault().id)
profile.put("target_high", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units))))
profile.put("target_low", JSONArray().put(JSONObject().put("time", "00:00").put("value", Profile.fromMgdlToUnits(108.0, units))))
- profile.put("units", units)
- return Profile(injector, profile, units)
+ profile.put("units", units.asText)
+ return pureProfileFromJson(profile, dateUtil)
}
private fun arrayToJson(b: Array, basalSum: Double): JSONArray {
@@ -59,7 +62,7 @@ class DefaultProfileDPV @Inject constructor(val injector: HasAndroidInjector) {
return array
}
- private fun singleValueArrayFromMmolToUnits(value: Double, units: String): JSONArray {
+ private fun singleValueArrayFromMmolToUnits(value: Double, units: GlucoseUnit): JSONArray {
val array = JSONArray()
array.put(JSONObject().put("time", "00:00").put("value", Profile.fromMmolToUnits(value, units)).put("timeAsSeconds", 0 * 3600))
return array
diff --git a/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt b/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt
index aef3c28a3b..2bb83ef910 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt
+++ b/app/src/main/java/info/nightscout/androidaps/db/CompatDBHelper.kt
@@ -1,14 +1,10 @@
package info.nightscout.androidaps.db
import info.nightscout.androidaps.database.AppRepository
-import info.nightscout.androidaps.database.entities.Food
-import info.nightscout.androidaps.database.entities.GlucoseValue
-import info.nightscout.androidaps.database.entities.TemporaryTarget
-import info.nightscout.androidaps.database.entities.TherapyEvent
-import info.nightscout.androidaps.events.EventFoodDatabaseChanged
-import info.nightscout.androidaps.events.EventNewBG
-import info.nightscout.androidaps.events.EventTempTargetChange
-import info.nightscout.androidaps.events.EventTherapyEventChange
+import info.nightscout.androidaps.database.entities.*
+import info.nightscout.androidaps.database.entities.ExtendedBolus
+import info.nightscout.androidaps.database.entities.TemporaryBasal
+import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
@@ -30,13 +26,41 @@ class CompatDBHelper @Inject constructor(
rxBus.send(EventNewBG(null))
}
.subscribe {
- it.filterIsInstance().firstOrNull()?.let {
- aapsLogger.debug(LTag.DATABASE, "Firing EventNewHistoryData")
- rxBus.send(EventNewHistoryData(it.timestamp))
- }
- it.filterIsInstance().lastOrNull()?.let {
+ /**
+ * GlucoseValues can come in batch
+ * oldest one should be used for invalidation, newest one for for triggering Loop.
+ * Thus we need to collect both
+ *
+ */
+ var newestGlucoseValue: GlucoseValue? = null
+ it.filterIsInstance().lastOrNull()?.let { gv ->
aapsLogger.debug(LTag.DATABASE, "Firing EventNewBg")
- rxBus.send(EventNewBG(it))
+ rxBus.send(EventNewBG(gv))
+ newestGlucoseValue = gv
+ }
+ it.filterIsInstance().map { gv -> gv.timestamp }.minOrNull()?.let { timestamp ->
+ aapsLogger.debug(LTag.DATABASE, "Firing EventNewHistoryData")
+ rxBus.send(EventNewHistoryData(timestamp, true, newestGlucoseValue))
+ }
+ it.filterIsInstance().map { t -> t.timestamp }.minOrNull()?.let { timestamp ->
+ aapsLogger.debug(LTag.DATABASE, "Firing EventTreatmentChange")
+ rxBus.send(EventTreatmentChange())
+ rxBus.send(EventNewHistoryData(timestamp, false))
+ }
+ it.filterIsInstance().map { t -> t.timestamp }.minOrNull()?.let { timestamp ->
+ aapsLogger.debug(LTag.DATABASE, "Firing EventTreatmentChange")
+ rxBus.send(EventTreatmentChange())
+ rxBus.send(EventNewHistoryData(timestamp, false))
+ }
+ it.filterIsInstance().map { t -> t.timestamp }.minOrNull()?.let { timestamp ->
+ aapsLogger.debug(LTag.DATABASE, "Firing EventTempBasalChange")
+ rxBus.send(EventTempBasalChange())
+ rxBus.send(EventNewHistoryData(timestamp, false))
+ }
+ it.filterIsInstance().map { t -> t.timestamp }.minOrNull()?.let { timestamp ->
+ aapsLogger.debug(LTag.DATABASE, "Firing EventExtendedBolusChange")
+ rxBus.send(EventExtendedBolusChange())
+ rxBus.send(EventNewHistoryData(timestamp, false))
}
it.filterIsInstance().firstOrNull()?.let {
aapsLogger.debug(LTag.DATABASE, "Firing EventTempTargetChange")
@@ -50,5 +74,13 @@ class CompatDBHelper @Inject constructor(
aapsLogger.debug(LTag.DATABASE, "Firing EventFoodDatabaseChanged")
rxBus.send(EventFoodDatabaseChanged())
}
+ it.filterIsInstance().firstOrNull()?.let {
+ aapsLogger.debug(LTag.DATABASE, "Firing EventProfileSwitchChanged")
+ rxBus.send(EventProfileSwitchChanged())
+ }
+ it.filterIsInstance().firstOrNull()?.let {
+ aapsLogger.debug(LTag.DATABASE, "Firing EventProfileSwitchChanged")
+ rxBus.send(EventProfileSwitchChanged())
+ }
}
}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
index 3e4f21c330..c323a475be 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
@@ -4,8 +4,6 @@ import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
-import androidx.annotation.Nullable;
-
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
@@ -16,43 +14,21 @@ import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
-import org.json.JSONException;
-import org.json.JSONObject;
-
import java.sql.SQLException;
import java.util.ArrayList;
-import java.util.Calendar;
import java.util.Collections;
-import java.util.GregorianCalendar;
import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
-import info.nightscout.androidaps.dana.comm.RecordTypes;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
-import info.nightscout.androidaps.events.EventReloadTempBasalData;
-import info.nightscout.androidaps.events.EventReloadTreatmentData;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.interfaces.ActivePluginProvider;
-import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
-import info.nightscout.androidaps.interfaces.ProfileInterface;
-import info.nightscout.androidaps.interfaces.ProfileStore;
+import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
-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.PercentageSplitter;
+import info.nightscout.androidaps.utils.DateUtil;
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
@@ -67,28 +43,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Inject RxBusWrapper rxBus;
@Inject VirtualPumpPlugin virtualPumpPlugin;
@Inject OpenHumansUploader openHumansUploader;
- @Inject ActivePluginProvider activePlugin;
- @Inject NSUpload nsUpload;
+ @Inject ActivePlugin activePlugin;
+ @Inject DateUtil dateUtil;
public static final String DATABASE_NAME = "AndroidAPSDb";
- public static final String DATABASE_EXTENDEDBOLUSES = "ExtendedBoluses";
- public static final String DATABASE_DANARHISTORY = "DanaRHistory";
- public static final String DATABASE_DBREQUESTS = "DBRequests";
- public static final String DATABASE_TDDS = "TDDs";
private static final int DATABASE_VERSION = 13;
public static Long earliestDataChange = null;
- private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor();
- private static ScheduledFuture> scheduledTemBasalsPost = null;
-
- private static final ScheduledExecutorService extendedBolusWorker = Executors.newSingleThreadScheduledExecutor();
- private static ScheduledFuture> scheduledExtendedBolusPost = null;
-
- private static final ScheduledExecutorService profileSwitchEventWorker = Executors.newSingleThreadScheduledExecutor();
- private static ScheduledFuture> scheduledProfileSwitchEventPost = null;
-
private int oldVersion = 0;
private int newVersion = 0;
@@ -103,21 +66,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
aapsLogger.info(LTag.DATABASE, "onCreate");
- TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
- TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
- TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
- TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
- TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
- TableUtils.createTableIfNotExists(connectionSource, TDD.class);
- TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
- TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
- TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class);
TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class);
- database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
- "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")");
- database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
- "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")");
} catch (SQLException e) {
aapsLogger.error("Can't create database", e);
throw new RuntimeException(e);
@@ -132,23 +82,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (oldVersion < 7) {
aapsLogger.info(LTag.DATABASE, "onUpgrade");
- TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
- TableUtils.dropTable(connectionSource, DbRequest.class, true);
- TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
- TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
- TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
- } else if (oldVersion < 10) {
- TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
- TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
- TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
- database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
- "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\")");
- database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
- "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\")");
- } else if (oldVersion < 11) {
- database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_BOLUS_IDS + "\"");
- database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DatabaseHelperInterface.Companion.DATABASE_INSIGHT_PUMP_IDS + "\"");
}
TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class);
} catch (SQLException e) {
@@ -179,28 +113,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void resetDatabases() {
try {
- TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true);
- TableUtils.dropTable(connectionSource, DbRequest.class, true);
- TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
- TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
- TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
- TableUtils.dropTable(connectionSource, TDD.class, true);
TableUtils.dropTable(connectionSource, OmnipodHistoryRecord.class, true);
- TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
- TableUtils.createTableIfNotExists(connectionSource, DbRequest.class);
- TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
- TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
- TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
- TableUtils.createTableIfNotExists(connectionSource, TDD.class);
TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class);
updateEarliestDataChange(0);
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}
virtualPumpPlugin.setFakingStatus(true);
- scheduleTemporaryBasalChange();
- scheduleExtendedBolusChange();
- scheduleProfileSwitchChange();
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
@@ -212,86 +131,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
);
}
- public void resetTemporaryBasals() {
- try {
- TableUtils.dropTable(connectionSource, TemporaryBasal.class, true);
- TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class);
- updateEarliestDataChange(0);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- virtualPumpPlugin.setFakingStatus(false);
- scheduleTemporaryBasalChange();
- }
-
- public void resetExtededBoluses() {
- try {
- TableUtils.dropTable(connectionSource, ExtendedBolus.class, true);
- TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class);
- updateEarliestDataChange(0);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- scheduleExtendedBolusChange();
- }
-
- public void resetProfileSwitch() {
- try {
- TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
- TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- scheduleProfileSwitchChange();
- }
-
- public void resetTDDs() {
- try {
- TableUtils.dropTable(connectionSource, TDD.class, true);
- TableUtils.createTableIfNotExists(connectionSource, TDD.class);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
// ------------------ getDao -------------------------------------------
- private Dao getDaoDanaRHistory() throws SQLException {
- return getDao(DanaRHistoryRecord.class);
- }
-
- private Dao getDaoTDD() throws SQLException {
- return getDao(TDD.class);
- }
-
- private Dao getDaoDbRequest() throws SQLException {
- return getDao(DbRequest.class);
- }
-
- private Dao getDaoTemporaryBasal() throws SQLException {
- return getDao(TemporaryBasal.class);
- }
-
- private Dao getDaoExtendedBolus() throws SQLException {
- return getDao(ExtendedBolus.class);
- }
-
- private Dao getDaoProfileSwitch() throws SQLException {
- return getDao(ProfileSwitch.class);
- }
-
- private Dao getDaoInsightPumpID() throws SQLException {
- return getDao(InsightPumpID.class);
- }
-
- private Dao getDaoInsightBolusID() throws SQLException {
- return getDao(InsightBolusID.class);
- }
-
- private Dao getDaoInsightHistoryOffset() throws SQLException {
- return getDao(InsightHistoryOffset.class);
- }
-
private Dao getDaoPodHistory() throws SQLException {
return getDao(OmnipodHistoryRecord.class);
}
@@ -300,130 +141,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(OHQueueItem.class);
}
- public long roundDateToSec(long date) {
- long rounded = date - date % 1000;
- if (rounded != date)
- aapsLogger.debug(LTag.DATABASE, "Rounding " + date + " to " + rounded);
- return rounded;
- }
-
- // ------------------- TDD handling -----------------------
- public void createOrUpdateTDD(TDD tdd) {
- try {
- Dao dao = getDaoTDD();
- dao.createOrUpdate(tdd);
- openHumansUploader.enqueueTotalDailyDose(tdd);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public List getTDDs() {
- List tddList;
- try {
- QueryBuilder queryBuilder = getDaoTDD().queryBuilder();
- queryBuilder.orderBy("date", false);
- queryBuilder.limit(10L);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- tddList = getDaoTDD().query(preparedQuery);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- tddList = new ArrayList<>();
- }
- return tddList;
- }
-
- public List getAllTDDs() {
- try {
- return getDaoTDD().queryForAll();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return Collections.emptyList();
- }
-
- public List getTDDsForLastXDays(int days) {
- List tddList;
- GregorianCalendar gc = new GregorianCalendar();
- gc.add(Calendar.DAY_OF_YEAR, (-1) * days);
-
- try {
- QueryBuilder queryBuilder = getDaoTDD().queryBuilder();
- queryBuilder.orderBy("date", false);
- Where where = queryBuilder.where();
- where.ge("date", gc.getTimeInMillis());
- PreparedQuery preparedQuery = queryBuilder.prepare();
- tddList = getDaoTDD().query(preparedQuery);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- tddList = new ArrayList<>();
- }
- return tddList;
- }
-
- // ------------- DbRequests handling -------------------
-
- public void create(DbRequest dbr) throws SQLException {
- getDaoDbRequest().create(dbr);
- }
-
- public int delete(DbRequest dbr) {
- try {
- return getDaoDbRequest().delete(dbr);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return 0;
- }
-
- public int deleteDbRequest(String nsClientId) {
- try {
- return getDaoDbRequest().deleteById(nsClientId);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return 0;
- }
-
- public void deleteDbRequestbyMongoId(String action, String id) {
- try {
- QueryBuilder queryBuilder = getDaoDbRequest().queryBuilder();
- // By nsID
- Where where = queryBuilder.where();
- where.eq("_id", id).and().eq("action", action);
- queryBuilder.limit(10L);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List dbList = getDaoDbRequest().query(preparedQuery);
- for (DbRequest r : dbList) delete(r);
- // By nsClientID
- where = queryBuilder.where();
- where.eq("nsClientID", id).and().eq("action", action);
- queryBuilder.limit(10L);
- preparedQuery = queryBuilder.prepare();
- dbList = getDaoDbRequest().query(preparedQuery);
- for (DbRequest r : dbList) delete(r);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public void deleteAllDbRequests() {
- try {
- TableUtils.clearTable(connectionSource, DbRequest.class);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public CloseableIterator getDbRequestIterator() {
- try {
- return getDaoDbRequest().closeableIterator();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- return null;
- }
- }
-
public static void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
earliestDataChange = newDate;
@@ -434,923 +151,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
- // ----------------- DanaRHistory handling --------------------
-
- public void createOrUpdate(DanaRHistoryRecord record) {
- try {
- getDaoDanaRHistory().createOrUpdate(record);
-
- //If it is a TDD, store it for stats also.
- if (record.recordCode == RecordTypes.RECORD_TYPE_DAILY) {
- createOrUpdateTDD(new TDD(record.recordDate, record.recordDailyBolus, record.recordDailyBasal, 0));
- }
-
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public List getDanaRHistoryRecordsByType(byte type) {
- List historyList;
- try {
- QueryBuilder queryBuilder = getDaoDanaRHistory().queryBuilder();
- queryBuilder.orderBy("recordDate", false);
- Where where = queryBuilder.where();
- where.eq("recordCode", type);
- queryBuilder.limit(200L);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- historyList = getDaoDanaRHistory().query(preparedQuery);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- historyList = new ArrayList<>();
- }
- return historyList;
- }
-
- // ------------ TemporaryBasal handling ---------------
-
- //return true if new record was created
- public boolean createOrUpdate(TemporaryBasal tempBasal) {
- try {
- TemporaryBasal old;
- tempBasal.date = roundDateToSec(tempBasal.date);
-
- if (tempBasal.source == Source.PUMP) {
- // check for changed from pump change in NS
- QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("pumpId", tempBasal.pumpId);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoTemporaryBasal().query(preparedQuery);
- if (trList.size() > 0) {
- // do nothing, pump history record cannot be changed
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
- return false;
- }
-
- // search by date (in case its standard record that has become pump record)
- QueryBuilder queryBuilder2 = getDaoTemporaryBasal().queryBuilder();
- Where where2 = queryBuilder2.where();
- where2.eq("date", tempBasal.date);
- PreparedQuery preparedQuery2 = queryBuilder2.prepare();
- List trList2 = getDaoTemporaryBasal().query(preparedQuery2);
-
- if (trList2.size() > 0) {
- old = trList2.get(0);
-
- old.copyFromPump(tempBasal);
- old.source = Source.PUMP;
-
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
-
- getDaoTemporaryBasal().update(old);
- openHumansUploader.enqueueTemporaryBasal(old);
-
- updateEarliestDataChange(tempBasal.date);
- scheduleTemporaryBasalChange();
-
- return false;
- }
-
- getDaoTemporaryBasal().create(tempBasal);
- openHumansUploader.enqueueTemporaryBasal(tempBasal);
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
- updateEarliestDataChange(tempBasal.date);
- scheduleTemporaryBasalChange();
- return true;
- }
- if (tempBasal.source == Source.NIGHTSCOUT) {
- old = getDaoTemporaryBasal().queryForId(tempBasal.date);
- if (old != null) {
- if (!old.isAbsolute && tempBasal.isAbsolute) { // converted to absolute by "ns_sync_use_absolute"
- // so far ignore, do not convert back because it may not be accurate
- return false;
- }
- if (!old.isEqual(tempBasal)) {
- long oldDate = old.date;
- getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
- old.copyFrom(tempBasal);
- getDaoTemporaryBasal().create(old);
- openHumansUploader.enqueueTemporaryBasal(old);
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
- updateEarliestDataChange(oldDate);
- updateEarliestDataChange(old.date);
- scheduleTemporaryBasalChange();
- return true;
- }
- return false;
- }
- // find by NS _id
- if (tempBasal._id != null) {
- QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", tempBasal._id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoTemporaryBasal().query(preparedQuery);
- if (trList.size() > 0) {
- old = trList.get(0);
- if (!old.isEqual(tempBasal)) {
- long oldDate = old.date;
- getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
- old.copyFrom(tempBasal);
- getDaoTemporaryBasal().create(old);
- openHumansUploader.enqueueTemporaryBasal(old);
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
- updateEarliestDataChange(oldDate);
- updateEarliestDataChange(old.date);
- scheduleTemporaryBasalChange();
- return true;
- }
- }
- }
- getDaoTemporaryBasal().create(tempBasal);
- openHumansUploader.enqueueTemporaryBasal(tempBasal);
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
- updateEarliestDataChange(tempBasal.date);
- scheduleTemporaryBasalChange();
- return true;
- }
- if (tempBasal.source == Source.USER) {
- getDaoTemporaryBasal().create(tempBasal);
- openHumansUploader.enqueueTemporaryBasal(tempBasal);
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
- updateEarliestDataChange(tempBasal.date);
- scheduleTemporaryBasalChange();
- return true;
- }
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return false;
- }
-
- public void delete(TemporaryBasal tempBasal) {
- try {
- getDaoTemporaryBasal().delete(tempBasal);
- openHumansUploader.enqueueTemporaryBasal(tempBasal, true);
- updateEarliestDataChange(tempBasal.date);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- scheduleTemporaryBasalChange();
- }
-
- public List getAllTemporaryBasals() {
- try {
- return getDaoTemporaryBasal().queryForAll();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return Collections.emptyList();
- }
-
- public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
- try {
- List tempbasals;
- QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
- queryBuilder.orderBy("date", ascending);
- Where where = queryBuilder.where();
- where.ge("date", mills);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- tempbasals = getDaoTemporaryBasal().query(preparedQuery);
- return tempbasals;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList();
- }
-
- public List getTemporaryBasalsDataFromTime(long from, long to, boolean ascending) {
- try {
- List tempbasals;
- QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
- queryBuilder.orderBy("date", ascending);
- Where where = queryBuilder.where();
- where.between("date", from, to);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- tempbasals = getDaoTemporaryBasal().query(preparedQuery);
- return tempbasals;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList();
- }
-
- private void scheduleTemporaryBasalChange() {
- class PostRunnable implements Runnable {
- public void run() {
- aapsLogger.debug(LTag.DATABASE, "Firing EventTempBasalChange");
- rxBus.send(new EventReloadTempBasalData());
- rxBus.send(new EventTempBasalChange());
- if (earliestDataChange != null)
- rxBus.send(new EventNewHistoryData(earliestDataChange));
- earliestDataChange = null;
- scheduledTemBasalsPost = null;
- }
- }
- // prepare task for execution in 1 sec
- // cancel waiting task to prevent sending multiple posts
- if (scheduledTemBasalsPost != null)
- scheduledTemBasalsPost.cancel(false);
- Runnable task = new PostRunnable();
- final int sec = 1;
- scheduledTemBasalsPost = tempBasalsWorker.schedule(task, sec, TimeUnit.SECONDS);
-
- }
-
- /*
- {
- "_id": "59232e1ddd032d04218dab00",
- "eventType": "Temp Basal",
- "duration": 60,
- "percent": -50,
- "created_at": "2017-05-22T18:29:57Z",
- "enteredBy": "AndroidAPS",
- "notes": "Basal Temp Start 50% 60.0 min",
- "NSCLIENT_ID": 1495477797863,
- "mills": 1495477797000,
- "mgdl": 194.5,
- "endmills": 1495481397000
- }
- */
-
- public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
- try {
- if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
- ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance())
- .source(Source.NIGHTSCOUT)
- .date(trJson.getLong("mills"))
- .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
- .durationInMinutes(trJson.getInt("duration"))
- .insulin(trJson.getDouble("originalExtendedAmount"))
- ._id(trJson.getString("_id"));
- // if faking found in NS, adapt AAPS to use it too
- if (!virtualPumpPlugin.getFakingStatus()) {
- virtualPumpPlugin.setFakingStatus(true);
- updateEarliestDataChange(0);
- scheduleTemporaryBasalChange();
- }
- createOrUpdate(extendedBolus);
- } else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
- ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance());
- extendedBolus.source = Source.NIGHTSCOUT;
- extendedBolus.date = trJson.getLong("mills");
- extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
- extendedBolus.durationInMinutes = 0;
- extendedBolus.insulin = 0;
- extendedBolus._id = trJson.getString("_id");
- // if faking found in NS, adapt AAPS to use it too
- if (!virtualPumpPlugin.getFakingStatus()) {
- virtualPumpPlugin.setFakingStatus(true);
- updateEarliestDataChange(0);
- scheduleTemporaryBasalChange();
- }
- createOrUpdate(extendedBolus);
- } else {
- TemporaryBasal tempBasal = new TemporaryBasal(StaticInjector.Companion.getInstance())
- .date(trJson.getLong("mills"))
- .source(Source.NIGHTSCOUT)
- .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
- if (trJson.has("duration")) {
- tempBasal.durationInMinutes = trJson.getInt("duration");
- }
- if (trJson.has("percent")) {
- tempBasal.percentRate = trJson.getInt("percent") + 100;
- tempBasal.isAbsolute = false;
- }
- if (trJson.has("absolute")) {
- tempBasal.absoluteRate = trJson.getDouble("absolute");
- tempBasal.isAbsolute = true;
- }
- tempBasal._id = trJson.getString("_id");
- createOrUpdate(tempBasal);
- }
- } catch (JSONException e) {
- aapsLogger.error("Unhandled exception: " + trJson.toString(), e);
- }
- }
-
- public void deleteTempBasalById(String _id) {
- TemporaryBasal stored = findTempBasalById(_id);
- if (stored != null) {
- aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
- delete(stored);
- updateEarliestDataChange(stored.date);
- scheduleTemporaryBasalChange();
- }
- }
-
- public TemporaryBasal findTempBasalById(String _id) {
- try {
- QueryBuilder queryBuilder = null;
- queryBuilder = getDaoTemporaryBasal().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", _id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = getDaoTemporaryBasal().query(preparedQuery);
-
- if (list.size() != 1) {
- return null;
- } else {
- return list.get(0);
- }
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
-
- public TemporaryBasal findTempBasalByPumpId(Long pumpId) {
- try {
- QueryBuilder queryBuilder = null;
- queryBuilder = getDaoTemporaryBasal().queryBuilder();
- queryBuilder.orderBy("date", false);
- Where where = queryBuilder.where();
- where.eq("pumpId", pumpId);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = getDaoTemporaryBasal().query(preparedQuery);
-
- if (list.size() > 0)
- return list.get(0);
- else
- return null;
-
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
-
- // ------------ ExtendedBolus handling ---------------
-
- public boolean createOrUpdate(ExtendedBolus extendedBolus) {
- try {
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
-
- ExtendedBolus old;
- extendedBolus.date = roundDateToSec(extendedBolus.date);
-
- if (extendedBolus.source == Source.PUMP) {
- // if pumpId == 0 do not check for existing pumpId
- // used with pumps without history
- // and insight where record as added first without pumpId
- // and then is record updated with pumpId
- if (extendedBolus.pumpId == 0) {
- getDaoExtendedBolus().createOrUpdate(extendedBolus);
- openHumansUploader.enqueueExtendedBolus(extendedBolus);
- } else {
- QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("pumpId", extendedBolus.pumpId);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoExtendedBolus().query(preparedQuery);
- if (trList.size() > 1) {
- aapsLogger.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId);
- return false;
- }
- getDaoExtendedBolus().createOrUpdate(extendedBolus);
- openHumansUploader.enqueueExtendedBolus(extendedBolus);
- }
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
- updateEarliestDataChange(extendedBolus.date);
- scheduleExtendedBolusChange();
- return true;
- }
- if (extendedBolus.source == Source.NIGHTSCOUT) {
- old = getDaoExtendedBolus().queryForId(extendedBolus.date);
- if (old != null) {
- if (!old.isEqual(extendedBolus)) {
- long oldDate = old.date;
- getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
- old.copyFrom(extendedBolus);
- getDaoExtendedBolus().create(old);
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log());
- openHumansUploader.enqueueExtendedBolus(old);
- updateEarliestDataChange(oldDate);
- updateEarliestDataChange(old.date);
- scheduleExtendedBolusChange();
- return true;
- }
- return false;
- }
- // find by NS _id
- if (extendedBolus._id != null) {
- QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", extendedBolus._id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoExtendedBolus().query(preparedQuery);
- if (trList.size() > 0) {
- old = trList.get(0);
- if (!old.isEqual(extendedBolus)) {
- long oldDate = old.date;
- getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
- old.copyFrom(extendedBolus);
- getDaoExtendedBolus().create(old);
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log());
- openHumansUploader.enqueueExtendedBolus(old);
- updateEarliestDataChange(oldDate);
- updateEarliestDataChange(old.date);
- scheduleExtendedBolusChange();
- return true;
- }
- }
- }
- getDaoExtendedBolus().create(extendedBolus);
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
- openHumansUploader.enqueueExtendedBolus(extendedBolus);
- updateEarliestDataChange(extendedBolus.date);
- scheduleExtendedBolusChange();
- return true;
- }
- if (extendedBolus.source == Source.USER) {
- getDaoExtendedBolus().create(extendedBolus);
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log());
- openHumansUploader.enqueueExtendedBolus(extendedBolus);
- updateEarliestDataChange(extendedBolus.date);
- scheduleExtendedBolusChange();
- return true;
- }
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return false;
- }
-
- public List getAllExtendedBoluses() {
- try {
- return getDaoExtendedBolus().queryForAll();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return Collections.emptyList();
- }
-
- public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
- try {
- return getDaoExtendedBolus().queryBuilder()
- .where().eq("pumpId", pumpId)
- .queryForFirst();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
- public void delete(ExtendedBolus extendedBolus) {
- try {
- getDaoExtendedBolus().delete(extendedBolus);
- openHumansUploader.enqueueExtendedBolus(extendedBolus, true);
- updateEarliestDataChange(extendedBolus.date);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- scheduleExtendedBolusChange();
- }
-
- public List getExtendedBolusDataFromTime(long mills, boolean ascending) {
- try {
- List extendedBoluses;
- QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
- queryBuilder.orderBy("date", ascending);
- Where where = queryBuilder.where();
- where.ge("date", mills);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
- return extendedBoluses;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList();
- }
-
- public List getExtendedBolusDataFromTime(long from, long to, boolean ascending) {
- try {
- List extendedBoluses;
- QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder();
- queryBuilder.orderBy("date", ascending);
- Where where = queryBuilder.where();
- where.between("date", from, to);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- extendedBoluses = getDaoExtendedBolus().query(preparedQuery);
- return extendedBoluses;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList();
- }
-
- public void deleteExtendedBolusById(String _id) {
- ExtendedBolus stored = findExtendedBolusById(_id);
- if (stored != null) {
- aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
- delete(stored);
- updateEarliestDataChange(stored.date);
- scheduleExtendedBolusChange();
- }
- }
-
- public ExtendedBolus findExtendedBolusById(String _id) {
- try {
- QueryBuilder queryBuilder = null;
- queryBuilder = getDaoExtendedBolus().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", _id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = getDaoExtendedBolus().query(preparedQuery);
-
- if (list.size() == 1) {
- return list.get(0);
- } else {
- return null;
- }
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
- /*
-{
- "_id": "5924898d577eb0880e355337",
- "eventType": "Combo Bolus",
- "duration": 120,
- "splitNow": 0,
- "splitExt": 100,
- "enteredinsulin": 1,
- "relative": 1,
- "created_at": "2017-05-23T19:12:14Z",
- "enteredBy": "AndroidAPS",
- "NSCLIENT_ID": 1495566734628,
- "mills": 1495566734000,
- "mgdl": 106
-}
- */
-
- public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
- ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(StaticInjector.Companion.getInstance(), json);
- if (extendedBolus != null)
- createOrUpdate(extendedBolus);
- }
-
- private void scheduleExtendedBolusChange() {
- class PostRunnable implements Runnable {
- public void run() {
- aapsLogger.debug(LTag.DATABASE, "Firing EventExtendedBolusChange");
- rxBus.send(new EventReloadTreatmentData(new EventExtendedBolusChange()));
- if (earliestDataChange != null)
- rxBus.send(new EventNewHistoryData(earliestDataChange));
- earliestDataChange = null;
- scheduledExtendedBolusPost = null;
- }
- }
- // prepare task for execution in 1 sec
- // cancel waiting task to prevent sending multiple posts
- if (scheduledExtendedBolusPost != null)
- scheduledExtendedBolusPost.cancel(false);
- Runnable task = new PostRunnable();
- final int sec = 1;
- scheduledExtendedBolusPost = extendedBolusWorker.schedule(task, sec, TimeUnit.SECONDS);
-
- }
-
- // ---------------- ProfileSwitch handling ---------------
-
- public List getProfileSwitchData(long from, boolean ascending) {
- try {
- Dao daoProfileSwitch = getDaoProfileSwitch();
- List profileSwitches;
- QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
- queryBuilder.orderBy("date", ascending);
- queryBuilder.limit(100L);
- Where where = queryBuilder.where();
- where.ge("date", from);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- profileSwitches = daoProfileSwitch.query(preparedQuery);
- //add last one without duration
- ProfileSwitch last = getLastProfileSwitchWithoutDuration();
- if (last != null) {
- if (!isInList(profileSwitches, last))
- profileSwitches.add(last);
- }
- return profileSwitches;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList<>();
- }
-
- boolean isInList(List profileSwitches, ProfileSwitch last) {
- for (ProfileSwitch ps : profileSwitches) {
- if (ps.isEqual(last)) return true;
- }
- return false;
- }
-
- public List getAllProfileSwitches() {
- try {
- return getDaoProfileSwitch().queryForAll();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return Collections.emptyList();
- }
-
- @Nullable
- private ProfileSwitch getLastProfileSwitchWithoutDuration() {
- try {
- Dao daoProfileSwitch = getDaoProfileSwitch();
- List profileSwitches;
- QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
- queryBuilder.orderBy("date", false);
- queryBuilder.limit(1L);
- Where where = queryBuilder.where();
- where.eq("durationInMinutes", 0);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- profileSwitches = daoProfileSwitch.query(preparedQuery);
- if (profileSwitches.size() > 0)
- return profileSwitches.get(0);
- else
- return null;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
- public List getProfileSwitchEventsFromTime(long mills, boolean ascending) {
- try {
- Dao daoProfileSwitch = getDaoProfileSwitch();
- List profileSwitches;
- QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
- queryBuilder.orderBy("date", ascending);
- queryBuilder.limit(100L);
- Where where = queryBuilder.where();
- where.ge("date", mills);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- profileSwitches = daoProfileSwitch.query(preparedQuery);
- return profileSwitches;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList<>();
- }
-
- public List getProfileSwitchEventsFromTime(long from, long to, boolean ascending) {
- try {
- Dao daoProfileSwitch = getDaoProfileSwitch();
- List profileSwitches;
- QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
- queryBuilder.orderBy("date", ascending);
- queryBuilder.limit(100L);
- Where where = queryBuilder.where();
- where.between("date", from, to);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- profileSwitches = daoProfileSwitch.query(preparedQuery);
- return profileSwitches;
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return new ArrayList<>();
- }
-
- public boolean createOrUpdate(ProfileSwitch profileSwitch) {
- try {
- ProfileSwitch old;
- profileSwitch.date = roundDateToSec(profileSwitch.date);
-
- if (profileSwitch.source == Source.NIGHTSCOUT) {
- old = getDaoProfileSwitch().queryForId(profileSwitch.date);
- if (old != null) {
- if (!old.isEqual(profileSwitch)) {
- profileSwitch.source = old.source;
- profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
- getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
- getDaoProfileSwitch().create(profileSwitch);
- aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
- openHumansUploader.enqueueProfileSwitch(profileSwitch);
- scheduleProfileSwitchChange();
- return true;
- }
- return false;
- }
- // find by NS _id
- if (profileSwitch._id != null) {
- QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", profileSwitch._id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List trList = getDaoProfileSwitch().query(preparedQuery);
- if (trList.size() > 0) {
- old = trList.get(0);
- if (!old.isEqual(profileSwitch)) {
- getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
- old.copyFrom(profileSwitch);
- getDaoProfileSwitch().create(old);
- aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
- openHumansUploader.enqueueProfileSwitch(old);
- scheduleProfileSwitchChange();
- return true;
- }
- }
- }
- // look for already added percentage from NS
- profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
- getDaoProfileSwitch().create(profileSwitch);
- aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
- openHumansUploader.enqueueProfileSwitch(profileSwitch);
- scheduleProfileSwitchChange();
- return true;
- }
- if (profileSwitch.source == Source.USER) {
- getDaoProfileSwitch().create(profileSwitch);
- aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
- openHumansUploader.enqueueProfileSwitch(profileSwitch);
- scheduleProfileSwitchChange();
- return true;
- }
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return false;
- }
-
- public void delete(ProfileSwitch profileSwitch) {
- try {
- getDaoProfileSwitch().delete(profileSwitch);
- openHumansUploader.enqueueProfileSwitch(profileSwitch, true);
- scheduleProfileSwitchChange();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- private void scheduleProfileSwitchChange() {
- class PostRunnable implements Runnable {
- public void run() {
- aapsLogger.debug(LTag.DATABASE, "Firing EventProfileNeedsUpdate");
- rxBus.send(new EventReloadProfileSwitchData());
- rxBus.send(new EventProfileNeedsUpdate());
- scheduledProfileSwitchEventPost = null;
- }
- }
- // prepare task for execution in 1 sec
- // cancel waiting task to prevent sending multiple posts
- if (scheduledProfileSwitchEventPost != null)
- scheduledProfileSwitchEventPost.cancel(false);
- Runnable task = new PostRunnable();
- final int sec = 1;
- scheduledProfileSwitchEventPost = profileSwitchEventWorker.schedule(task, sec, TimeUnit.SECONDS);
-
- }
-
- /*
-{
- "_id":"592fa43ed97496a80da913d2",
- "created_at":"2017-06-01T05:20:06Z",
- "eventType":"Profile Switch",
- "profile":"2016 +30%",
- "units":"mmol",
- "enteredBy":"sony",
- "NSCLIENT_ID":1496294454309,
-}
- */
-
- public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) {
- try {
- ProfileSwitch profileSwitch = new ProfileSwitch(StaticInjector.Companion.getInstance());
- profileSwitch.date = trJson.getLong("mills");
- if (trJson.has("duration"))
- profileSwitch.durationInMinutes = trJson.getInt("duration");
- profileSwitch._id = trJson.getString("_id");
- profileSwitch.profileName = trJson.getString("profile");
- profileSwitch.isCPP = trJson.has("CircadianPercentageProfile");
- profileSwitch.source = Source.NIGHTSCOUT;
- if (trJson.has("timeshift"))
- profileSwitch.timeshift = trJson.getInt("timeshift");
- if (trJson.has("percentage"))
- profileSwitch.percentage = trJson.getInt("percentage");
- if (trJson.has("profileJson"))
- profileSwitch.profileJson = trJson.getString("profileJson");
- else {
- ProfileInterface profileInterface = activePlugin.getActiveProfileInterface();
- ProfileStore store = profileInterface.getProfile();
- if (store != null) {
- Profile profile = store.getSpecificProfile(profileSwitch.profileName);
- if (profile != null) {
- profileSwitch.profileJson = profile.getData().toString();
- aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store");
- // Update data in NS
- nsUpload.updateProfileSwitch(profileSwitch);
- } else {
- aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
- return;
- }
- } else {
- aapsLogger.debug(LTag.DATABASE, "Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
- return;
- }
- }
- if (trJson.has("profilePlugin"))
- profileSwitch.profilePlugin = trJson.getString("profilePlugin");
- createOrUpdate(profileSwitch);
- } catch (JSONException e) {
- aapsLogger.error("Unhandled exception: " + trJson.toString(), e);
- }
- }
-
- public void deleteProfileSwitchById(String _id) {
- ProfileSwitch stored = findProfileSwitchById(_id);
- if (stored != null) {
- aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
- delete(stored);
- scheduleProfileSwitchChange();
- }
- }
-
- public ProfileSwitch findProfileSwitchById(String _id) {
- try {
- QueryBuilder queryBuilder = getDaoProfileSwitch().queryBuilder();
- Where where = queryBuilder.where();
- where.eq("_id", _id);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- List list = getDaoProfileSwitch().query(preparedQuery);
-
- if (list.size() == 1) {
- return list.get(0);
- } else {
- return null;
- }
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
- // ---------------- Insight history handling ---------------
-
- public void createOrUpdate(InsightHistoryOffset offset) {
- try {
- getDaoInsightHistoryOffset().createOrUpdate(offset);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) {
- try {
- return getDaoInsightHistoryOffset().queryForId(pumpSerial);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
- public void createOrUpdate(InsightBolusID bolusID) {
- try {
- getDaoInsightBolusID().createOrUpdate(bolusID);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) {
- try {
- return getDaoInsightBolusID().queryBuilder()
- .where().eq("pumpSerial", pumpSerial)
- .and().eq("bolusID", bolusID)
- .and().between("timestamp", timestamp - 259200000, timestamp + 259200000)
- .queryForFirst();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
- public void createOrUpdate(InsightPumpID pumpID) {
- try {
- getDaoInsightPumpID().createOrUpdate(pumpID);
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- }
-
- public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) {
- try {
- return getDaoInsightPumpID().queryBuilder()
- .orderBy("timestamp", false)
- .where().eq("pumpSerial", pumpSerial)
- .and().in("eventType", "PumpStopped", "PumpPaused")
- .and().lt("timestamp", before)
- .queryForFirst();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return null;
- }
-
// ---------------- Food handling ---------------
// ---------------- PodHistory handling ---------------
@@ -1493,16 +293,4 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
return 0L;
}
-
- public long getCountOfAllRows() {
- try {
- return getDaoExtendedBolus().countOf()
- + getDaoProfileSwitch().countOf()
- + getDaoTDD().countOf()
- + getDaoTemporaryBasal().countOf();
- } catch (SQLException e) {
- aapsLogger.error("Unhandled exception", e);
- }
- return 0L;
- }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java
index 6587fb6371..da0b2479cf 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java
@@ -1,12 +1,10 @@
package info.nightscout.androidaps.db;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import com.j256.ormlite.dao.CloseableIterator;
-import org.jetbrains.annotations.Nullable;
-import org.json.JSONObject;
-
import java.sql.SQLException;
import java.util.List;
@@ -16,74 +14,31 @@ import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
+@Deprecated
@Singleton
public class DatabaseHelperProvider implements DatabaseHelperInterface {
@Inject DatabaseHelperProvider() {
}
- @Override public void createOrUpdate(@NonNull DanaRHistoryRecord record) {
- MainApp.Companion.getDbHelper().createOrUpdate(record);
- }
-
@Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) {
MainApp.Companion.getDbHelper().createOrUpdate(record);
}
- @NonNull @Override public List getDanaRHistoryRecordsByType(byte type) {
- return MainApp.Companion.getDbHelper().getDanaRHistoryRecordsByType(type);
- }
-
- @NonNull @Override public List getTDDs() {
- return MainApp.Companion.getDbHelper().getTDDs();
- }
-
- @Override public long size(@NonNull String table) {
- return MainApp.Companion.getDbHelper().size(table);
- }
-
- @Override public void create(@NonNull DbRequest record) {
- try {
- MainApp.Companion.getDbHelper().create(record);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- @Override public void deleteAllDbRequests() {
- MainApp.Companion.getDbHelper().deleteAllDbRequests();
- }
-
- @Override public int deleteDbRequest(@NonNull String id) {
- return MainApp.Companion.getDbHelper().deleteDbRequest(id);
- }
-
- @Override public void deleteDbRequestbyMongoId(@NonNull String action, @NonNull String _id) {
- MainApp.Companion.getDbHelper().deleteDbRequestbyMongoId(action, _id);
- }
-
- @NonNull @Override public CloseableIterator getDbRequestIterator() {
- return MainApp.Companion.getDbHelper().getDbRequestIterator();
- }
-
- @Override public long roundDateToSec(long date) {
- return MainApp.Companion.getDbHelper().roundDateToSec(date);
- }
-
- @Override public void createOrUpdateTDD(@NonNull TDD record) {
- MainApp.Companion.getDbHelper().createOrUpdateTDD(record);
- }
-
@Override public boolean createOrUpdate(@NonNull TemporaryBasal tempBasal) {
- return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal);
+// return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal);
+ return false;
}
- @NonNull @Override public TemporaryBasal findTempBasalByPumpId(long id) {
- return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id);
+ @Nullable @Override public TemporaryBasal findTempBasalByPumpId(long id) {
+// return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id);
+ return null;
}
+ @Deprecated
@NonNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
- return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending);
+// return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending);
+ return null;
}
@NonNull @Override public List getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) {
@@ -94,84 +49,13 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId);
}
- @NonNull @Override public List getTDDsForLastXDays(int days) {
- return MainApp.Companion.getDbHelper().getTDDsForLastXDays(days);
- }
-
- @NonNull @Override public List getProfileSwitchData(long from, boolean ascending) {
- return MainApp.Companion.getDbHelper().getProfileSwitchData(from, ascending);
- }
-
- @Override public void createOrUpdate(@NonNull InsightBolusID record) {
- MainApp.Companion.getDbHelper().createOrUpdate(record);
- }
-
- @Override public void createOrUpdate(@NonNull InsightPumpID record) {
- MainApp.Companion.getDbHelper().createOrUpdate(record);
- }
-
- @Override public void createOrUpdate(@NonNull InsightHistoryOffset record) {
- MainApp.Companion.getDbHelper().createOrUpdate(record);
- }
-
@Override public void delete(@NonNull ExtendedBolus extendedBolus) {
- MainApp.Companion.getDbHelper().delete(extendedBolus);
+// MainApp.Companion.getDbHelper().delete(extendedBolus);
}
@Nullable @Override public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
- return MainApp.Companion.getDbHelper().getExtendedBolusByPumpId(pumpId);
- }
-
- @Nullable @Override public InsightBolusID getInsightBolusID(@NonNull String pumpSerial, int bolusID, long timestamp) {
- return MainApp.Companion.getDbHelper().getInsightBolusID(pumpSerial, bolusID, timestamp);
- }
-
- @Nullable @Override public InsightHistoryOffset getInsightHistoryOffset(@NonNull String pumpSerial) {
- return MainApp.Companion.getDbHelper().getInsightHistoryOffset(pumpSerial);
- }
-
- @Nullable @Override public InsightPumpID getPumpStoppedEvent(@NonNull String pumpSerial, long before) {
- return MainApp.Companion.getDbHelper().getPumpStoppedEvent(pumpSerial, before);
- }
-
- @Override public boolean createOrUpdate(@NonNull ExtendedBolus extendedBolus) {
- return MainApp.Companion.getDbHelper().createOrUpdate(extendedBolus);
- }
-
- @Override public void createOrUpdate(@NonNull ProfileSwitch profileSwitch) {
- MainApp.Companion.getDbHelper().createOrUpdate(profileSwitch);
- }
-
- @Override public void delete(@NonNull TemporaryBasal tempBasal) {
- MainApp.Companion.getDbHelper().delete(tempBasal);
- }
-
- @NonNull @Override public List getExtendedBolusDataFromTime(long mills, boolean ascending) {
- return MainApp.Companion.getDbHelper().getExtendedBolusDataFromTime(mills, ascending);
- }
-
- @Override public void deleteTempBasalById(@NonNull String _id) {
- MainApp.Companion.getDbHelper().deleteTempBasalById(_id);
- }
-
- @Override public void deleteExtendedBolusById(@NonNull String _id) {
- MainApp.Companion.getDbHelper().deleteExtendedBolusById(_id);
- }
-
- @Override public void deleteProfileSwitchById(@NonNull String _id) {
- MainApp.Companion.getDbHelper().deleteProfileSwitchById(_id);
- }
-
- @Override public void createTempBasalFromJsonIfNotExists(@NonNull JSONObject json) {
- MainApp.Companion.getDbHelper().createTempBasalFromJsonIfNotExists(json);
- }
-
- @Override public void createExtendedBolusFromJsonIfNotExists(@NonNull JSONObject json) {
- MainApp.Companion.getDbHelper().createExtendedBolusFromJsonIfNotExists(json);
- }
-
- @Override public void createProfileSwitchFromJsonIfNotExists(@NonNull JSONObject trJson) {
- MainApp.Companion.getDbHelper().createProfileSwitchFromJsonIfNotExists(trJson);
+// return MainApp.Companion.getDbHelper().getExtendedBolusByPumpId(pumpId);
+ return null;
}
@Override public void resetDatabases() {
@@ -182,42 +66,10 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
MainApp.Companion.getDbHelper().createOrUpdate(record);
}
- @Override public void delete(@NonNull ProfileSwitch profileSwitch) {
- MainApp.Companion.getDbHelper().delete(profileSwitch);
- }
-
- @NonNull @Override public List getProfileSwitchEventsFromTime(long from, long to, boolean ascending) {
- return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(from, to, ascending);
- }
-
- @NonNull @Override public List getProfileSwitchEventsFromTime(long mills, boolean ascending) {
- return MainApp.Companion.getDbHelper().getProfileSwitchEventsFromTime(mills, ascending);
- }
-
- @NonNull @Override public List getAllExtendedBoluses() {
- return MainApp.Companion.getDbHelper().getAllExtendedBoluses();
- }
-
- @NonNull @Override public List getAllProfileSwitches() {
- return MainApp.Companion.getDbHelper().getAllProfileSwitches();
- }
-
- @NonNull @Override public List getAllTDDs() {
- return MainApp.Companion.getDbHelper().getAllTDDs();
- }
-
- @NonNull @Override public List getAllTemporaryBasals() {
- return MainApp.Companion.getDbHelper().getAllTemporaryBasals();
- }
-
@NonNull @Override public List getAllOHQueueItems(long maxEntries) {
return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries);
}
- @Override public void resetProfileSwitch() {
- MainApp.Companion.getDbHelper().resetProfileSwitch();
- }
-
@Override public long getOHQueueSize() {
return MainApp.Companion.getDbHelper().getOHQueueSize();
}
@@ -226,10 +78,6 @@ public class DatabaseHelperProvider implements DatabaseHelperInterface {
MainApp.Companion.getDbHelper().clearOpenHumansQueue();
}
- @Override public long getCountOfAllRows() {
- return MainApp.Companion.getDbHelper().getCountOfAllRows();
- }
-
@Override public void removeAllOHQueueItemsWithIdSmallerThan(long id) {
MainApp.Companion.getDbHelper().removeAllOHQueueItemsWithIdSmallerThan(id);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt
index d431be7a6c..1421d586ed 100644
--- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt
+++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt
@@ -7,12 +7,14 @@ import dagger.android.AndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.automation.di.AutomationModule
import info.nightscout.androidaps.combo.di.ComboModule
-import info.nightscout.androidaps.core.di.CoreModule
+import info.nightscout.androidaps.dana.di.DanaHistoryModule
+import info.nightscout.androidaps.di.CoreModule
import info.nightscout.androidaps.dana.di.DanaModule
import info.nightscout.androidaps.danar.di.DanaRModule
import info.nightscout.androidaps.danars.di.DanaRSModule
-import info.nightscout.androidaps.danars.di.InsightModule
import info.nightscout.androidaps.database.DatabaseModule
+import info.nightscout.androidaps.insight.di.InsightDatabaseModule
+import info.nightscout.androidaps.insight.di.InsightModule
import info.nightscout.androidaps.plugins.pump.common.di.RileyLinkModule
import info.nightscout.androidaps.plugins.pump.medtronic.di.MedtronicModule
import info.nightscout.androidaps.plugins.pump.omnipod.eros.dagger.OmnipodErosModule
@@ -45,10 +47,12 @@ import javax.inject.Singleton
UIModule::class,
CoreModule::class,
DanaModule::class,
+ DanaHistoryModule::class,
DanaRModule::class,
DanaRSModule::class,
ComboModule::class,
InsightModule::class,
+ InsightDatabaseModule::class,
WorkersModule::class,
OHUploaderModule::class
]
diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt
index c18c1128a3..30037c3948 100644
--- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt
+++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt
@@ -6,45 +6,51 @@ import dagger.Lazy
import dagger.Module
import dagger.Provides
import dagger.android.HasAndroidInjector
-import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.db.DatabaseHelperProvider
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
-import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
-import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs
-import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation
+import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefsImpl
+import info.nightscout.androidaps.plugins.general.nsclient.DataSyncSelectorImplementation
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
+import info.nightscout.androidaps.plugins.pump.PumpSyncImplementation
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.CommandQueue
-import info.nightscout.androidaps.utils.androidNotification.NotificationHolder
-import info.nightscout.androidaps.utils.resources.IconsProvider
+import info.nightscout.androidaps.utils.DateUtil
+import info.nightscout.androidaps.utils.androidNotification.NotificationHolderImpl
+import info.nightscout.androidaps.utils.buildHelper.ConfigImpl
+import info.nightscout.androidaps.utils.resources.IconsProviderImplementation
+import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.storage.FileStorage
import info.nightscout.androidaps.utils.storage.Storage
import javax.inject.Singleton
+
+@Suppress("unused")
@Module(includes = [
AppModule.AppBindings::class
])
open class AppModule {
@Provides
- fun providesPlugins(configInterface: ConfigInterface,
+ fun providesPlugins(config: Config,
@PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>,
@PluginsModule.PumpDriver pumpDrivers: Lazy