Merge remote-tracking branch 'upstream/dev' into omnipod_eros_dev_merge_from_upstream

This commit is contained in:
Bart Sopers 2020-08-16 12:37:28 +02:00
commit a3cb8ff648
1960 changed files with 32130 additions and 22953 deletions

1
.gitignore vendored
View file

@ -8,7 +8,6 @@
build/ build/
.idea/* .idea/*
!.idea/codeStyles/ !.idea/codeStyles/
app/src/main/jniLibs
full/ full/
debug/ debug/
release/ release/

View file

@ -8,7 +8,7 @@ android:
components: components:
- platform-tools - platform-tools
- tools - tools
- build-tools-28.0.3 - build-tools-29.0.2
- android-28 - android-28
- extra-google-m2repository - extra-google-m2repository
- extra-android-m2repository - extra-android-m2repository

View file

@ -1,6 +1,6 @@
# AndroidAPS # AndroidAPS
* Check the wiki: http://wiki.androidaps.org * Check the wiki: https://androidaps.readthedocs.io
* Everyone whos been looping with AndroidAPS needs to fill out the form after 3 days of looping https://docs.google.com/forms/d/14KcMjlINPMJHVt28MDRupa4sz4DDIooI4SrW0P3HSN8/viewform?c=0&w=1 * Everyone whos been looping with AndroidAPS needs to fill out the form after 3 days of looping https://docs.google.com/forms/d/14KcMjlINPMJHVt28MDRupa4sz4DDIooI4SrW0P3HSN8/viewform?c=0&w=1
[![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
@ -11,4 +11,4 @@
dev: [![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/dev/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS) dev: [![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/dev/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS)
[![Donate via PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y4LHGJJESAVB8) ![BTC](https://bitit.io/assets/coins/icon-btc-1e5a37bc0eb730ac83130d7aa859052bd4b53ac3f86f99966627801f7b0410be.svg) 3KawK8aQe48478s6fxJ8Ms6VTWkwjgr9f2

View file

@ -1,13 +1,12 @@
buildscript { buildscript {
repositories { repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter() jcenter()
maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2
} }
dependencies { dependencies {
classpath 'io.fabric.tools:gradle:1.+' //classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4'
classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4' classpath 'com.hiya:jacoco-android:0.2'
classpath 'de.undercouch:gradle-download-task:3.4.3'
} }
} }
apply plugin: 'com.android.application' apply plugin: 'com.android.application'
@ -15,26 +14,23 @@ apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-kapt'
apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.gms.google-services'
apply plugin: 'io.fabric' //apply plugin: 'jacoco-android'
apply plugin: 'jacoco-android' apply plugin: 'com.hiya.jacoco-android'
apply plugin: 'de.undercouch.download' apply plugin: 'com.google.firebase.crashlytics'
jacoco { jacoco {
toolVersion = "0.8.3" toolVersion = "0.8.3"
} }
ext { ext {
ormLiteVersion = "4.46"
powermockVersion = "1.7.3" powermockVersion = "1.7.3"
dexmakerVersion = "1.2" dexmakerVersion = "1.2"
retrofit2Version = '2.8.1' retrofit2Version = '2.9.0'
okhttp3Version = '4.6.0' okhttp3Version = '4.7.2'
} }
repositories { repositories {
maven { url 'https://maven.fabric.io/public' }
jcenter { url "https://jcenter.bintray.com/" } jcenter { url "https://jcenter.bintray.com/" }
mavenCentral() mavenCentral()
google() google()
@ -126,7 +122,7 @@ android {
ndkVersion "21.1.6352462" ndkVersion "21.1.6352462"
defaultConfig { defaultConfig {
minSdkVersion 23 minSdkVersion 24
targetSdkVersion 28 targetSdkVersion 28
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
@ -139,9 +135,9 @@ android {
// if you change minSdkVersion to less than 11, you need to change executeTask for wear // if you change minSdkVersion to less than 11, you need to change executeTask for wear
// OMNIPOD: Keep track of what commit from the main repository we're on, these fields aren't actually used anywhere // OMNIPOD: Keep track of what commit from the main repository we're on, these fields aren't actually used anywhere
buildConfigField "String", "DEV_VERSION", '"2.6.5-dev"' buildConfigField "String", "DEV_VERSION", '"2.6.7-dev"'
buildConfigField "String", "DEV_VERSION_COMMIT", '"cf291b3adc2a8df06fd99220b59b500298c8e56f"' buildConfigField "String", "DEV_VERSION_COMMIT", '"65c8cc98804cfc366239ad2bedb2dd98e3e4f3c2"'
buildConfigField "String", "DEV_VERSION_COMMIT_DATE", '"6.5.2020"' // 6th May buildConfigField "String", "DEV_VERSION_COMMIT_DATE", '"16.8.2020"' // 16th of August
ndk { ndk {
moduleName "BleCommandUtil" moduleName "BleCommandUtil"
@ -249,16 +245,18 @@ dependencies {
wearApp project(':wear') wearApp project(':wear')
implementation project(':core') implementation project(':core')
implementation project(':dana')
implementation project(':danars')
implementation project(':danar')
implementation project(':rileylink')
implementation project(':medtronic')
implementation fileTree(include: ['*.jar'], dir: 'libs') implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.google.android.gms:play-services-wearable:17.0.0' implementation 'com.google.android.gms:play-services-wearable:17.0.0'
implementation "com.google.android.gms:play-services-location:17.0.0" implementation "com.google.android.gms:play-services-location:17.0.0"
implementation 'com.google.firebase:firebase-core:17.4.0' implementation 'com.google.firebase:firebase-core:17.4.3'
implementation 'com.google.firebase:firebase-auth:19.3.1' implementation 'com.google.firebase:firebase-auth:19.3.1'
implementation 'com.google.firebase:firebase-database:19.3.0' implementation 'com.google.firebase:firebase-database:19.3.1'
implementation('com.crashlytics.sdk.android:crashlytics:2.10.1@aar') {
transitive = true;
}
implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.legacy:legacy-support-v13:1.0.0' implementation 'androidx.legacy:legacy-support-v13:1.0.0'
@ -269,12 +267,12 @@ dependencies {
implementation 'androidx.gridlayout:gridlayout:1.0.0' implementation 'androidx.gridlayout:gridlayout:1.0.0'
implementation 'androidx.percentlayout:percentlayout:1.0.0' implementation 'androidx.percentlayout:percentlayout:1.0.0'
implementation "androidx.preference:preference-ktx:1.1.1" implementation "androidx.preference:preference-ktx:1.1.1"
implementation "androidx.activity:activity:${activityVersion}"
implementation "androidx.activity:activity-ktx:${activityVersion}" implementation "androidx.activity:activity-ktx:${activityVersion}"
implementation "androidx.fragment:fragment:${fragmentVersion}"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0' implementation 'com.google.android.material:material:1.1.0'
implementation 'com.wdullaer:materialdatetimepicker:4.2.3'
implementation "io.reactivex.rxjava2:rxandroid:2.1.1" implementation "io.reactivex.rxjava2:rxandroid:${rxandroid_version}"
implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}" implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}"
implementation "com.j256.ormlite:ormlite-android:${ormLiteVersion}" implementation "com.j256.ormlite:ormlite-android:${ormLiteVersion}"
@ -286,10 +284,9 @@ dependencies {
// Graphview cannot be upgraded // Graphview cannot be upgraded
implementation "com.jjoe64:graphview:4.0.1" implementation "com.jjoe64:graphview:4.0.1"
implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2" implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.madgag.spongycastle:core:1.58.0.0' implementation 'com.madgag.spongycastle:core:1.58.0.0'
// Omnipod wizard
implementation(name: "com.atech-software.android.library.wizardpager-1.1.4", ext: "aar") implementation(name: "com.atech-software.android.library.wizardpager-1.1.4", ext: "aar")
implementation("com.google.android:flexbox:0.3.0") { implementation("com.google.android:flexbox:0.3.0") {
exclude group: "com.android.support" exclude group: "com.android.support"
} }
@ -313,7 +310,7 @@ dependencies {
implementation 'com.eatthepath:java-otp:0.2.0' implementation 'com.eatthepath:java-otp:0.2.0'
testImplementation "junit:junit:4.13" testImplementation "junit:junit:4.13"
testImplementation "org.json:json:20190722" testImplementation 'org.json:json:20200518'
testImplementation "org.mockito:mockito-core:2.8.47" testImplementation "org.mockito:mockito-core:2.8.47"
testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}" testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}"
testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}" testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}"
@ -362,30 +359,6 @@ dependencies {
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
} }
task downloadZipFile(type: Download) {
src 'https://github.com/MilosKozak/danars-support-lib/archive/master.zip'
dest new File(buildDir, 'danars.zip')
}
task downloadAndUnzipFile(dependsOn: downloadZipFile, type: Copy) {
from zipTree(downloadZipFile.dest)
def outputDir = file("${buildDir}/unpacked/dist")
into outputDir
}
task copyLibs(dependsOn: downloadAndUnzipFile, type: Copy) {
def src = file("${buildDir}/unpacked/dist/danars-support-lib-master")
def target = file("src/main/jniLibs/")
from src
into target
}
task full_clean(type: Delete) {
delete file("src/main/jniLibs")
}
/* /*
// Run 'adb' shell command to clear application data of main app for 'debug' variant // Run 'adb' shell command to clear application data of main app for 'debug' variant
task clearMainAppData(type: Exec) { task clearMainAppData(type: Exec) {
@ -417,8 +390,6 @@ tasks.whenTaskAdded { task ->
} }
} }
*/ */
clean.dependsOn full_clean
preBuild.dependsOn copyLibs
printf('--------------\n') printf('--------------\n')
printf('isMaster: %s\n', isMaster().toString()) printf('isMaster: %s\n', isMaster().toString())

View file

@ -8,16 +8,15 @@ import androidx.test.rule.GrantPermissionRule
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin
import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.source.RandomBgPlugin import info.nightscout.androidaps.plugins.source.RandomBgPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
@ -30,7 +29,6 @@ import org.junit.Before
import org.junit.Rule import org.junit.Rule
import org.junit.Test import org.junit.Test
import org.junit.runner.RunWith import org.junit.runner.RunWith
import org.slf4j.LoggerFactory
import javax.inject.Inject import javax.inject.Inject
@LargeTest @LargeTest
@ -44,7 +42,7 @@ class RealPumpTest {
private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}"
@Inject lateinit var pump : DanaRv2Plugin @Inject lateinit var pump : info.nightscout.androidaps.danaRv2.DanaRv2Plugin
@Inject lateinit var randomBgPlugin :RandomBgPlugin @Inject lateinit var randomBgPlugin :RandomBgPlugin
@Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction

View file

@ -58,15 +58,6 @@
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".activities.PreferencesActivity" /> <activity android:name=".activities.PreferencesActivity" />
<activity
android:name=".activities.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".activities.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".plugins.pump.danaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.pump.danaR.activities.DanaRUserOptionsActivity" />
<activity android:name=".activities.TDDStatsActivity" />
<activity android:name=".plugins.general.overview.activities.QuickWizardListActivity"> <activity android:name=".plugins.general.overview.activities.QuickWizardListActivity">
<intent-filter> <intent-filter>
<action android:name="info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity" /> <action android:name="info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity" />
@ -74,17 +65,11 @@
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".plugins.pump.danaRS.activities.BLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpDanaRS.activities.BLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".plugins.pump.danaRS.activities.PairingHelperActivity" />
<activity android:name=".plugins.general.maintenance.activities.PrefImportListActivity" /> <activity android:name=".plugins.general.maintenance.activities.PrefImportListActivity" />
<activity android:name=".historyBrowser.HistoryBrowseActivity" /> <activity android:name=".historyBrowser.HistoryBrowseActivity" />
<activity android:name=".activities.SurveyActivity" /> <activity android:name=".activities.SurveyActivity" />
<activity android:name=".activities.ProfileHelperActivity"
android:theme="@style/ProfileHelperAppTheme" />
<activity android:name=".activities.StatsActivity" /> <activity android:name=".activities.StatsActivity" />
<!-- Receive new BG readings from other local apps --> <!-- Receive new BG readings from other local apps -->
@ -122,6 +107,9 @@
<!-- Receiver keepalive, scheduled every 30 min --> <!-- Receiver keepalive, scheduled every 30 min -->
<receiver android:name=".receivers.KeepAliveReceiver" /> <receiver android:name=".receivers.KeepAliveReceiver" />
<!-- Receive ignore 5m, 15m, 30m requests for carb notifications -->
<receiver android:name=".plugins.aps.loop.CarbSuggestionReceiver"></receiver>
<!-- Auto start --> <!-- Auto start -->
<receiver <receiver
android:name=".receivers.AutoStartReceiver" android:name=".receivers.AutoStartReceiver"
@ -149,22 +137,6 @@
<service <service
android:name=".services.LocationService" android:name=".services.LocationService"
android:exported="false" /> android:exported="false" />
<service
android:name=".plugins.pump.danaR.services.DanaRExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.pump.danaRKorean.services.DanaRKoreanExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.pump.danaRv2.services.DanaRv2ExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.pump.danaRS.services.DanaRSService"
android:enabled="true"
android:exported="true" />
<service <service
android:name=".plugins.general.wear.wearintegration.WatchUpdaterService" android:name=".plugins.general.wear.wearintegration.WatchUpdaterService"
android:exported="true"> android:exported="true">
@ -286,16 +258,7 @@
android:name=".plugins.pump.medtronic.service.RileyLinkMedtronicService" android:name=".plugins.pump.medtronic.service.RileyLinkMedtronicService"
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<activity android:name=".plugins.pump.common.dialog.RileyLinkBLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpCommon.dialog.RileyLinkBLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity"
android:label="@string/title_activity_rileylink_settings"
android:theme="@style/Theme.AppCompat.NoTitle" />
<activity android:name=".plugins.pump.medtronic.dialog.MedtronicHistoryActivity" /> <activity android:name=".plugins.pump.medtronic.dialog.MedtronicHistoryActivity" />
<uses-library android:name="org.apache.http.legacy" android:required="false"/> <uses-library android:name="org.apache.http.legacy" android:required="false"/>

View file

@ -407,6 +407,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_
, 'bg': bg , 'bg': bg
, 'tick': tick , 'tick': tick
, 'eventualBG': eventualBG , 'eventualBG': eventualBG
, 'targetBG': target_bg
, 'insulinReq': 0 , 'insulinReq': 0
, 'reservoir' : reservoir_data // The expected reservoir volume at which to deliver the microbolus (the reservoir volume from right before the last pumphistory run) , 'reservoir' : reservoir_data // The expected reservoir volume at which to deliver the microbolus (the reservoir volume from right before the last pumphistory run)
, 'deliverAt' : deliverAt // The time at which the microbolus should be delivered , 'deliverAt' : deliverAt // The time at which the microbolus should be delivered
@ -800,7 +801,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_
rT.COB=meal_data.mealCOB; rT.COB=meal_data.mealCOB;
rT.IOB=iob_data.iob; rT.IOB=iob_data.iob;
rT.reason="COB: " + meal_data.mealCOB + ", Dev: " + convert_bg(deviation, profile) + ", BGI: " + convert_bg(bgi, profile) + ", ISF: " + convert_bg(sens, profile) + ", CR: " + round(profile.carb_ratio, 2) + ", Target: " + convert_bg(target_bg, profile) + ", minPredBG " + convert_bg(minPredBG, profile) + ", minGuardBG " + convert_bg(minGuardBG, profile) + ", IOBpredBG " + convert_bg(lastIOBpredBG, profile); rT.reason="COB: " + round(meal_data.mealCOB, 1) + ", Dev: " + convert_bg(deviation, profile) + ", BGI: " + convert_bg(bgi, profile) + ", ISF: " + convert_bg(sens, profile) + ", CR: " + round(profile.carb_ratio, 2) + ", Target: " + convert_bg(target_bg, profile) + ", minPredBG " + convert_bg(minPredBG, profile) + ", minGuardBG " + convert_bg(minGuardBG, profile) + ", IOBpredBG " + convert_bg(lastIOBpredBG, profile);
if (lastCOBpredBG > 0) { if (lastCOBpredBG > 0) {
rT.reason += ", COBpredBG " + convert_bg(lastCOBpredBG, profile); rT.reason += ", COBpredBG " + convert_bg(lastCOBpredBG, profile);
} }
@ -877,8 +878,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_
console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq); console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq);
if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) { if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) {
rT.carbsReq = carbsReq; rT.carbsReq = carbsReq;
rT.carbsReqWithin = minutesAboveThreshold;
rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; "; rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; ";
} }
// don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted // don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted
if (bg < threshold && iob_data.iob < -profile.current_basal*20/60 && minDelta > 0 && minDelta > expectedDelta) { if (bg < threshold && iob_data.iob < -profile.current_basal*20/60 && minDelta > 0 && minDelta > expectedDelta) {
rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*20/60,2); rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*20/60,2);

View file

@ -1,15 +0,0 @@
package info.nightscout.androidaps;
/**
* Created by mike on 07.06.2016.
*/
public class Config {
public static int SUPPORTEDNSVERSION = 1002; // 0.10.00
public static final boolean APS = BuildConfig.FLAVOR.equals("full");
public static final boolean NSCLIENT = BuildConfig.FLAVOR.equals("nsclient") || BuildConfig.FLAVOR.equals("nsclient2");
public static final boolean PUMPCONTROL = BuildConfig.FLAVOR.equals("pumpcontrol");
public static final boolean PUMPDRIVERS = BuildConfig.FLAVOR.equals("full") || BuildConfig.FLAVOR.equals("pumpcontrol");
}

View file

@ -0,0 +1,15 @@
package info.nightscout.androidaps
import info.nightscout.androidaps.interfaces.ConfigInterface
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class Config @Inject constructor(): ConfigInterface{
override val SUPPORTEDNSVERSION = 1002 // 0.10.00
override val APS = BuildConfig.FLAVOR == "full"
override val NSCLIENT = BuildConfig.FLAVOR == "nsclient" || BuildConfig.FLAVOR == "nsclient2"
override val PUMPCONTROL = BuildConfig.FLAVOR == "pumpcontrol"
override val PUMPDRIVERS = BuildConfig.FLAVOR == "full" || BuildConfig.FLAVOR == "pumpcontrol"
}

View file

@ -27,6 +27,7 @@ import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator import com.google.android.material.tabs.TabLayoutMediator
import com.joanzapata.iconify.Iconify import com.joanzapata.iconify.Iconify
import com.joanzapata.iconify.fonts.FontAwesomeModule import com.joanzapata.iconify.fonts.FontAwesomeModule
import info.nightscout.androidaps.activities.ProfileHelperActivity
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.activities.SingleFragmentActivity import info.nightscout.androidaps.activities.SingleFragmentActivity
@ -49,10 +50,10 @@ import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicato
import info.nightscout.androidaps.setupwizard.SetupWizardActivity import info.nightscout.androidaps.setupwizard.SetupWizardActivity
import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.AndroidPermission
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.LocaleHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.extensions.isRunningRealPumpTest 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.protection.ProtectionCheck
import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.IconsProvider
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -85,6 +86,7 @@ class MainActivity : NoSplashAppCompatActivity() {
@Inject lateinit var iconsProvider: IconsProvider @Inject lateinit var iconsProvider: IconsProvider
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin @Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin
@Inject lateinit var config: Config
private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
private var pluginPreferencesMenuItem: MenuItem? = null private var pluginPreferencesMenuItem: MenuItem? = null
@ -137,15 +139,15 @@ class MainActivity : NoSplashAppCompatActivity() {
} }
androidPermission.notifyForStoragePermission(this) androidPermission.notifyForStoragePermission(this)
androidPermission.notifyForBatteryOptimizationPermission(this) androidPermission.notifyForBatteryOptimizationPermission(this)
if (Config.PUMPDRIVERS) { androidPermission.notifyForLocationPermissions(this)
androidPermission.notifyForLocationPermissions(this) if (config.PUMPDRIVERS) {
androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin) androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin)
androidPermission.notifyForSystemWindowPermissions(this) androidPermission.notifyForSystemWindowPermissions(this)
} }
} }
private fun checkPluginPreferences(viewPager: ViewPager2) { private fun checkPluginPreferences(viewPager: ViewPager2) {
pluginPreferencesMenuItem?.isEnabled = (viewPager.adapter as TabPageAdapter).getPluginAt(viewPager.currentItem).preferencesId != -1 if (viewPager.currentItem >= 0) pluginPreferencesMenuItem?.isEnabled = (viewPager.adapter as TabPageAdapter).getPluginAt(viewPager.currentItem).preferencesId != -1
} }
override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
@ -173,6 +175,7 @@ class MainActivity : NoSplashAppCompatActivity() {
private fun processPreferenceChange(ev: EventPreferenceChange) { private fun processPreferenceChange(ev: EventPreferenceChange) {
if (ev.isChanged(resourceHelper, R.string.key_keep_screen_on)) setWakeLock() if (ev.isChanged(resourceHelper, R.string.key_keep_screen_on)) setWakeLock()
if (ev.isChanged(resourceHelper, R.string.key_skin)) recreate()
} }
private fun setupViews() { private fun setupViews() {
@ -322,6 +325,11 @@ class MainActivity : NoSplashAppCompatActivity() {
return true return true
} }
*/ */
R.id.nav_defaultprofile -> {
startActivity(Intent(this, ProfileHelperActivity::class.java))
return true
}
R.id.nav_stats -> { R.id.nav_stats -> {
startActivity(Intent(this, StatsActivity::class.java)) startActivity(Intent(this, StatsActivity::class.java))
return true return true
@ -352,7 +360,7 @@ class MainActivity : NoSplashAppCompatActivity() {
val hashes: List<String> = signatureVerifierPlugin.shortHashes() val hashes: List<String> = signatureVerifierPlugin.shortHashes()
if (hashes.isNotEmpty()) fabricPrivacy.firebaseAnalytics.setUserProperty("Hash", hashes[0]) if (hashes.isNotEmpty()) fabricPrivacy.firebaseAnalytics.setUserProperty("Hash", hashes[0])
activePlugin.activePump.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } activePlugin.activePump.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) }
if (!Config.NSCLIENT && !Config.PUMPCONTROL) if (!config.NSCLIENT && !config.PUMPCONTROL)
activePlugin.activeAPS.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } activePlugin.activeAPS.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) }
activePlugin.activeBgSource.let { fabricPrivacy.firebaseAnalytics.setUserProperty("BgSource", 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.activeProfileInterface.javaClass.simpleName)

View file

@ -7,7 +7,6 @@ import android.content.res.Resources;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.wifi.WifiManager; import android.net.wifi.WifiManager;
import androidx.annotation.StringRes;
import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OpenHelperManager;
@ -21,6 +20,7 @@ import javax.inject.Inject;
import dagger.android.AndroidInjector; import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication; import dagger.android.DaggerApplication;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.StaticInjector;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
@ -37,7 +37,7 @@ import info.nightscout.androidaps.receivers.NetworkChangeReceiver;
import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver;
import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.ActivityMonitor;
import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.locale.LocaleHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class MainApp extends DaggerApplication { public class MainApp extends DaggerApplication {
@ -52,11 +52,15 @@ public class MainApp extends DaggerApplication {
@Inject ActivityMonitor activityMonitor; @Inject ActivityMonitor activityMonitor;
@Inject VersionCheckerUtils versionCheckersUtils; @Inject VersionCheckerUtils versionCheckersUtils;
@Inject SP sp; @Inject SP sp;
@Inject NSUpload nsUpload;
@Inject Config config;
@Inject ConfigBuilderPlugin configBuilderPlugin; @Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager;
@Inject List<PluginBase> plugins; @Inject List<PluginBase> plugins;
@Inject StaticInjector staticInjector; // TODO avoid , here fake only to initialize
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
@ -66,7 +70,7 @@ public class MainApp extends DaggerApplication {
sResources = getResources(); sResources = getResources();
LocaleHelper.INSTANCE.update(this); LocaleHelper.INSTANCE.update(this);
sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class);
/*
Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> {
if (ex instanceof InternalError) { if (ex instanceof InternalError) {
// usually the app trying to spawn a thread while being killed // usually the app trying to spawn a thread while being killed
@ -74,7 +78,7 @@ public class MainApp extends DaggerApplication {
} }
aapsLogger.error("Uncaught exception crashing app", ex); aapsLogger.error("Uncaught exception crashing app", ex);
}); });
*/
registerActivityLifecycleCallbacks(activityMonitor); registerActivityLifecycleCallbacks(activityMonitor);
JodaTimeAndroid.init(this); JodaTimeAndroid.init(this);
@ -92,7 +96,7 @@ public class MainApp extends DaggerApplication {
pluginStore.setPlugins(plugins); pluginStore.setPlugins(plugins);
configBuilderPlugin.initialize(); configBuilderPlugin.initialize();
NSUpload.uploadAppStart(); nsUpload.uploadAppStart();
new Thread(() -> keepAliveManager.setAlarm(this)).start(); new Thread(() -> keepAliveManager.setAlarm(this)).start();
doMigrations(); doMigrations();
@ -100,7 +104,13 @@ public class MainApp extends DaggerApplication {
private void doMigrations() { private void doMigrations() {
// set values for different builds
if (!sp.contains(R.string.key_ns_alarms))
sp.putBoolean(R.string.key_ns_alarms, config.getNSCLIENT());
if (!sp.contains(R.string.key_ns_announcements))
sp.putBoolean(R.string.key_ns_announcements, config.getNSCLIENT());
if (!sp.contains(R.string.key_language))
sp.putString(R.string.key_language, "default");
} }
@Override @Override
@ -111,6 +121,7 @@ public class MainApp extends DaggerApplication {
.build(); .build();
} }
@SuppressWarnings("deprecation")
private void registerLocalBroadcastReceiver() { private void registerLocalBroadcastReceiver() {
IntentFilter filter = new IntentFilter(); IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_NEW_TREATMENT); filter.addAction(Intents.ACTION_NEW_TREATMENT);
@ -145,16 +156,6 @@ public class MainApp extends DaggerApplication {
registerReceiver(new BTReceiver(), filter); registerReceiver(new BTReceiver(), filter);
} }
@Deprecated
public static String gs(@StringRes int id) {
return sResources.getString(id);
}
@Deprecated
public static MainApp instance() {
return sInstance;
}
public static DatabaseHelper getDbHelper() { public static DatabaseHelper getDbHelper() {
return sDatabaseHelper; return sDatabaseHelper;
} }

View file

@ -13,19 +13,22 @@ import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection import dagger.android.support.AndroidSupportInjection
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R 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.data.Profile
import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
@ -35,13 +38,8 @@ import info.nightscout.androidaps.plugins.general.wear.WearPlugin
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin
import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin
import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
@ -67,19 +65,18 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var pluginStore: PluginStore @Inject lateinit var pluginStore: PluginStore
@Inject lateinit var config: Config
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var danaRPlugin: DanaRPlugin @Inject lateinit var danaRPlugin: DanaRPlugin
@Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin
@Inject lateinit var danaRv2Plugin: DanaRv2Plugin @Inject lateinit var danaRv2Plugin: DanaRv2Plugin
@Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var danaRSPlugin: DanaRSPlugin
@Inject lateinit var careportalPlugin: CareportalPlugin
@Inject lateinit var comboPlugin: ComboPlugin @Inject lateinit var comboPlugin: ComboPlugin
@Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin @Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin
@Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var localInsightPlugin: LocalInsightPlugin @Inject lateinit var localInsightPlugin: LocalInsightPlugin
@Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin
@Inject lateinit var omnipodPumpPlugin: OmnipodPumpPlugin
@Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin
@Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@ -102,6 +99,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var passwordCheck: PasswordCheck @Inject lateinit var passwordCheck: PasswordCheck
@Inject lateinit var nsSettingStatus: NSSettingsStatus @Inject lateinit var nsSettingStatus: NSSettingsStatus
// TODO why?
@Inject lateinit var androidInjector: DispatchingAndroidInjector<Any> @Inject lateinit var androidInjector: DispatchingAndroidInjector<Any>
override fun androidInjector(): AndroidInjector<Any> = androidInjector override fun androidInjector(): AndroidInjector<Any> = androidInjector
@ -161,22 +159,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
addPreferencesFromResourceIfEnabled(tomatoPlugin, rootKey) addPreferencesFromResourceIfEnabled(tomatoPlugin, rootKey)
addPreferencesFromResourceIfEnabled(poctechPlugin, rootKey) addPreferencesFromResourceIfEnabled(poctechPlugin, rootKey)
addPreferencesFromResourceIfEnabled(glimpPlugin, rootKey) addPreferencesFromResourceIfEnabled(glimpPlugin, rootKey)
addPreferencesFromResourceIfEnabled(careportalPlugin, rootKey) addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, config.APS)
addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, Config.APS) addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, config.APS)
addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, Config.APS) addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, config.APS)
addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, Config.APS)
addPreferencesFromResourceIfEnabled(sensitivityAAPSPlugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityAAPSPlugin, rootKey)
addPreferencesFromResourceIfEnabled(sensitivityWeightedAveragePlugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityWeightedAveragePlugin, rootKey)
addPreferencesFromResourceIfEnabled(sensitivityOref1Plugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityOref1Plugin, rootKey)
addPreferencesFromResourceIfEnabled(danaRPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRPlugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(danaRv2Plugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRv2Plugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(danaRSPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(danaRSPlugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, config.PUMPDRIVERS)
addPreferencesFromResourceIfEnabled(omnipodPumpPlugin, rootKey, Config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey, !config.NSCLIENT)
addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey, !Config.NSCLIENT)
addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, rootKey) addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, rootKey)
addPreferencesFromResourceIfEnabled(nsClientPlugin, rootKey) addPreferencesFromResourceIfEnabled(nsClientPlugin, rootKey)
addPreferencesFromResourceIfEnabled(tidepoolPlugin, rootKey) addPreferencesFromResourceIfEnabled(tidepoolPlugin, rootKey)
@ -189,9 +185,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey) addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey)
} }
initSummary(preferenceScreen, pluginId != -1) initSummary(preferenceScreen, pluginId != -1)
for (plugin in pluginStore.plugins) { preprocessPreferences()
plugin.preprocessPreferences(this)
}
} }
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
@ -208,12 +202,49 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
activity?.recreate() activity?.recreate()
return return
} }
if (key == resourceHelper.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) if (key == resourceHelper.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) {
activity?.let { activity?.let {
show(it, resourceHelper.gs(R.string.configbuilder_sensitivity), resourceHelper.gs(R.string.sensitivity_warning)) show(it, resourceHelper.gs(R.string.configbuilder_sensitivity), resourceHelper.gs(R.string.sensitivity_warning))
} }
}
checkForBiometricFallback(key)
updatePrefSummary(findPreference(key)) updatePrefSummary(findPreference(key))
preprocessPreferences()
}
private fun preprocessPreferences() {
for (plugin in pluginStore.plugins) {
plugin.preprocessPreferences(this)
}
}
private fun checkForBiometricFallback(key: String) {
// Biometric protection activated without set master password
if ((resourceHelper.gs(R.string.key_settings_protection) == key ||
resourceHelper.gs(R.string.key_application_protection) == key ||
resourceHelper.gs(R.string.key_bolus_protection) == key) &&
sp.getString(R.string.key_master_password, "") == "" &&
sp.getInt(key, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal
) {
activity?.let {
val title = resourceHelper.gs(R.string.unsecure_fallback_biometric)
val message = resourceHelper.gs(R.string.master_password_missing, resourceHelper.gs(R.string.configbuilder_general), resourceHelper.gs(R.string.protection))
show(it, title = title, message = message)
}
}
// Master password erased with activated Biometric protection
val isBiometricActivated = sp.getInt(R.string.key_settings_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal ||
sp.getInt(R.string.key_application_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal ||
sp.getInt(R.string.key_bolus_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal
if (resourceHelper.gs(R.string.key_master_password) == key && sp.getString(key, "") == "" && isBiometricActivated) {
activity?.let {
val title = resourceHelper.gs(R.string.unsecure_fallback_biometric)
val message = resourceHelper.gs(R.string.unsecure_fallback_descriotion_biometric)
show(it, title = title, message = message)
}
}
} }
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
@ -242,11 +273,9 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
resourceHelper.gs(R.string.key_high_mark), resourceHelper.gs(R.string.key_high_mark),
resourceHelper.gs(R.string.key_low_mark) resourceHelper.gs(R.string.key_low_mark)
) )
if (listOf(*unitDependent).contains(pref.key)) { if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) {
val editTextPref = pref as EditTextPreference val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text))
val converted = Profile.toCurrentUnitsString(profileFunction, SafeParse.stringToDouble(editTextPref.text)) pref.summary = converted.toString()
editTextPref.summary = converted
editTextPref.text = converted
} }
} }
@ -282,7 +311,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
} }
for (plugin in pluginStore.plugins) { for (plugin in pluginStore.plugins) {
pref?.let { it.key?.let { plugin.updatePreferenceSummary(pref) }} pref?.let { it.key?.let { plugin.updatePreferenceSummary(pref) } }
} }
val hmacPasswords = arrayOf( val hmacPasswords = arrayOf(

View file

@ -5,7 +5,7 @@ import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceScreen import androidx.preference.PreferenceScreen
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.LocaleHelper import info.nightscout.androidaps.utils.locale.LocaleHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject import javax.inject.Inject

View file

@ -0,0 +1,288 @@
package info.nightscout.androidaps.activities
import android.content.res.ColorStateList
import android.os.Bundle
import android.text.Editable
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.defaultProfile.DefaultProfile
import info.nightscout.androidaps.data.defaultProfile.DefaultProfileDPV
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.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged
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.resources.ResourceHelper
import info.nightscout.androidaps.utils.stats.TddCalculator
import kotlinx.android.synthetic.main.activity_profilehelper.*
import java.text.DecimalFormat
import javax.inject.Inject
class ProfileHelperActivity : NoSplashAppCompatActivity() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var tddCalculator: TddCalculator
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var defaultProfile: DefaultProfile
@Inject lateinit var defaultProfileDPV: DefaultProfileDPV
@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
enum class ProfileType {
MOTOL_DEFAULT,
DPV_DEFAULT,
CURRENT,
AVAILABLE_PROFILE,
PROFILE_SWITCH
}
private var tabSelected = 0
private val typeSelected = arrayOf(ProfileType.MOTOL_DEFAULT, ProfileType.CURRENT)
private val ageUsed = arrayOf(15.0, 15.0)
private val weightUsed = arrayOf(0.0, 0.0)
private val tddUsed = arrayOf(0.0, 0.0)
private val pctUsed = arrayOf(32.0, 32.0)
private lateinit var profileList: ArrayList<CharSequence>
private val profileUsed = arrayOf(0, 0)
private lateinit var profileSwitch: List<ProfileSwitch>
private val profileSwitchUsed = arrayOf(0, 0)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_profilehelper)
profilehelper_menu1.setOnClickListener {
switchTab(0, typeSelected[0])
}
profilehelper_menu2.setOnClickListener {
switchTab(1, typeSelected[1])
}
profilehelper_profiletype.setOnClickListener {
PopupMenu(this, profilehelper_profiletype).apply {
menuInflater.inflate(R.menu.menu_profilehelper, menu)
setOnMenuItemClickListener { item ->
profilehelper_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_profileswitch -> switchTab(tabSelected, ProfileType.PROFILE_SWITCH)
}
true
}
show()
}
}
// Active profile
profileList = activePlugin.activeProfileInterface.profile?.getProfileList() ?: ArrayList()
profilehelper_available_profile_list.setOnClickListener {
PopupMenu(this, profilehelper_available_profile_list).apply {
var order = 0
for (name in profileList) menu.add(Menu.NONE, order, order++, name)
setOnMenuItemClickListener { item ->
profilehelper_available_profile_list.setText(item.title)
profileUsed[tabSelected] = item.itemId
true
}
show()
}
}
// Profile switch
profileSwitch = databaseHelper.getProfileSwitchData(dateUtil._now() - T.months(2).msecs(), true)
profilehelper_profileswitch_list.setOnClickListener {
PopupMenu(this, profilehelper_profileswitch_list).apply {
var order = 0
for (name in profileSwitch) menu.add(Menu.NONE, order, order++, name.customizedName)
setOnMenuItemClickListener { item ->
profilehelper_profileswitch_list.setText(item.title)
profileSwitchUsed[tabSelected] = item.itemId
true
}
show()
}
}
// Default profile
profilehelper_copytolocalprofile.setOnClickListener {
val age = ageUsed[tabSelected]
val weight = weightUsed[tabSelected]
val tdd = tddUsed[tabSelected]
val pct = pctUsed[tabSelected]
val profile = if (typeSelected[tabSelected] == ProfileType.MOTOL_DEFAULT) defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())
else defaultProfileDPV.profile(age, tdd, pct / 100.0, profileFunction.getUnits())
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())))
rxBus.send(EventLocalProfileChanged())
})
}
}
profilehelper_age.setParams(0.0, 1.0, 18.0, 1.0, DecimalFormat("0"), false, null)
profilehelper_weight.setParams(0.0, 0.0, 150.0, 1.0, DecimalFormat("0"), false, null, object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
profilehelper_tdd_row.visibility = (profilehelper_weight.value == 0.0).toVisibility()
}
})
profilehelper_tdd.setParams(0.0, 0.0, 200.0, 1.0, DecimalFormat("0"), false, null, object : TextWatcher {
override fun afterTextChanged(s: Editable) {}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
profilehelper_weight_row.visibility = (profilehelper_tdd.value == 0.0).toVisibility()
}
})
profilehelper_basalpctfromtdd.setParams(32.0, 32.0, 37.0, 1.0, DecimalFormat("0"), false, null)
profilehelper_tdds.text = tddCalculator.stats()
// Current profile
profilehelper_current_profile_text.text = profileFunction.getProfileName()
// General
profilehelper_compareprofile.setOnClickListener {
storeValues()
for (i in 0..1) {
if (typeSelected[i] == ProfileType.MOTOL_DEFAULT) {
if (ageUsed[i] < 1 || ageUsed[i] > 18) {
ToastUtils.showToastInUiThread(this, R.string.invalidage)
return@setOnClickListener
}
if ((weightUsed[i] < 5 || weightUsed[i] > 150) && tddUsed[i] == 0.0) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
if ((tddUsed[i] < 5 || tddUsed[i] > 150) && weightUsed[i] == 0.0) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
}
if (typeSelected[i] == ProfileType.DPV_DEFAULT) {
if (ageUsed[i] < 1 || ageUsed[i] > 18) {
ToastUtils.showToastInUiThread(this, R.string.invalidage)
return@setOnClickListener
}
if (tddUsed[i] < 5 || tddUsed[i] > 150) {
ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener
}
if ((pctUsed[i] < 32 || pctUsed[i] > 37)) {
ToastUtils.showToastInUiThread(this, R.string.invalidpct)
return@setOnClickListener
}
}
}
getProfile(ageUsed[0], tddUsed[0], weightUsed[0], pctUsed[0] / 100.0, 0)?.let { profile0 ->
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.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("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")
return@setOnClickListener
}
}
ToastUtils.showToastInUiThread(this, R.string.invalidinput)
}
switchTab(0, typeSelected[0], false)
}
private fun getProfile(age: Double, tdd: Double, weight: Double, basalPct: Double, tab: Int): Profile? =
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()
}
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.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString()
ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].customizedName
}
private fun storeValues() {
ageUsed[tabSelected] = profilehelper_age.value
weightUsed[tabSelected] = profilehelper_weight.value
tddUsed[tabSelected] = profilehelper_tdd.value
pctUsed[tabSelected] = profilehelper_basalpctfromtdd.value
}
private fun switchTab(tab: Int, newContent: ProfileType, storeOld: Boolean = true) {
setBackgroundColorOnSelected(tab)
// Store values for selected tab. listBox values are stored on selection change
if (storeOld) storeValues()
tabSelected = tab
typeSelected[tabSelected] = newContent
profilehelper_profiletype_title.defaultHintTextColor = ColorStateList.valueOf(resourceHelper.gc(if (tab == 0) R.color.tabBgColorSelected else R.color.examinedProfile))
// show new content
profilehelper_profiletype.setText(
when (typeSelected[tabSelected]) {
ProfileType.MOTOL_DEFAULT -> resourceHelper.gs(R.string.motoldefaultprofile)
ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.dpvdefaultprofile)
ProfileType.CURRENT -> resourceHelper.gs(R.string.currentprofile)
ProfileType.AVAILABLE_PROFILE -> resourceHelper.gs(R.string.availableprofile)
ProfileType.PROFILE_SWITCH -> resourceHelper.gs(R.string.careportal_profileswitch)
})
profilehelper_default_profile.visibility = (newContent == ProfileType.MOTOL_DEFAULT || newContent == ProfileType.DPV_DEFAULT).toVisibility()
profilehelper_current_profile.visibility = (newContent == ProfileType.CURRENT).toVisibility()
profilehelper_available_profile.visibility = (newContent == ProfileType.AVAILABLE_PROFILE).toVisibility()
profilehelper_profile_switch.visibility = (newContent == ProfileType.PROFILE_SWITCH).toVisibility()
// restore selected values
profilehelper_age.value = ageUsed[tabSelected]
profilehelper_weight.value = weightUsed[tabSelected]
profilehelper_tdd.value = tddUsed[tabSelected]
profilehelper_basalpctfromtdd.value = pctUsed[tabSelected]
profilehelper_basalpctfromtdd_row.visibility = (newContent == ProfileType.DPV_DEFAULT).toVisibility()
if (profileList.isNotEmpty())
profilehelper_available_profile_list.setText(profileList[profileUsed[tabSelected]].toString())
if (profileSwitch.isNotEmpty())
profilehelper_profileswitch_list.setText(profileSwitch[profileSwitchUsed[tabSelected]].customizedName)
}
private fun setBackgroundColorOnSelected(tab: Int) {
profilehelper_menu1.setBackgroundColor(resourceHelper.gc(if (tab == 1) R.color.defaultbackground else R.color.tabBgColorSelected))
profilehelper_menu2.setBackgroundColor(resourceHelper.gc(if (tab == 0) R.color.defaultbackground else R.color.examinedProfile))
}
}

View file

@ -9,7 +9,7 @@ import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.utils.LocaleHelper import info.nightscout.androidaps.utils.locale.LocaleHelper
import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck
import javax.inject.Inject import javax.inject.Inject

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.activities
import android.os.Bundle import android.os.Bundle
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.ActivityMonitor import info.nightscout.androidaps.utils.ActivityMonitor
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TddCalculator
import info.nightscout.androidaps.utils.stats.TirCalculator import info.nightscout.androidaps.utils.stats.TirCalculator

View file

@ -8,9 +8,9 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.defaultProfile.DefaultProfile import info.nightscout.androidaps.data.defaultProfile.DefaultProfile
import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.utils.ActivityMonitor import info.nightscout.androidaps.utils.ActivityMonitor
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.InstanceId import info.nightscout.androidaps.utils.InstanceId
@ -19,7 +19,7 @@ import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TddCalculator
import info.nightscout.androidaps.utils.stats.TirCalculator import info.nightscout.androidaps.utils.stats.TirCalculator
import kotlinx.android.synthetic.main.survey_activity.* import kotlinx.android.synthetic.main.activity_survey.*
import javax.inject.Inject import javax.inject.Inject
class SurveyActivity : NoSplashAppCompatActivity() { class SurveyActivity : NoSplashAppCompatActivity() {
@ -34,7 +34,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.survey_activity) setContentView(R.layout.activity_survey)
survey_id.text = InstanceId.instanceId() survey_id.text = InstanceId.instanceId()
@ -62,16 +62,20 @@ class SurveyActivity : NoSplashAppCompatActivity() {
ToastUtils.showToastInUiThread(this, R.string.invalidweight) ToastUtils.showToastInUiThread(this, R.string.invalidweight)
return@setOnClickListener return@setOnClickListener
} }
val profile = defaultProfile.profile(age, tdd, weight, profileFunction.getUnits()) profileFunction.getProfile()?.let { runningProfile ->
val args = Bundle() defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())?.let { profile ->
args.putLong("time", DateUtil.now()) ProfileViewerDialog().also { pvd ->
args.putInt("mode", ProfileViewerDialog.Mode.CUSTOM_PROFILE.ordinal) pvd.arguments = Bundle().also {
args.putString("customProfile", profile.data.toString()) it.putLong("time", DateUtil.now())
args.putString("customProfileUnits", profile.units) it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal)
args.putString("customProfileName", "Age: $age TDD: $tdd Weight: $weight") it.putString("customProfile", runningProfile.data.toString())
val pvd = ProfileViewerDialog() it.putString("customProfile2", profile.data.toString())
pvd.arguments = args it.putString("customProfileUnits", profile.units)
pvd.show(supportFragmentManager, "ProfileViewDialog") it.putString("customProfileName", "Age: $age TDD: $tdd Weight: $weight")
}
}.show(supportFragmentManager, "ProfileViewDialog")
}
}
} }
survey_submit.setOnClickListener { survey_submit.setOnClickListener {

View file

@ -0,0 +1,101 @@
package info.nightscout.androidaps.db;
import com.j256.ormlite.dao.CloseableIterator;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
@Singleton
public class DatabaseHelperProvider implements DatabaseHelperInterface {
@Inject DatabaseHelperProvider() {}
@NotNull @Override public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
return MainApp.getDbHelper().getAllBgreadingsDataFromTime(mills, ascending);
}
@Override public void createOrUpdate(@NotNull CareportalEvent careportalEvent) {
MainApp.getDbHelper().createOrUpdate(careportalEvent);
}
@Override public void createOrUpdate(@NotNull DanaRHistoryRecord record) {
MainApp.getDbHelper().createOrUpdate(record);
}
@NotNull @Override public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type);
}
@NotNull @Override public List<TDD> getTDDs() {
return MainApp.getDbHelper().getTDDs();
}
@Override public long size(@NotNull String table) {
return MainApp.getDbHelper().size(table);
}
@Override public void create(@NotNull DbRequest record) {
try {
MainApp.getDbHelper().create(record);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override public void deleteAllDbRequests() {
MainApp.getDbHelper().deleteAllDbRequests();
}
@Override public int deleteDbRequest(@NotNull String id) {
return MainApp.getDbHelper().deleteDbRequest(id);
}
@Override public void deleteDbRequestbyMongoId(@NotNull String action, @NotNull String _id) {
MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id);
}
@NotNull @Override public CloseableIterator<DbRequest> getDbRequestInterator() {
return MainApp.getDbHelper().getDbRequestInterator();
}
@Override public long roundDateToSec(long date) {
return MainApp.getDbHelper().roundDateToSec(date);
}
@Override public void createOrUpdateTDD(@NotNull TDD record) {
MainApp.getDbHelper().createOrUpdateTDD(record);
}
@Override public void createOrUpdate(@NotNull TemporaryBasal tempBasal) {
MainApp.getDbHelper().createOrUpdate(tempBasal);
}
@NotNull @Override public TemporaryBasal findTempBasalByPumpId(long id) {
return MainApp.getDbHelper().findTempBasalByPumpId(id);
}
@NotNull @Override public List<TemporaryBasal> getTemporaryBasalsDataFromTime(long mills, boolean ascending) {
return MainApp.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending);
}
@NotNull @Override public CareportalEvent getCareportalEventFromTimestamp(long timestamp) {
return MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp);
}
@NotNull @Override public List<TDD> getTDDsForLastXDays(int days) {
return MainApp.getDbHelper().getTDDsForLastXDays(days);
}
@NotNull @Override public List<ProfileSwitch> getProfileSwitchData(long from, boolean ascending) {
return MainApp.getDbHelper().getProfileSwitchData(from, ascending);
}
}

View file

@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalAdapterAM
import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
@ -17,12 +17,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
abstract class APSModule { abstract class APSModule {
@ContributesAndroidInjector abstract fun loggerCallbackInjector(): LoggerCallback @ContributesAndroidInjector abstract fun loggerCallbackInjector(): LoggerCallback
@ContributesAndroidInjector abstract fun apsResultInjector(): APSResult
@ContributesAndroidInjector abstract fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector abstract fun determineBasalResultSMBInjector(): DetermineBasalResultSMB
@ContributesAndroidInjector abstract fun determineBasalResultAMAInjector(): DetermineBasalResultAMA @ContributesAndroidInjector abstract fun determineBasalResultAMAInjector(): DetermineBasalResultAMA
@ContributesAndroidInjector abstract fun determineBasalAdapterAMAJSInjector(): DetermineBasalAdapterAMAJS @ContributesAndroidInjector abstract fun determineBasalAdapterAMAJSInjector(): DetermineBasalAdapterAMAJS
@ContributesAndroidInjector abstract fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS @ContributesAndroidInjector abstract fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS
@ContributesAndroidInjector abstract fun autosensDataInjector(): AutosensData
@ContributesAndroidInjector abstract fun iobCobThreadInjector(): IobCobThread @ContributesAndroidInjector abstract fun iobCobThreadInjector(): IobCobThread
@ContributesAndroidInjector abstract fun iobCobOref1ThreadInjector(): IobCobOref1Thread @ContributesAndroidInjector abstract fun iobCobOref1ThreadInjector(): IobCobOref1Thread
} }

View file

@ -11,10 +11,6 @@ import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizar
import info.nightscout.androidaps.plugins.general.smsCommunicator.activities.SmsCommunicatorOtpActivity import info.nightscout.androidaps.plugins.general.smsCommunicator.activities.SmsCommunicatorOtpActivity
import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRHistoryActivity
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRUserOptionsActivity
import info.nightscout.androidaps.plugins.pump.danaRS.activities.BLEScanActivity
import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity
import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity
import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity
import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity
@ -25,11 +21,6 @@ import info.nightscout.androidaps.setupwizard.SetupWizardActivity
@Suppress("unused") @Suppress("unused")
abstract class ActivitiesModule { abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity
@ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity
@ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaRHistoryActivity
@ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaRUserOptionsActivity
@ContributesAndroidInjector abstract fun contributeErrorHelperActivity(): ErrorHelperActivity
@ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity @ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity
@ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity @ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity
@ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity @ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity
@ -37,7 +28,6 @@ abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity @ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity
@ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity
@ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity @ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity
@ContributesAndroidInjector abstract fun contributesPairingHelperActivity(): PairingHelperActivity
@ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity @ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity
@ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity @ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity
@ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity @ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity
@ -48,5 +38,6 @@ abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesSmsCommunicatorOtpActivity(): SmsCommunicatorOtpActivity @ContributesAndroidInjector abstract fun contributesSmsCommunicatorOtpActivity(): SmsCommunicatorOtpActivity
@ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity @ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity
@ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity @ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity
@ContributesAndroidInjector abstract fun contributesDefaultProfileActivity(): ProfileHelperActivity
@ContributesAndroidInjector abstract fun contributesPrefImportListActivity(): PrefImportListActivity @ContributesAndroidInjector abstract fun contributesPrefImportListActivity(): PrefImportListActivity
} }

View file

@ -5,56 +5,18 @@ import dagger.Component
import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector import dagger.android.AndroidInjector
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.core.dependencyInjection.CoreModule import info.nightscout.androidaps.core.di.CoreModule
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.dana.di.DanaModule
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.danar.di.DanaRModule
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.danars.di.DanaRSModule
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
import info.nightscout.androidaps.plugins.general.automation.AutomationEvent
import info.nightscout.androidaps.plugins.general.automation.actions.*
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.plugins.general.automation.triggers.*
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.*
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager
import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask
import info.nightscout.androidaps.plugins.treatments.Treatment
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.queue.commands.*
import info.nightscout.androidaps.setupwizard.SWEventListener
import info.nightscout.androidaps.setupwizard.SWScreen
import info.nightscout.androidaps.setupwizard.elements.*
import info.nightscout.androidaps.utils.wizard.BolusWizard
import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
import javax.inject.Singleton import javax.inject.Singleton
@Singleton @Singleton
@Component( @Component(
modules = [ modules = [
AndroidInjectionModule::class, AndroidInjectionModule::class,
CoreModule::class, PluginsModule::class,
SkinsModule::class,
ActivitiesModule::class, ActivitiesModule::class,
FragmentsModule::class, FragmentsModule::class,
AppModule::class, AppModule::class,
@ -65,13 +27,17 @@ import javax.inject.Singleton
ObjectivesModule::class, ObjectivesModule::class,
WizardModule::class, WizardModule::class,
MedtronicModule::class, MedtronicModule::class,
OmnipodModule::class,
APSModule::class, APSModule::class,
PreferencesModule::class, PreferencesModule::class,
OverviewModule::class, OverviewModule::class,
DataClassesModule::class, DataClassesModule::class,
SMSModule::class, SMSModule::class,
UIModule::class, UIModule::class,
OmnipodModule::class CoreModule::class,
DanaModule::class,
DanaRModule::class,
DanaRSModule::class
] ]
) )
interface AppComponent : AndroidInjector<MainApp> { interface AppComponent : AndroidInjector<MainApp> {

View file

@ -8,46 +8,34 @@ import dagger.Provides
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.db.DatabaseHelperProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.androidNotification.NotificationHolder
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.FileStorage
import info.nightscout.androidaps.utils.storage.Storage import info.nightscout.androidaps.utils.storage.Storage
import javax.inject.Singleton import javax.inject.Singleton
@Module(includes = [ @Module(includes = [
AppModule.AppBindings::class, AppModule.AppBindings::class
PluginsModule::class,
SkinsModule::class
]) ])
open class AppModule { open class AppModule {
@Provides @Provides
@Singleton fun providesPlugins(configInterface: ConfigInterface,
fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy): ProfileFunction { @PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>,
return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin, fabricPrivacy)
}
@Provides
fun providesPlugins(@PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>,
@PluginsModule.PumpDriver pumpDrivers: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>, @PluginsModule.PumpDriver pumpDrivers: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.NotNSClient notNsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>, @PluginsModule.NotNSClient notNsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.NSClient nsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>) @PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>)
: List<@JvmSuppressWildcards PluginBase> { : List<@JvmSuppressWildcards PluginBase> {
val plugins = allConfigs.toMutableMap() val plugins = allConfigs.toMutableMap()
if (Config.PUMPDRIVERS) plugins += pumpDrivers.get() if (configInterface.PUMPDRIVERS) plugins += pumpDrivers.get()
if (Config.APS) plugins += aps.get() if (configInterface.APS) plugins += aps.get()
if (!Config.NSCLIENT) plugins += notNsClient.get() if (!configInterface.NSCLIENT) plugins += notNsClient.get()
if (Config.NSCLIENT) plugins += nsClient.get()
return plugins.toList().sortedBy { it.first }.map { it.second } return plugins.toList().sortedBy { it.first }.map { it.second }
} }
@ -63,7 +51,12 @@ open class AppModule {
@Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider
@Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider @Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider
@Binds fun bindConfigInterface(config: Config): ConfigInterface
@Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilderInterface
@Binds fun bindTreatmentInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface
@Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface
@Binds fun bindUploadQueueInterface(uploadQueue: UploadQueue): UploadQueueInterface
@Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolder): NotificationHolderInterface
} }
} }

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.queue.commands.*
@ -10,8 +9,6 @@ import info.nightscout.androidaps.queue.commands.*
@Suppress("unused") @Suppress("unused")
abstract class CommandQueueModule { abstract class CommandQueueModule {
@ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResult
@ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue
@ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus
@ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus @ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus

View file

@ -3,14 +3,10 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.db.*
import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.plugins.general.food.FoodService
import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.BolusWizard
import info.nightscout.androidaps.utils.wizard.QuickWizardEntry import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
@ -19,18 +15,11 @@ import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
@Suppress("unused") @Suppress("unused")
abstract class DataClassesModule { abstract class DataClassesModule {
@ContributesAndroidInjector abstract fun profileInjector(): Profile
@ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus @ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus
@ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore
@ContributesAndroidInjector abstract fun bgReadingInjector(): BgReading
@ContributesAndroidInjector abstract fun treatmentInjector(): Treatment
@ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch
@ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal
@ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent
@ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus
@ContributesAndroidInjector abstract fun DatabaseHelperInjector(): DatabaseHelper
@ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService @ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService
@ContributesAndroidInjector abstract fun foodServiceInjector(): FoodService
@ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard
@ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry

View file

@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog
import info.nightscout.androidaps.plugins.general.actions.ActionsFragment import info.nightscout.androidaps.plugins.general.actions.ActionsFragment
import info.nightscout.androidaps.plugins.general.automation.AutomationFragment import info.nightscout.androidaps.plugins.general.automation.AutomationFragment
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseActionDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseActionDialog
@ -18,8 +17,6 @@ import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTrigg
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditActionDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditActionDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditTriggerDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditTriggerDialog
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog
import info.nightscout.androidaps.plugins.general.food.FoodFragment import info.nightscout.androidaps.plugins.general.food.FoodFragment
import info.nightscout.androidaps.plugins.general.maintenance.MaintenanceFragment import info.nightscout.androidaps.plugins.general.maintenance.MaintenanceFragment
import info.nightscout.androidaps.plugins.general.nsclient.NSClientFragment import info.nightscout.androidaps.plugins.general.nsclient.NSClientFragment
@ -34,7 +31,6 @@ import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import info.nightscout.androidaps.plugins.pump.combo.ComboFragment import info.nightscout.androidaps.plugins.pump.combo.ComboFragment
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment
import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment
import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic
@ -54,13 +50,11 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment @ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment
@ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment @ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment
@ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment @ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment
@ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment
@ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment @ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment
@ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment
@ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment @ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment
@ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment @ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment
@ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment @ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment
@ -89,7 +83,6 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment @ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment
@ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog
@ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog
@ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog
@ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog
@ -100,17 +93,13 @@ abstract class FragmentsModule {
@ContributesAndroidInjector @ContributesAndroidInjector
abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog
@ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog
@ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog
@ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog
@ContributesAndroidInjector abstract fun contributesChooseActionDialog(): ChooseActionDialog @ContributesAndroidInjector abstract fun contributesChooseActionDialog(): ChooseActionDialog
@ContributesAndroidInjector abstract fun contributesChooseTriggerDialog(): ChooseTriggerDialog @ContributesAndroidInjector abstract fun contributesChooseTriggerDialog(): ChooseTriggerDialog
@ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog
@ContributesAndroidInjector abstract fun contributesNewNSTreatmentDialog(): NewNSTreatmentDialog
@ContributesAndroidInjector abstract fun contributesNtpProgressDialog(): NtpProgressDialog
@ContributesAndroidInjector abstract fun contributesObjectivesExamDialog(): ObjectivesExamDialog @ContributesAndroidInjector abstract fun contributesObjectivesExamDialog(): ObjectivesExamDialog
@ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog @ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog
@ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog
@ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog @ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog
@ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog @ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog
@ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog @ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog

View file

@ -2,10 +2,6 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.general.automation.AutomationEvent
import info.nightscout.androidaps.plugins.general.automation.actions.*
import info.nightscout.androidaps.plugins.general.automation.elements.*
import info.nightscout.androidaps.plugins.general.automation.triggers.*
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE
@ -16,8 +12,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Radi
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.*
import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager
import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.queue.commands.*
@Module @Module
@Suppress("unused") @Suppress("unused")

View file

@ -19,6 +19,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus
import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager
import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsPodStateManager
import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUITask import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUITask
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Singleton import javax.inject.Singleton
@ -53,7 +54,7 @@ abstract class OmnipodModule {
@Provides @Provides
@Singleton @Singleton
fun podStateManagerProvider(aapsLogger: AAPSLogger, sp: SP, omnipodPumpStatus: OmnipodPumpStatus, fun podStateManagerProvider(aapsLogger: AAPSLogger, sp: SP, omnipodPumpStatus: OmnipodPumpStatus,
rxBus: RxBusWrapper, resourceHelper: ResourceHelper): PodStateManager = rxBus: RxBusWrapper, resourceHelper: ResourceHelper, dateUtil: DateUtil): PodStateManager =
AapsPodStateManager(aapsLogger, sp, omnipodPumpStatus, rxBus, resourceHelper) AapsPodStateManager(aapsLogger, sp, omnipodPumpStatus, rxBus, resourceHelper, dateUtil)
} }
} }

View file

@ -2,16 +2,8 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
@Module @Module
@Suppress("unused") @Suppress("unused")

View file

@ -1,13 +1,13 @@
package info.nightscout.androidaps.dependencyInjection package info.nightscout.androidaps.dependencyInjection
import dagger.Binds import dagger.Binds
import dagger.Lazy
import dagger.Module import dagger.Module
import dagger.Provides
import dagger.multibindings.IntKey import dagger.multibindings.IntKey
import dagger.multibindings.IntoMap import dagger.multibindings.IntoMap
import dagger.multibindings.IntoSet import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.Config import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
@ -21,7 +21,6 @@ import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintP
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin
import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin
import info.nightscout.androidaps.plugins.general.food.FoodPlugin import info.nightscout.androidaps.plugins.general.food.FoodPlugin
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin
@ -38,10 +37,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin
@ -70,7 +65,7 @@ abstract class PluginsModule {
abstract fun bindIobCobCalculatorPlugin(plugin: IobCobCalculatorPlugin): PluginBase abstract fun bindIobCobCalculatorPlugin(plugin: IobCobCalculatorPlugin): PluginBase
@Binds @Binds
@NotNSClient @AllConfigs
@IntoMap @IntoMap
@IntKey(20) @IntKey(20)
abstract fun bindActionsPlugin(plugin: ActionsPlugin): PluginBase abstract fun bindActionsPlugin(plugin: ActionsPlugin): PluginBase
@ -165,12 +160,6 @@ abstract class PluginsModule {
@IntKey(170) @IntKey(170)
abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase
@Binds
@NSClient
@IntoMap
@IntKey(180)
abstract fun bindCareportalPlugin(plugin: CareportalPlugin): PluginBase
@Binds @Binds
@APS @APS
@IntoMap @IntoMap
@ -202,7 +191,7 @@ abstract class PluginsModule {
abstract fun bindLocalProfilePlugin(plugin: LocalProfilePlugin): PluginBase abstract fun bindLocalProfilePlugin(plugin: LocalProfilePlugin): PluginBase
@Binds @Binds
@AllConfigs @APS
@IntoMap @IntoMap
@IntKey(250) @IntKey(250)
abstract fun bindAutomationPlugin(plugin: AutomationPlugin): PluginBase abstract fun bindAutomationPlugin(plugin: AutomationPlugin): PluginBase
@ -231,7 +220,6 @@ abstract class PluginsModule {
@IntKey(280) @IntKey(280)
abstract fun bindSmsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase abstract fun bindSmsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase
@Binds @Binds
@APS @APS
@IntoMap @IntoMap
@ -367,9 +355,6 @@ abstract class PluginsModule {
@Qualifier @Qualifier
annotation class NotNSClient annotation class NotNSClient
@Qualifier
annotation class NSClient
@Qualifier @Qualifier
annotation class APS annotation class APS

View file

@ -4,8 +4,10 @@ import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver
import info.nightscout.androidaps.plugins.aps.loop.CarbSuggestionReceiver
import info.nightscout.androidaps.receivers.* import info.nightscout.androidaps.receivers.*
@Module @Module
@Suppress("unused") @Suppress("unused")
abstract class ReceiversModule { abstract class ReceiversModule {
@ -14,10 +16,9 @@ abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesChargingStateReceiver(): ChargingStateReceiver @ContributesAndroidInjector abstract fun contributesChargingStateReceiver(): ChargingStateReceiver
@ContributesAndroidInjector abstract fun contributesDataReceiver(): DataReceiver @ContributesAndroidInjector abstract fun contributesDataReceiver(): DataReceiver
@ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver @ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver
@ContributesAndroidInjector abstract fun contributesNetworkChangeReceiver(): NetworkChangeReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
@ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver @ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver
@ContributesAndroidInjector abstract fun contributesCarbSuggestionReceiver(): CarbSuggestionReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver
} }

View file

@ -7,11 +7,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Dismiss
import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService
import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService
import info.nightscout.androidaps.plugins.pump.danaR.services.AbstractDanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService
import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService
import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2ExecutionService
import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService
import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService
import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService
@ -24,17 +19,12 @@ import info.nightscout.androidaps.services.LocationService
@Suppress("unused") @Suppress("unused")
abstract class ServicesModule { abstract class ServicesModule {
@ContributesAndroidInjector abstract fun contributesAbstractDanaRExecutionService(): AbstractDanaRExecutionService
@ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService @ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService
@ContributesAndroidInjector abstract fun contributesDataService(): DataService @ContributesAndroidInjector abstract fun contributesDataService(): DataService
@ContributesAndroidInjector abstract fun contributesDismissNotificationService(): DismissNotificationService @ContributesAndroidInjector abstract fun contributesDismissNotificationService(): DismissNotificationService
@ContributesAndroidInjector abstract fun contributesDummyService(): DummyService @ContributesAndroidInjector abstract fun contributesDummyService(): DummyService
@ContributesAndroidInjector abstract fun contributesLocationService(): LocationService @ContributesAndroidInjector abstract fun contributesLocationService(): LocationService
@ContributesAndroidInjector abstract fun contributesNSClientService(): NSClientService @ContributesAndroidInjector abstract fun contributesNSClientService(): NSClientService
@ContributesAndroidInjector abstract fun contributesDanaRSService(): DanaRSService
@ContributesAndroidInjector abstract fun contributesDanaRv2ExecutionService(): DanaRv2ExecutionService
@ContributesAndroidInjector abstract fun contributesDanaRExecutionService(): DanaRExecutionService
@ContributesAndroidInjector abstract fun contributesDanaRKoreanExecutionService(): DanaRKoreanExecutionService
@ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService @ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService
@ContributesAndroidInjector abstract fun contributesInsightAlertService(): InsightAlertService @ContributesAndroidInjector abstract fun contributesInsightAlertService(): InsightAlertService
@ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService @ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService

View file

@ -8,6 +8,7 @@ import dagger.multibindings.IntoMap
import info.nightscout.androidaps.skins.SkinButtonsOn import info.nightscout.androidaps.skins.SkinButtonsOn
import info.nightscout.androidaps.skins.SkinClassic import info.nightscout.androidaps.skins.SkinClassic
import info.nightscout.androidaps.skins.SkinInterface import info.nightscout.androidaps.skins.SkinInterface
import info.nightscout.androidaps.skins.SkinLargeDisplay
import javax.inject.Qualifier import javax.inject.Qualifier
@Module @Module
@ -25,6 +26,12 @@ open class SkinsModule {
@IntKey(10) @IntKey(10)
fun bindsSkinButtonsOn(skinButtonsOn: SkinButtonsOn): SkinInterface = skinButtonsOn fun bindsSkinButtonsOn(skinButtonsOn: SkinButtonsOn): SkinInterface = skinButtonsOn
@Provides
@Skin
@IntoMap
@IntKey(20)
fun bindsSkinLargeDisplay(skinLargeDisplay: SkinLargeDisplay): SkinInterface = skinLargeDisplay
@Qualifier @Qualifier
annotation class Skin annotation class Skin
} }

View file

@ -2,16 +2,6 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module import dagger.Module
import dagger.android.ContributesAndroidInjector import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.plugins.aps.loop.APSResult
import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS
import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
import info.nightscout.androidaps.skins.SkinListPreference import info.nightscout.androidaps.skins.SkinListPreference
@Module @Module

View file

@ -1,16 +0,0 @@
PreferenceActivity is an Example how to make an Activity injectable.
We might undo that as we don't actually have us inject things.
MyPreferencesFragment is an injectable Fragment. Here we actually have Dagger2 provide us an InsulinOrefFreePeakPlugin instance.
If we use multiple Fragments, we should generate a base-class. Then we only have to add a "provides***Fragment" to the FragmentsModule and derive from that class.
InsulinOrefFreePeakPlugin is an example how to get things injected via the constructor.
You could call "new InsulinOrefFreePeakPlugin(new SPImpl(SPImpl(PreferenceManager.getDefaultSharedPreferences(context))), new ResourceHelper())"... but Dagger will resolve that for you in MainApp. :)
SPImpl is an example how to bind an implementation to an Interface via Dagger.
ResourceHelper is an example how to generate simple classes that Dagger can auto-resolve how to inject them. No need for a provider here.
ResourceHelper might have a weak reference at some point and not a static dependency on MainApp... but at least we reduced the static dependencies within a plugin.
In order to Test: Any dependency of InsulinOrefFreePeakPlugin is passed via the constructor. Instead of static mocking MainApp you now can Mock ResourceHelper with a very small interface.

View file

@ -9,7 +9,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.db.TempTarget
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.plugins.treatments.CarbsGenerator
@ -40,6 +40,7 @@ class CarbsDialog : DialogFragmentWithDate() {
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var carbsGenerator: CarbsGenerator @Inject lateinit var carbsGenerator: CarbsGenerator
companion object { companion object {
@ -170,7 +171,7 @@ class CarbsDialog : DialogFragmentWithDate() {
eventTime -= eventTime % 1000 eventTime -= eventTime % 1000
val time = eventTime + timeOffset * 1000 * 60 val time = eventTime + timeOffset * 1000 * 60
if (timeOffset != 0) if (timeOffset != 0)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))
val duration = overview_carbs_duration.value.toInt() val duration = overview_carbs_duration.value.toInt()
if (duration > 0) if (duration > 0)
actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour))
@ -184,7 +185,7 @@ class CarbsDialog : DialogFragmentWithDate() {
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes)
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) {
activity?.let { activity -> activity?.let { activity ->
@ -233,7 +234,7 @@ class CarbsDialog : DialogFragmentWithDate() {
} else { } else {
aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration") aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration")
carbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes) carbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes)
NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) nsUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset))
} }
} }
}, null) }, null)

View file

@ -15,13 +15,13 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.Translator
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.dialog_care.* import kotlinx.android.synthetic.main.dialog_care.*
import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.notes.*
@ -36,6 +36,7 @@ class CareDialog : DialogFragmentWithDate() {
@Inject lateinit var mainApp: MainApp @Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var translator: Translator @Inject lateinit var translator: Translator
enum class EventType { enum class EventType {
@ -43,10 +44,13 @@ class CareDialog : DialogFragmentWithDate() {
SENSOR_INSERT, SENSOR_INSERT,
BATTERY_CHANGE, BATTERY_CHANGE,
NOTE, NOTE,
EXERCISE EXERCISE,
QUESTION,
ANNOUNCEMENT
} }
private var options: EventType = EventType.BGCHECK private var options: EventType = EventType.BGCHECK
@StringRes @StringRes
private var event: Int = R.string.none private var event: Int = R.string.none
@ -79,11 +83,13 @@ class CareDialog : DialogFragmentWithDate() {
} }
actions_care_icon.setImageResource(when (options) { actions_care_icon.setImageResource(when (options) {
EventType.BGCHECK -> R.drawable.icon_cp_bgcheck EventType.BGCHECK -> R.drawable.ic_cp_bgcheck
EventType.SENSOR_INSERT -> R.drawable.icon_cp_cgm_insert EventType.SENSOR_INSERT -> R.drawable.ic_cp_cgm_insert
EventType.BATTERY_CHANGE -> R.drawable.icon_cp_pump_battery EventType.BATTERY_CHANGE -> R.drawable.ic_cp_pump_battery
EventType.NOTE -> R.drawable.icon_cp_note EventType.NOTE -> R.drawable.ic_cp_note
EventType.EXERCISE -> R.drawable.icon_cp_exercise EventType.EXERCISE -> R.drawable.ic_cp_exercise
EventType.QUESTION -> R.drawable.ic_cp_question
EventType.ANNOUNCEMENT -> R.drawable.ic_cp_announcement
}) })
actions_care_title.text = resourceHelper.gs(when (options) { actions_care_title.text = resourceHelper.gs(when (options) {
EventType.BGCHECK -> R.string.careportal_bgcheck EventType.BGCHECK -> R.string.careportal_bgcheck
@ -91,9 +97,13 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange
EventType.NOTE -> R.string.careportal_note EventType.NOTE -> R.string.careportal_note
EventType.EXERCISE -> R.string.careportal_exercise EventType.EXERCISE -> R.string.careportal_exercise
EventType.QUESTION -> R.string.careportal_question
EventType.ANNOUNCEMENT -> R.string.careportal_announcement
}) })
when (options) { when (options) {
EventType.QUESTION,
EventType.ANNOUNCEMENT,
EventType.BGCHECK -> { EventType.BGCHECK -> {
action_care_duration_layout.visibility = View.GONE action_care_duration_layout.visibility = View.GONE
} }
@ -133,7 +143,7 @@ class CareDialog : DialogFragmentWithDate() {
} }
actions_care_duration.setParams(savedInstanceState?.getDouble("actions_care_duration") actions_care_duration.setParams(savedInstanceState?.getDouble("actions_care_duration")
?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok) ?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok)
if (options == EventType.NOTE) if (options == EventType.NOTE || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT)
notes_layout?.visibility = View.VISIBLE // independent to preferences notes_layout?.visibility = View.VISIBLE // independent to preferences
} }
@ -143,7 +153,7 @@ class CareDialog : DialogFragmentWithDate() {
val json = JSONObject() val json = JSONObject()
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()
if (options == EventType.BGCHECK) { if (options == EventType.BGCHECK || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT) {
val type = val type =
when { when {
actions_care_meter.isChecked -> "Finger" actions_care_meter.isChecked -> "Finger"
@ -167,7 +177,7 @@ class CareDialog : DialogFragmentWithDate() {
eventTime -= eventTime % 1000 eventTime -= eventTime % 1000
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
json.put("created_at", DateUtil.toISOString(eventTime)) json.put("created_at", DateUtil.toISOString(eventTime))
json.put("mills", eventTime) json.put("mills", eventTime)
@ -177,6 +187,8 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE
EventType.NOTE -> CareportalEvent.NOTE EventType.NOTE -> CareportalEvent.NOTE
EventType.EXERCISE -> CareportalEvent.EXERCISE EventType.EXERCISE -> CareportalEvent.EXERCISE
EventType.QUESTION -> CareportalEvent.QUESTION
EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT
}) })
json.put("units", profileFunction.getUnits()) json.put("units", profileFunction.getUnits())
if (enteredBy.isNotEmpty()) if (enteredBy.isNotEmpty())
@ -193,11 +205,13 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE
EventType.NOTE -> CareportalEvent.NOTE EventType.NOTE -> CareportalEvent.NOTE
EventType.EXERCISE -> CareportalEvent.EXERCISE EventType.EXERCISE -> CareportalEvent.EXERCISE
EventType.QUESTION -> CareportalEvent.QUESTION
EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT
} }
careportalEvent.json = json.toString() careportalEvent.json = json.toString()
aapsLogger.debug("USER ENTRY: CAREPORTAL ${careportalEvent.eventType} json: ${careportalEvent.json}") aapsLogger.debug("USER ENTRY: CAREPORTAL ${careportalEvent.eventType} json: ${careportalEvent.json}")
MainApp.getDbHelper().createOrUpdate(careportalEvent) MainApp.getDbHelper().createOrUpdate(careportalEvent)
NSUpload.uploadCareportalEntryToNS(json) nsUpload.uploadCareportalEntryToNS(json)
}, null) }, null)
} }
return true return true

View file

@ -24,6 +24,7 @@ import javax.inject.Inject
abstract class DialogFragmentWithDate : DaggerDialogFragment() { abstract class DialogFragmentWithDate : DaggerDialogFragment() {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP @Inject lateinit var sp: SP
@Inject lateinit var dateUtil: DateUtil
var eventTime = DateUtil.now() var eventTime = DateUtil.now()
var eventTimeChanged = false var eventTimeChanged = false
@ -57,7 +58,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
eventTime = savedInstanceState?.getLong("eventTime") ?: DateUtil.now() eventTime = savedInstanceState?.getLong("eventTime") ?: DateUtil.now()
eventTimeChanged = savedInstanceState?.getBoolean("eventTimeChanged") ?: false eventTimeChanged = savedInstanceState?.getBoolean("eventTimeChanged") ?: false
overview_eventdate?.text = DateUtil.dateString(eventTime) overview_eventdate?.text = DateUtil.dateString(eventTime)
overview_eventtime?.text = DateUtil.timeString(eventTime) overview_eventtime?.text = dateUtil.timeString(eventTime)
// create an OnDateSetListener // create an OnDateSetListener
val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
@ -92,7 +93,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
cal.set(Calendar.SECOND, seconds++) // randomize seconds to prevent creating record of the same time, if user choose time manually cal.set(Calendar.SECOND, seconds++) // randomize seconds to prevent creating record of the same time, if user choose time manually
eventTime = cal.timeInMillis eventTime = cal.timeInMillis
eventTimeChanged = true eventTimeChanged = true
overview_eventtime?.text = DateUtil.timeString(eventTime) overview_eventtime?.text = dateUtil.timeString(eventTime)
} }
overview_eventtime?.setOnClickListener { overview_eventtime?.setOnClickListener {

View file

@ -62,7 +62,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() {
override fun submit(): Boolean { override fun submit(): Boolean {
val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text) val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text)
val durationInMinutes = SafeParse.stringToInt(actions_extendedbolus_duration.text) val durationInMinutes = actions_extendedbolus_duration.value.toInt()
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()
val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value()
actions.add(resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraint)) actions.add(resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraint))

View file

@ -23,9 +23,10 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import kotlinx.android.synthetic.main.dialog_fill.* import kotlinx.android.synthetic.main.dialog_fill.*
import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.notes.*
import kotlinx.android.synthetic.main.okcancel.* import kotlinx.android.synthetic.main.okcancel.*
@ -39,9 +40,9 @@ class FillDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var injector: HasAndroidInjector
override fun onSaveInstanceState(savedInstanceState: Bundle) { override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState) super.onSaveInstanceState(savedInstanceState)
@ -112,7 +113,7 @@ class FillDialog : DialogFragmentWithDate() {
eventTime -= eventTime % 1000 eventTime -= eventTime % 1000
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
if (insulinAfterConstraints > 0 || fill_catheter_change.isChecked || fill_cartridge_change.isChecked) { if (insulinAfterConstraints > 0 || fill_catheter_change.isChecked || fill_cartridge_change.isChecked) {
activity?.let { activity -> activity?.let { activity ->
@ -123,12 +124,12 @@ class FillDialog : DialogFragmentWithDate() {
} }
if (siteChange) { if (siteChange) {
aapsLogger.debug("USER ENTRY: SITE CHANGE") aapsLogger.debug("USER ENTRY: SITE CHANGE")
generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes) nsUpload.generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes)
} }
if (insulinChange) { if (insulinChange) {
// add a second for case of both checked // add a second for case of both checked
aapsLogger.debug("USER ENTRY: INSULIN CHANGE") aapsLogger.debug("USER ENTRY: INSULIN CHANGE")
generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes) nsUpload.generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes)
} }
}, null) }, null)
} }
@ -161,28 +162,4 @@ class FillDialog : DialogFragmentWithDate() {
} }
}) })
} }
private fun generateCareportalEvent(eventType: String, time: Long, notes: String) {
val careportalEvent = CareportalEvent(injector)
careportalEvent.source = Source.USER
careportalEvent.date = time
careportalEvent.json = generateJson(eventType, time, notes).toString()
careportalEvent.eventType = eventType
MainApp.getDbHelper().createOrUpdate(careportalEvent)
NSUpload.uploadEvent(eventType, time, notes)
}
private fun generateJson(careportalEvent: String, time: Long, notes: String): JSONObject {
val data = JSONObject()
try {
data.put("eventType", careportalEvent)
data.put("created_at", DateUtil.toISOString(time))
data.put("mills", time)
data.put("enteredBy", sp.getString("careportal_enteredby", resourceHelper.gs(R.string.app_name)))
if (notes.isNotEmpty()) data.put("notes", notes)
} catch (ignored: JSONException) {
}
return data
}
} }

View file

@ -9,6 +9,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import com.google.common.base.Joiner import com.google.common.base.Joiner
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
@ -21,7 +22,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
@ -45,6 +46,7 @@ class InsulinDialog : DialogFragmentWithDate() {
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var config: Config
companion object { companion object {
private const val PLUS1_DEFAULT = 0.5 private const val PLUS1_DEFAULT = 0.5
@ -88,6 +90,10 @@ class InsulinDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
if (config.NSCLIENT) {
overview_insulin_record_only.isChecked = true
overview_insulin_record_only.isEnabled = false
}
val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time") overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time")
@ -145,7 +151,7 @@ class InsulinDialog : DialogFragmentWithDate() {
val timeOffset = overview_insulin_time.value.toInt() val timeOffset = overview_insulin_time.value.toInt()
val time = DateUtil.now() + T.mins(timeOffset.toLong()).msecs() val time = DateUtil.now() + T.mins(timeOffset.toLong()).msecs()
if (timeOffset != 0) if (timeOffset != 0)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time))
val notes = notes.text.toString() val notes = notes.text.toString()
if (notes.isNotEmpty()) if (notes.isNotEmpty())

View file

@ -9,7 +9,7 @@ import com.google.common.base.Joiner
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
@ -28,6 +28,8 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
var profileIndex: Int? = null
override fun onSaveInstanceState(savedInstanceState: Bundle) { override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState) super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value)
@ -38,6 +40,9 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View? {
onCreateViewGeneral() onCreateViewGeneral()
arguments?.let { bundle ->
profileIndex = bundle.getInt("profileIndex", 0)
}
return inflater.inflate(R.layout.dialog_profileswitch, container, false) return inflater.inflate(R.layout.dialog_profileswitch, container, false)
} }
@ -59,9 +64,12 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
overview_profileswitch_profile.adapter = adapter overview_profileswitch_profile.adapter = adapter
// set selected to actual profile // set selected to actual profile
for (p in profileList.indices) if (profileIndex != null)
if (profileList[p] == profileFunction.getProfileName(false)) overview_profileswitch_profile.setSelection(profileIndex as Int)
overview_profileswitch_profile.setSelection(p) else
for (p in profileList.indices)
if (profileList[p] == profileFunction.getProfileName(false))
overview_profileswitch_profile.setSelection(p)
} ?: return } ?: return
treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now())?.let { ps -> treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now())?.let { ps ->
@ -98,7 +106,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
if (notes.isNotEmpty()) if (notes.isNotEmpty())
actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes)
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {

View file

@ -1,114 +0,0 @@
package info.nightscout.androidaps.dialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import dagger.android.HasAndroidInjector
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.close.*
import kotlinx.android.synthetic.main.dialog_profileviewer.*
import org.json.JSONObject
import javax.inject.Inject
class ProfileViewerDialog : DaggerDialogFragment() {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
private var time: Long = 0
enum class Mode(val i: Int) {
RUNNING_PROFILE(1),
CUSTOM_PROFILE(2)
}
private var mode: Mode = Mode.RUNNING_PROFILE
private var customProfileJson: String = ""
private var customProfileName: String = ""
private var customProfileUnits: String = Constants.MGDL
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
time = bundle.getLong("time", 0)
mode = Mode.values()[bundle.getInt("mode", Mode.RUNNING_PROFILE.ordinal)]
customProfileJson = bundle.getString("customProfile", "")
customProfileUnits = bundle.getString("customProfileUnits", Constants.MGDL)
customProfileName = bundle.getString("customProfileName", "")
}
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
isCancelable = true
dialog?.setCanceledOnTouchOutside(false)
return inflater.inflate(R.layout.dialog_profileviewer, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
close.setOnClickListener { dismiss() }
val profile: Profile?
val profileName: String?
val date: String?
when (mode) {
Mode.RUNNING_PROFILE -> {
profile = treatmentsPlugin.getProfileSwitchFromHistory(time)?.profileObject
profileName = treatmentsPlugin.getProfileSwitchFromHistory(time)?.customizedName
date = DateUtil.dateAndTimeString(treatmentsPlugin.getProfileSwitchFromHistory(time)?.date
?: 0)
profileview_datelayout.visibility = View.VISIBLE
}
Mode.CUSTOM_PROFILE -> {
profile = Profile(injector, JSONObject(customProfileJson), customProfileUnits)
profileName = customProfileName
date = ""
profileview_datelayout.visibility = View.GONE
}
}
profileview_noprofile.visibility = View.VISIBLE
profile?.let {
profileview_units.text = it.units
profileview_dia.text = resourceHelper.gs(R.string.format_hours, it.dia)
profileview_activeprofile.text = profileName
profileview_date.text = date
profileview_ic.text = it.icList
profileview_isf.text = it.isfList
profileview_basal.text = it.basalList
profileview_target.text = it.targetList
basal_graph.show(it)
profileview_noprofile.visibility = View.GONE
profileview_invalidprofile.visibility = if (it.isValid("ProfileViewDialog")) View.GONE else View.VISIBLE
}
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putLong("time", time)
bundle.putInt("mode", mode.ordinal)
bundle.putString("customProfile", customProfileJson)
bundle.putString("customProfileName", customProfileName)
bundle.putString("customProfileUnits", customProfileUnits)
}
}

View file

@ -14,7 +14,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.interfaces.PumpDescription
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
@ -83,25 +83,25 @@ class TempBasalDialog : DialogFragmentWithDate() {
override fun submit(): Boolean { override fun submit(): Boolean {
var percent = 0 var percent = 0
var absolute = 0.0 var absolute = 0.0
val durationInMinutes = SafeParse.stringToInt(actions_tempbasal_duration.text) val durationInMinutes = actions_tempbasal_duration.value.toInt()
val profile = profileFunction.getProfile() ?: return false val profile = profileFunction.getProfile() ?: return false
val actions: LinkedList<String> = LinkedList() val actions: LinkedList<String> = LinkedList()
if (isPercentPump) { if (isPercentPump) {
val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text) val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text)
percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value()
actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": $percent%") actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": $percent%")
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes))
if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied))
} else { } else {
val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text) val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text)
absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value()
actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute)) actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes))
if (abs(absolute - basalAbsoluteInput) > 0.01) if (abs(absolute - basalAbsoluteInput) > 0.01)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.constraintapllied) + "</font>") actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.constraintapllied) + "</font>")
} }
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
val callback: Callback = object : Callback() { val callback: Callback = object : Callback() {
override fun run() { override fun run() {
if (!result.success) { if (!result.success) {

View file

@ -14,9 +14,8 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.db.TempTarget
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
@ -77,7 +76,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList) val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList)
overview_temptarget_reason.adapter = adapterReason overview_temptarget_reason.adapter = adapterReason
overview_temptarget_reason.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { overview_temptarget_reason.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val defaultDuration: Double val defaultDuration: Double
val defaultTarget: Double val defaultTarget: Double
when (reasonList[position]) { when (reasonList[position]) {
@ -123,13 +122,13 @@ class TempTargetDialog : DialogFragmentWithDate() {
val duration = overview_temptarget_duration.value.toInt() val duration = overview_temptarget_duration.value.toInt()
if (target != 0.0 && duration != 0) { if (target != 0.0 && duration != 0) {
actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) actions.add(resourceHelper.gs(R.string.reason) + ": " + reason)
actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId)) actions.add(resourceHelper.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration))
} else { } else {
actions.add(resourceHelper.gs(R.string.stoptemptarget)) actions.add(resourceHelper.gs(R.string.stoptemptarget))
} }
if (eventTimeChanged) if (eventTimeChanged)
actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime))
activity?.let { activity -> activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {

View file

@ -9,6 +9,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import com.google.common.base.Joiner import com.google.common.base.Joiner
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.DetailedBolusInfo
@ -25,6 +26,7 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.dialog_insulin.*
import kotlinx.android.synthetic.main.dialog_treatment.* import kotlinx.android.synthetic.main.dialog_treatment.*
import kotlinx.android.synthetic.main.okcancel.* import kotlinx.android.synthetic.main.okcancel.*
import java.text.DecimalFormat import java.text.DecimalFormat
@ -38,6 +40,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var ctx: Context @Inject lateinit var ctx: Context
@Inject lateinit var config: Config
private val textWatcher: TextWatcher = object : TextWatcher { private val textWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {} override fun afterTextChanged(s: Editable) {}
@ -75,6 +78,10 @@ class TreatmentDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
if (config.NSCLIENT) {
overview_treatment_record_only.isChecked = true
overview_treatment_record_only.isEnabled = false
}
val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble()
val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
val pumpDescription = activePlugin.activePump.pumpDescription val pumpDescription = activePlugin.activePump.pumpDescription

View file

@ -24,7 +24,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
@ -261,7 +261,7 @@ class WizardDialog : DaggerDialogFragment() {
private fun calculateInsulin() { private fun calculateInsulin() {
val profileStore = activePlugin.activeProfileInterface.profile val profileStore = activePlugin.activeProfileInterface.profile
if (treatments_wizard_profile.selectedItem == null || profileStore == null) if (treatments_wizard_profile?.selectedItem == null || profileStore == null)
return // not initialized yet return // not initialized yet
var profileName = treatments_wizard_profile.selectedItem.toString() var profileName = treatments_wizard_profile.selectedItem.toString()
val specificProfile: Profile? val specificProfile: Profile?

View file

@ -9,7 +9,7 @@ import android.view.WindowManager
import dagger.android.support.DaggerDialogFragment import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper

View file

@ -1,3 +0,0 @@
package info.nightscout.androidaps.events
class EventRebuildTabs @JvmOverloads constructor(var recreate: Boolean = false) : Event()

View file

@ -1,5 +1,5 @@
package info.nightscout.androidaps.events package info.nightscout.androidaps.events
import info.nightscout.androidaps.plugins.treatments.Treatment import info.nightscout.androidaps.db.Treatment
class EventTreatmentChange(val treatment: Treatment?) : EventLoop() class EventTreatmentChange(val treatment: Treatment?) : EventLoop()

View file

@ -3,10 +3,10 @@ package info.nightscout.androidaps.historyBrowser
import android.app.DatePickerDialog import android.app.DatePickerDialog
import android.graphics.Color import android.graphics.Color
import android.os.Bundle import android.os.Bundle
import android.os.SystemClock
import android.util.DisplayMetrics import android.util.DisplayMetrics
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.LinearLayout import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView import android.widget.TextView
import com.jjoe64.graphview.GraphView import com.jjoe64.graphview.GraphView
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
@ -15,12 +15,13 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.events.EventCustomCalculationFinished import info.nightscout.androidaps.events.EventCustomCalculationFinished
import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.general.overview.OverviewMenus import info.nightscout.androidaps.plugins.general.overview.OverviewMenus
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
@ -33,6 +34,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_historybrowse.* import kotlinx.android.synthetic.main.activity_historybrowse.*
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
@ -49,11 +51,13 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var iobCobStaticCalculatorPlugin: IobCobStaticCalculatorPlugin @Inject lateinit var iobCobCalculatorPluginHistory: IobCobCalculatorPluginHistory
@Inject lateinit var treatmentsPluginHistory: TreatmentsPluginHistory
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var overviewMenus: OverviewMenus @Inject lateinit var overviewMenus: OverviewMenus
@Inject lateinit var dateUtil: DateUtil
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@ -72,12 +76,10 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
historybrowse_left.setOnClickListener { historybrowse_left.setOnClickListener {
start -= T.hours(rangeToDisplay.toLong()).msecs() start -= T.hours(rangeToDisplay.toLong()).msecs()
updateGUI("onClickLeft")
runCalculation("onClickLeft") runCalculation("onClickLeft")
} }
historybrowse_right.setOnClickListener { historybrowse_right.setOnClickListener {
start += T.hours(rangeToDisplay.toLong()).msecs() start += T.hours(rangeToDisplay.toLong()).msecs()
updateGUI("onClickRight")
runCalculation("onClickRight") runCalculation("onClickRight")
} }
historybrowse_end.setOnClickListener { historybrowse_end.setOnClickListener {
@ -88,13 +90,12 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
calendar[Calendar.MINUTE] = 0 calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] = 0 calendar[Calendar.HOUR_OF_DAY] = 0
start = calendar.timeInMillis start = calendar.timeInMillis
updateGUI("onClickEnd")
runCalculation("onClickEnd") runCalculation("onClickEnd")
} }
historybrowse_zoom.setOnClickListener { historybrowse_zoom.setOnClickListener {
rangeToDisplay += 6 rangeToDisplay += 6
rangeToDisplay = if (rangeToDisplay > 24) 6 else rangeToDisplay rangeToDisplay = if (rangeToDisplay > 24) 6 else rangeToDisplay
updateGUI("rangeChange") updateGUI("rangeChange", false)
} }
historybrowse_zoom.setOnLongClickListener { historybrowse_zoom.setOnLongClickListener {
val calendar = Calendar.getInstance() val calendar = Calendar.getInstance()
@ -104,7 +105,6 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
calendar[Calendar.MINUTE] = 0 calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] = 0 calendar[Calendar.HOUR_OF_DAY] = 0
start = calendar.timeInMillis start = calendar.timeInMillis
updateGUI("resetToMidnight")
runCalculation("onLongClickZoom") runCalculation("onLongClickZoom")
true true
} }
@ -113,12 +113,15 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
val cal = Calendar.getInstance() val cal = Calendar.getInstance()
cal.timeInMillis = start cal.timeInMillis = start
cal.set(Calendar.YEAR, year) cal[Calendar.YEAR] = year
cal.set(Calendar.MONTH, monthOfYear) cal[Calendar.MONTH] = monthOfYear
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) cal[Calendar.DAY_OF_MONTH] = dayOfMonth
cal[Calendar.MILLISECOND] = 0
cal[Calendar.SECOND] = 0
cal[Calendar.MINUTE] = 0
cal[Calendar.HOUR_OF_DAY] = 0
start = cal.timeInMillis start = cal.timeInMillis
historybrowse_date?.text = DateUtil.dateAndTimeString(start) historybrowse_date?.text = dateUtil.dateAndTimeString(start)
updateGUI("onClickDate")
runCalculation("onClickDate") runCalculation("onClickDate")
} }
@ -142,24 +145,38 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
overviewMenus.setupChartMenu(overview_chartMenuButton) overviewMenus.setupChartMenu(overview_chartMenuButton)
prepareGraphs() prepareGraphs()
savedInstanceState?.let { bundle ->
rangeToDisplay = bundle.getInt("rangeToDisplay", 0)
start = bundle.getLong("start", 0)
}
} }
public override fun onPause() { public override fun onPause() {
super.onPause() super.onPause()
disposable.clear() disposable.clear()
iobCobStaticCalculatorPlugin.stopCalculation("onPause") iobCobCalculatorPluginHistory.stopCalculation("onPause")
} }
public override fun onResume() { public override fun onResume() {
super.onResume() super.onResume()
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished::class.java) .toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(Schedulers.io())
.subscribe({ event: EventAutosensCalculationFinished -> .subscribe({
// catch only events from iobCobStaticCalculatorPlugin // catch only events from iobCobCalculatorPluginHistory
if (event.cause === eventCustomCalculationFinished) { if (it.cause is EventCustomCalculationFinished) {
aapsLogger.debug(LTag.AUTOSENS, "EventAutosensCalculationFinished") updateGUI("EventAutosensCalculationFinished", bgOnly = false)
updateGUI("EventAutosensCalculationFinished") }
}) { fabricPrivacy::logException }
)
disposable.add(rxBus
.toObservable(EventAutosensBgLoaded::class.java)
.observeOn(Schedulers.io())
.subscribe({
// catch only events from iobCobCalculatorPluginHistory
if (it.cause is EventCustomCalculationFinished) {
updateGUI("EventAutosensCalculationFinished", bgOnly = true)
} }
}) { fabricPrivacy::logException } }) { fabricPrivacy::logException }
) )
@ -172,21 +189,32 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
.toObservable(EventRefreshOverview::class.java) .toObservable(EventRefreshOverview::class.java)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ .subscribe({
prepareGraphs() if (it.now) {
updateGUI("EventRefreshOverview") prepareGraphs()
updateGUI("EventRefreshOverview", bgOnly = false)
}
}) { fabricPrivacy::logException } }) { fabricPrivacy::logException }
) )
// set start of current day if (start == 0L) {
val calendar = Calendar.getInstance() // set start of current day
calendar.timeInMillis = System.currentTimeMillis() val calendar = Calendar.getInstance()
calendar[Calendar.MILLISECOND] = 0 calendar.timeInMillis = System.currentTimeMillis()
calendar[Calendar.SECOND] = 0 calendar[Calendar.MILLISECOND] = 0
calendar[Calendar.MINUTE] = 0 calendar[Calendar.SECOND] = 0
calendar[Calendar.HOUR_OF_DAY] = 0 calendar[Calendar.MINUTE] = 0
start = calendar.timeInMillis calendar[Calendar.HOUR_OF_DAY] = 0
runCalculation("onResume") start = calendar.timeInMillis
SystemClock.sleep(1000) runCalculation("onResume")
updateGUI("onResume") } else {
updateGUI("onResume", bgOnly = false)
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("rangeToDisplay", rangeToDisplay)
outState.putLong("start", start)
} }
private fun prepareGraphs() { private fun prepareGraphs() {
@ -199,19 +227,28 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
secondaryGraphsLabel.clear() secondaryGraphsLabel.clear()
history_iobgraph.removeAllViews() history_iobgraph.removeAllViews()
for (i in 1 until numOfGraphs) { for (i in 1 until numOfGraphs) {
val label = TextView(this) val relativeLayout = RelativeLayout(this)
label.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(100, 0, 0, -50) } relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
history_iobgraph.addView(label)
secondaryGraphsLabel.add(label)
val graph = GraphView(this) val graph = GraphView(this)
graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, 0, 0, resourceHelper.dpToPx(10)) } graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, resourceHelper.dpToPx(15), 0, resourceHelper.dpToPx(10)) }
graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid)
graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.reloadStyles()
graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.isHorizontalLabelsVisible = false
graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.labelVerticalWidth = axisWidth
graph.gridLabelRenderer?.numVerticalLabels = 3 graph.gridLabelRenderer?.numVerticalLabels = 3
graph.viewport.backgroundColor = Color.argb(20, 255, 255, 255) // 8% of gray graph.viewport.backgroundColor = Color.argb(20, 255, 255, 255) // 8% of gray
history_iobgraph.addView(graph) relativeLayout.addView(graph)
val label = TextView(this)
val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(resourceHelper.dpToPx(30), resourceHelper.dpToPx(25), 0, 0) }
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
label.layoutParams = layoutParams
relativeLayout.addView(label)
secondaryGraphsLabel.add(label)
history_iobgraph.addView(relativeLayout)
secondaryGraphs.add(graph) secondaryGraphs.add(graph)
} }
} }
@ -219,36 +256,38 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
} }
private fun runCalculation(from: String) { private fun runCalculation(from: String) {
val end = start + T.hours(rangeToDisplay.toLong()).msecs() GlobalScope.launch(Dispatchers.Default) {
iobCobStaticCalculatorPlugin.stopCalculation(from) treatmentsPluginHistory.initializeData(start - T.hours(8).msecs())
iobCobStaticCalculatorPlugin.clearCache() val end = start + T.hours(rangeToDisplay.toLong()).msecs()
iobCobStaticCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished) iobCobCalculatorPluginHistory.stopCalculation(from)
iobCobCalculatorPluginHistory.clearCache()
iobCobCalculatorPluginHistory.runCalculation(from, end, true, false, eventCustomCalculationFinished)
}
} }
@Synchronized fun updateGUI(from: String, bgOnly: Boolean) {
fun updateGUI(from: String) {
aapsLogger.debug(LTag.UI, "updateGUI from: $from") aapsLogger.debug(LTag.UI, "updateGUI from: $from")
val pump = activePlugin.activePump val pump = activePlugin.activePump
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
historybrowse_noprofile?.visibility = (profile == null).toVisibility()
profile ?: return
val lowLine = defaultValueHelper.determineLowLine() val lowLine = defaultValueHelper.determineLowLine()
val highLine = defaultValueHelper.determineHighLine() val highLine = defaultValueHelper.determineHighLine()
historybrowse_date?.text = DateUtil.dateAndTimeString(start)
historybrowse_zoom?.text = rangeToDisplay.toString()
GlobalScope.launch(Dispatchers.Main) { GlobalScope.launch(Dispatchers.Main) {
historybrowse_noprofile?.visibility = (profile == null).toVisibility()
profile ?: return@launch
historybrowse_bggraph ?: return@launch historybrowse_bggraph ?: return@launch
val graphData = GraphData(injector, historybrowse_bggraph, iobCobStaticCalculatorPlugin) historybrowse_date?.text = dateUtil.dateAndTimeString(start)
historybrowse_zoom?.text = rangeToDisplay.toString()
val graphData = GraphData(injector, historybrowse_bggraph, iobCobCalculatorPluginHistory, treatmentsPluginHistory)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList() val secondaryGraphsData: ArrayList<GraphData> = ArrayList()
// do preparation in different thread // do preparation in different thread
withContext(Dispatchers.Default) { withContext(Dispatchers.Default) {
val fromTime: Long = start + T.secs(100).msecs() val fromTime: Long = start + T.secs(100).msecs()
val toTime: Long = start + T.hours(rangeToDisplay.toLong()).msecs() val toTime: Long = start + T.hours(rangeToDisplay.toLong()).msecs() + T.secs(100).msecs()
aapsLogger.debug(LTag.UI, "Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime)) aapsLogger.debug(LTag.UI, "Period: " + dateUtil.dateAndTimeString(fromTime) + " - " + dateUtil.dateAndTimeString(toTime))
val pointer = System.currentTimeMillis() val pointer = System.currentTimeMillis()
// **** In range Area **** // **** In range Area ****
@ -260,71 +299,73 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
// set manual x bounds to have nice steps // set manual x bounds to have nice steps
graphData.formatAxis(fromTime, toTime) graphData.formatAxis(fromTime, toTime)
// Treatments
graphData.addTreatments(fromTime, toTime)
if (overviewMenus.setting[0][OverviewMenus.CharType.ACT.ordinal])
graphData.addActivity(fromTime, toTime, false, 0.8)
// add basal data
if (pump.pumpDescription.isTempBasalCapable && overviewMenus.setting[0][OverviewMenus.CharType.BAS.ordinal]) {
graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2)
}
// add target line // add target line
graphData.addTargetLine(fromTime, toTime, profile, null) graphData.addTargetLine(fromTime, toTime, profile, null)
// **** NOW line **** // **** NOW line ****
graphData.addNowLine(pointer) graphData.addNowLine(pointer)
// ------------------ 2nd graph if (!bgOnly) {
for (g in 0 until secondaryGraphs.size) { // Treatments
val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobStaticCalculatorPlugin) graphData.addTreatments(fromTime, toTime)
var useIobForScale = false if (overviewMenus.setting[0][OverviewMenus.CharType.ACT.ordinal])
var useCobForScale = false graphData.addActivity(fromTime, toTime, false, 0.8)
var useDevForScale = false
var useRatioForScale = false // add basal data
var useDSForScale = false if (pump.pumpDescription.isTempBasalCapable && overviewMenus.setting[0][OverviewMenus.CharType.BAS.ordinal]) {
var useIAForScale = false graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2)
var useABSForScale = false
when {
overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] -> useIAForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true
} }
// ------------------ 2nd graph
for (g in 0 until secondaryGraphs.size) {
val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobCalculatorPluginHistory, treatmentsPluginHistory)
var useIobForScale = false
var useCobForScale = false
var useDevForScale = false
var useRatioForScale = false
var useDSForScale = false
var useIAForScale = false
var useABSForScale = false
when {
overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] -> useIAForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true
}
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(fromTime, toTime, useIobForScale, 1.0, overviewMenus.setting[g + 1][OverviewMenus.CharType.PRE.ordinal]) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(fromTime, toTime, useIobForScale, 1.0, overviewMenus.setting[g + 1][OverviewMenus.CharType.PRE.ordinal])
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, toTime, useCobForScale, if (useCobForScale) 1.0 else 0.5) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, toTime, useCobForScale, if (useCobForScale) 1.0 else 0.5)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1.0)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1.0)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal]) secondGraphData.addActivity(fromTime, toTime, useIAForScale, 0.8) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal]) secondGraphData.addActivity(fromTime, toTime, useIAForScale, 0.8)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, toTime, useABSForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, toTime, useABSForScale, 1.0)
if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1.0)
// set manual x bounds to have nice steps // set manual x bounds to have nice steps
secondGraphData.formatAxis(fromTime, toTime) secondGraphData.formatAxis(fromTime, toTime)
secondGraphData.addNowLine(pointer) secondGraphData.addNowLine(pointer)
secondaryGraphsData.add(secondGraphData) secondaryGraphsData.add(secondGraphData)
}
} }
} }
// finally enforce drawing of graphs in UI thread // finally enforce drawing of graphs in UI thread
graphData.performUpdate() graphData.performUpdate()
for (g in 0 until secondaryGraphs.size) { if (!bgOnly)
secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1) for (g in 0 until secondaryGraphs.size) {
secondaryGraphs[g].visibility = ( secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1)
overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] || secondaryGraphs[g].visibility = (!bgOnly && (
overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] ||
overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] ||
).toVisibility() overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal]
secondaryGraphsData[g].performUpdate() )).toVisibility()
} secondaryGraphsData[g].performUpdate()
}
} }
} }
} }

View file

@ -2,20 +2,22 @@ package info.nightscout.androidaps.historyBrowser
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton
class IobCobStaticCalculatorPlugin @Inject constructor( @Singleton
class IobCobCalculatorPluginHistory @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
rxBus: RxBusWrapper, rxBus: RxBusWrapper,
@ -23,13 +25,14 @@ class IobCobStaticCalculatorPlugin @Inject constructor(
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
profileFunction: ProfileFunction, profileFunction: ProfileFunction,
activePlugin: ActivePluginProvider, activePlugin: ActivePluginProvider,
treatmentsPlugin: TreatmentsPlugin, treatmentsPluginHistory: TreatmentsPluginHistory,
sensitivityOref1Plugin: SensitivityOref1Plugin, sensitivityOref1Plugin: SensitivityOref1Plugin,
sensitivityAAPSPlugin: SensitivityAAPSPlugin, sensitivityAAPSPlugin: SensitivityAAPSPlugin,
sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin, sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin,
fabricPrivacy: FabricPrivacy fabricPrivacy: FabricPrivacy,
dateUtil: DateUtil
) : IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction, ) : IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction,
activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy) { activePlugin, treatmentsPluginHistory, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil) {
override fun onStart() { // do not attach to rxbus override fun onStart() { // do not attach to rxbus
} }

View file

@ -0,0 +1,41 @@
package info.nightscout.androidaps.historyBrowser
import android.content.Context
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TreatmentsPluginHistory @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
context: Context,
sp: SP,
profileFunction: ProfileFunction,
activePlugin: ActivePluginProvider,
nsUpload: NSUpload,
fabricPrivacy: FabricPrivacy, dateUtil: DateUtil
) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil) {
init {
onStart()
}
override fun onStart() {
service = TreatmentService(injector)
initializeData(range())
}
}

View file

@ -4,7 +4,7 @@ import org.mozilla.javascript.ScriptableObject;
import javax.inject.Inject; import javax.inject.Inject;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.StaticInjector;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
@ -26,7 +26,7 @@ public class LoggerCallback extends ScriptableObject {
//empty constructor needed for Rhino //empty constructor needed for Rhino
errorBuffer = new StringBuffer(); errorBuffer = new StringBuffer();
logBuffer = new StringBuffer(); logBuffer = new StringBuffer();
MainApp.instance().androidInjector().inject(this); StaticInjector.Companion.getInstance().androidInjector().inject(this);
} }
@Override @Override

View file

@ -0,0 +1,15 @@
package info.nightscout.androidaps.plugins.aps.loop
import android.content.Context
import android.content.Intent
import dagger.android.DaggerBroadcastReceiver
import javax.inject.Inject
class CarbSuggestionReceiver : DaggerBroadcastReceiver() {
@Inject lateinit var loopPlugin: LoopPlugin
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
val duration = intent.getIntExtra("ignoreDuration", 5)
loopPlugin.disableCarbSuggestions(duration)
}
}

View file

@ -29,6 +29,7 @@ class LoopFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var loopPlugin: LoopPlugin
@Inject lateinit var dateUtil: DateUtil
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -81,12 +82,12 @@ class LoopFragment : DaggerFragment() {
loop_request?.text = it.request?.toSpanned() ?: "" loop_request?.text = it.request?.toSpanned() ?: ""
loop_constraintsprocessed?.text = it.constraintsProcessed?.toSpanned() ?: "" loop_constraintsprocessed?.text = it.constraintsProcessed?.toSpanned() ?: ""
loop_source?.text = it.source ?: "" loop_source?.text = it.source ?: ""
loop_lastrun?.text = DateUtil.dateAndTimeString(it.lastAPSRun) loop_lastrun?.text = dateUtil.dateAndTimeString(it.lastAPSRun)
?: "" ?: ""
loop_smbrequest_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest) loop_smbrequest_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest)
loop_smbexecution_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact) loop_smbexecution_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact)
loop_tbrrequest_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest) loop_tbrrequest_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest)
loop_tbrexecution_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastTBREnact) loop_tbrexecution_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBREnact)
loop_tbrsetbypump?.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml()) } loop_tbrsetbypump?.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml()) }
?: "" ?: ""

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.aps.loop; package info.nightscout.androidaps.plugins.aps.loop;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel; import android.app.NotificationChannel;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
@ -22,6 +21,7 @@ import javax.inject.Singleton;
import dagger.Lazy; import dagger.Lazy;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -41,9 +41,11 @@ import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.LoopInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
@ -53,7 +55,9 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
@ -65,15 +69,15 @@ import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.receivers.ReceiverStatusStore;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import info.nightscout.androidaps.utils.HardLimits;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class LoopPlugin extends PluginBase { public class LoopPlugin extends PluginBase implements LoopInterface {
private final HasAndroidInjector injector; private final HasAndroidInjector injector;
private final SP sp; private final SP sp;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
@ -89,7 +93,9 @@ public class LoopPlugin extends PluginBase {
private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final ReceiverStatusStore receiverStatusStore; private final ReceiverStatusStore receiverStatusStore;
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final NSUpload nsUpload;
private final HardLimits hardLimits; private final HardLimits hardLimits;
private Notification notification;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
@ -101,21 +107,18 @@ public class LoopPlugin extends PluginBase {
private boolean isSuperBolus; private boolean isSuperBolus;
private boolean isDisconnected; private boolean isDisconnected;
public class LastRun { private long carbsSuggestionsSuspendedUntil = 0;
public APSResult request = null; private int prevCarbsreq = 0;
public APSResult constraintsProcessed = null;
public PumpEnactResult tbrSetByPump = null; @Nullable private LastRun lastRun = null;
public PumpEnactResult smbSetByPump = null;
public String source = null; @Nullable @Override public LastRun getLastRun() {
public long lastAPSRun = DateUtil.now(); return lastRun;
public long lastTBREnact = 0;
public long lastSMBEnact = 0;
public long lastTBRRequest = 0;
public long lastSMBRequest = 0;
public long lastOpenModeAccept;
} }
@Nullable public LastRun lastRun = null; @Override public void setLastRun(@Nullable LastRun lastRun) {
this.lastRun = lastRun;
}
@Inject @Inject
public LoopPlugin( public LoopPlugin(
@ -135,6 +138,7 @@ public class LoopPlugin extends PluginBase {
IobCobCalculatorPlugin iobCobCalculatorPlugin, IobCobCalculatorPlugin iobCobCalculatorPlugin,
ReceiverStatusStore receiverStatusStore, ReceiverStatusStore receiverStatusStore,
FabricPrivacy fabricPrivacy, FabricPrivacy fabricPrivacy,
NSUpload nsUpload,
HardLimits hardLimits HardLimits hardLimits
) { ) {
super(new PluginDescription() super(new PluginDescription()
@ -161,6 +165,7 @@ public class LoopPlugin extends PluginBase {
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.receiverStatusStore = receiverStatusStore; this.receiverStatusStore = receiverStatusStore;
this.fabricPrivacy = fabricPrivacy; this.fabricPrivacy = fabricPrivacy;
this.nsUpload = nsUpload;
this.hardLimits = hardLimits; this.hardLimits = hardLimits;
loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L); loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L);
@ -292,7 +297,7 @@ public class LoopPlugin extends PluginBase {
return true; return true;
} }
public boolean isLGS(){ public boolean isLGS() {
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value();
String APSmode = sp.getString(R.string.key_aps_mode, "open"); String APSmode = sp.getString(R.string.key_aps_mode, "open");
@ -333,6 +338,14 @@ public class LoopPlugin extends PluginBase {
} }
return isDisconnected; return isDisconnected;
} }
public boolean treatmentTimethreshold(int duartionMinutes) {
long threshold = System.currentTimeMillis() + (duartionMinutes*60*1000);
boolean bool = false;
if (treatmentsPlugin.getLastBolusTime() > threshold || treatmentsPlugin.getLastCarbTime() > threshold)
bool = true;
return bool;
}
public synchronized void invoke(String initiator, boolean allowNotification) { public synchronized void invoke(String initiator, boolean allowNotification) {
invoke(initiator, allowNotification, false); invoke(initiator, allowNotification, false);
@ -384,7 +397,7 @@ public class LoopPlugin extends PluginBase {
} }
result.percent = (int) (result.rate / profile.getBasal() * 100); result.percent = (int) (result.rate / profile.getBasal() * 100);
// check rate for constrais // check rate for constraints
final APSResult resultAfterConstraints = result.newAndClone(injector); final APSResult resultAfterConstraints = result.newAndClone(injector);
resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate); resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate);
resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value();
@ -402,19 +415,23 @@ public class LoopPlugin extends PluginBase {
resultAfterConstraints.smb = 0; resultAfterConstraints.smb = 0;
} }
if (lastRun == null) lastRun = new LastRun(); if (lastRun != null) {
lastRun.request = result; prevCarbsreq = lastRun.getConstraintsProcessed().carbsReq;
lastRun.constraintsProcessed = resultAfterConstraints; }
lastRun.lastAPSRun = DateUtil.now();
lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
lastRun.lastTBREnact = 0;
lastRun.lastTBRRequest = 0;
lastRun.lastSMBEnact = 0;
lastRun.lastSMBRequest = 0;
NSUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore); if (lastRun == null) lastRun = new LastRun();
lastRun.setRequest(result);
lastRun.setConstraintsProcessed(resultAfterConstraints);
lastRun.setLastAPSRun(DateUtil.now());
lastRun.setSource(((PluginBase) usedAPS).getName());
lastRun.setTbrSetByPump(null);
lastRun.setSmbSetByPump(null);
lastRun.setLastTBREnact(0);
lastRun.setLastTBRRequest(0);
lastRun.setLastSMBEnact(0);
lastRun.setLastSMBRequest(0);
nsUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
if (isSuspended()) { if (isSuspended()) {
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended)); getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended));
@ -431,33 +448,100 @@ public class LoopPlugin extends PluginBase {
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
if (closedLoopEnabled.value()) { if (closedLoopEnabled.value()) {
if (allowNotification) {
if (resultAfterConstraints.isCarbsRequired()
&& resultAfterConstraints.carbsReq >= sp.getInt(R.string.key_smb_enable_carbs_suggestions_threshold, 0)
&& carbsSuggestionsSuspendedUntil < System.currentTimeMillis() && !treatmentTimethreshold(-15)) {
if (sp.getBoolean(R.string.key_enable_carbs_required_alert_local,true) && !sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false)) {
Notification carbreqlocal = new Notification(Notification.CARBS_REQUIRED, resultAfterConstraints.getCarbsRequiredText(), Notification.NORMAL);
rxBus.send(new EventNewNotification(carbreqlocal));
}
if (sp.getBoolean(R.string.key_ns_create_announcements_from_carbs_req, false)) {
nsUpload.uploadError(resultAfterConstraints.getCarbsRequiredText());
}
if (sp.getBoolean(R.string.key_enable_carbs_required_alert_local,true) && sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false)){
Intent intentAction5m = new Intent(context, CarbSuggestionReceiver.class);
intentAction5m.putExtra("ignoreDuration", 5);
PendingIntent pendingIntent5m = PendingIntent.getBroadcast(context, 1, intentAction5m, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action actionIgnore5m = new
NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore5m,"Ignore 5m"), pendingIntent5m);
Intent intentAction15m = new Intent(context, CarbSuggestionReceiver.class);
intentAction15m.putExtra("ignoreDuration", 15);
PendingIntent pendingIntent15m = PendingIntent.getBroadcast(context, 1, intentAction15m, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action actionIgnore15m = new
NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore15m,"Ignore 15m"), pendingIntent15m);
Intent intentAction30m = new Intent(context, CarbSuggestionReceiver.class);
intentAction30m.putExtra("ignoreDuration", 30);
PendingIntent pendingIntent30m = PendingIntent.getBroadcast(context, 1, intentAction30m, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Action actionIgnore30m = new
NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore30m,"Ignore 30m"), pendingIntent30m);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(resourceHelper.gs(R.string.carbssuggestion))
.setContentText(resultAfterConstraints.getCarbsRequiredText())
.setAutoCancel(true)
.setPriority(Notification.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_ALARM)
.addAction(actionIgnore5m)
.addAction(actionIgnore15m)
.addAction(actionIgnore30m)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
rxBus.send(new EventNewOpenLoopNotification());
//only send to wear if Native notifications are turned off
if (!sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false)) {
// Send to Wear
actionStringHandler.get().handleInitiate("changeRequest");
}
}
} else {
//If carbs were required previously, but are no longer needed, dismiss notifications
if ( prevCarbsreq > 0 ) {
dismissSuggestion();
rxBus.send(new EventDismissNotification(Notification.CARBS_REQUIRED));
}
}
}
if (resultAfterConstraints.isChangeRequested() if (resultAfterConstraints.isChangeRequested()
&& !commandQueue.bolusInQueue() && !commandQueue.bolusInQueue()
&& !commandQueue.isRunning(Command.CommandType.BOLUS)) { && !commandQueue.isRunning(Command.CommandType.BOLUS)) {
final PumpEnactResult waiting = new PumpEnactResult(getInjector()); final PumpEnactResult waiting = new PumpEnactResult(getInjector());
waiting.queued = true; waiting.queued = true;
if (resultAfterConstraints.tempBasalRequested) if (resultAfterConstraints.tempBasalRequested)
lastRun.tbrSetByPump = waiting; lastRun.setTbrSetByPump(waiting);
if (resultAfterConstraints.bolusRequested) if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting; lastRun.setSmbSetByPump(waiting);
rxBus.send(new EventLoopUpdateGui()); rxBus.send(new EventLoopUpdateGui());
fabricPrivacy.logCustom("APSRequest"); fabricPrivacy.logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() { applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override @Override
public void run() { public void run() {
if (result.enacted || result.success) { if (result.enacted || result.success) {
lastRun.tbrSetByPump = result; lastRun.setTbrSetByPump(result);
lastRun.lastTBRRequest = lastRun.lastAPSRun; lastRun.setLastTBRRequest(lastRun.getLastAPSRun());
lastRun.lastTBREnact = DateUtil.now(); lastRun.setLastTBREnact(DateUtil.now());
rxBus.send(new EventLoopUpdateGui()); rxBus.send(new EventLoopUpdateGui());
applySMBRequest(resultAfterConstraints, new Callback() { applySMBRequest(resultAfterConstraints, new Callback() {
@Override @Override
public void run() { public void run() {
//Callback is only called if a bolus was acutally requested //Callback is only called if a bolus was acutally requested
if (result.enacted || result.success) { if (result.enacted || result.success) {
lastRun.smbSetByPump = result; lastRun.setTbrSetByPump(result);
lastRun.lastSMBRequest = lastRun.lastAPSRun; lastRun.setLastTBRRequest(lastRun.getLastAPSRun());
lastRun.lastSMBEnact = DateUtil.now(); lastRun.setLastTBREnact(DateUtil.now());
} else { } else {
new Thread(() -> { new Thread(() -> {
SystemClock.sleep(1000); SystemClock.sleep(1000);
@ -472,8 +556,8 @@ public class LoopPlugin extends PluginBase {
} }
}); });
} else { } else {
lastRun.tbrSetByPump = null; lastRun.setTbrSetByPump(null);
lastRun.smbSetByPump = null; lastRun.setSmbSetByPump(null);
} }
} else { } else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) { if (resultAfterConstraints.isChangeRequested() && allowNotification) {
@ -483,42 +567,15 @@ public class LoopPlugin extends PluginBase {
.setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion)) .setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString()) .setContentText(resultAfterConstraints.toString())
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH) .setPriority(Notification.IMPORTANCE_HIGH)
.setCategory(Notification.CATEGORY_ALARM) .setCategory(Notification.CATEGORY_ALARM)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (sp.getBoolean("wearcontrol", false)) { if (sp.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true); builder.setLocalOnly(true);
} }
presentSuggestion(builder);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
rxBus.send(new EventNewOpenLoopNotification());
// Send to Wear
actionStringHandler.get().handleInitiate("changeRequest");
} else if (allowNotification) { } else if (allowNotification) {
// dismiss notifications dismissSuggestion();
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
actionStringHandler.get().handleInitiate("cancelChangeRequest");
} }
} }
@ -528,18 +585,57 @@ public class LoopPlugin extends PluginBase {
} }
} }
public void disableCarbSuggestions(int duartionMinutes) {
carbsSuggestionsSuspendedUntil = System.currentTimeMillis() + (duartionMinutes*60*1000);
dismissSuggestion();
}
private void presentSuggestion(NotificationCompat.Builder builder) {
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
rxBus.send(new EventNewOpenLoopNotification());
// Send to Wear
actionStringHandler.get().handleInitiate("changeRequest");
}
private void dismissSuggestion() {
// dismiss notifications
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(Constants.notificationID);
actionStringHandler.get().handleInitiate("cancelChangeRequest");
}
public void acceptChangeRequest() { public void acceptChangeRequest() {
Profile profile = profileFunction.getProfile(); Profile profile = profileFunction.getProfile();
final LoopPlugin lp = this; final LoopPlugin lp = this;
applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() { applyTBRRequest(lastRun.getConstraintsProcessed(), profile, new Callback() {
@Override @Override
public void run() { public void run() {
if (result.enacted) { if (result.enacted) {
lastRun.tbrSetByPump = result; lastRun.setTbrSetByPump(result);
lastRun.lastTBRRequest = lastRun.lastAPSRun; lastRun.setLastTBRRequest(lastRun.getLastAPSRun());
lastRun.lastTBREnact = DateUtil.now(); lastRun.setLastTBREnact(DateUtil.now());
lastRun.lastOpenModeAccept = DateUtil.now(); lastRun.setLastOpenModeAccept(DateUtil.now());
NSUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore); nsUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
sp.incInt(R.string.key_ObjectivesmanualEnacts); sp.incInt(R.string.key_ObjectivesmanualEnacts);
} }
rxBus.send(new EventAcceptOpenLoopChange()); rxBus.send(new EventAcceptOpenLoopChange());
@ -773,6 +869,7 @@ public class LoopPlugin extends PluginBase {
event.eventType = CareportalEvent.OPENAPSOFFLINE; event.eventType = CareportalEvent.OPENAPSOFFLINE;
event.json = data.toString(); event.json = data.toString();
MainApp.getDbHelper().createOrUpdate(event); MainApp.getDbHelper().createOrUpdate(event);
NSUpload.uploadOpenAPSOffline(event); nsUpload.uploadOpenAPSOffline(event);
} }
} }

View file

@ -32,7 +32,7 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback; import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;

View file

@ -32,6 +32,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject lateinit var dateUtil: DateUtil
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View? {
@ -96,7 +97,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug
} }
if (openAPSAMAPlugin.lastAPSRun != 0L) { if (openAPSAMAPlugin.lastAPSRun != 0L) {
openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun) openapsma_lastrun.text = dateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun)
} }
openAPSAMAPlugin.lastAutosensResult?.let { openAPSAMAPlugin.lastAutosensResult?.let {
openapsma_autosensdata.text = JSONFormatter.format(it.json()) openapsma_autosensdata.text = JSONFormatter.format(it.json())

View file

@ -27,8 +27,8 @@ import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;

View file

@ -26,16 +26,16 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback; import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback;
import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.SafeParse; import info.nightscout.androidaps.utils.SafeParse;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
@ -237,7 +237,8 @@ public class DetermineBasalAdapterSMBJS {
) throws JSONException { ) throws JSONException {
String units = profile.getUnits(); String units = profile.getUnits();
Double pumpbolusstep = activePluginProvider.getActivePump().getPumpDescription().bolusStep; PumpInterface pump = activePluginProvider.getActivePump();
Double pumpbolusstep = pump.getPumpDescription().bolusStep;
mProfile = new JSONObject(); mProfile = new JSONObject();
mProfile.put("max_iob", maxIob); mProfile.put("max_iob", maxIob);
@ -259,13 +260,13 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("low_temptarget_lowers_sensitivity", false); mProfile.put("low_temptarget_lowers_sensitivity", false);
mProfile.put("sensitivity_raises_target", SMBDefaults.sensitivity_raises_target); mProfile.put("sensitivity_raises_target", sp.getBoolean(resourceHelper.gs(R.string.key_sensitivity_raises_target),SMBDefaults.sensitivity_raises_target));
mProfile.put("resistance_lowers_target", SMBDefaults.resistance_lowers_target); mProfile.put("resistance_lowers_target", sp.getBoolean(resourceHelper.gs(R.string.key_resistance_lowers_target),SMBDefaults.resistance_lowers_target));
mProfile.put("adv_target_adjustments", SMBDefaults.adv_target_adjustments); mProfile.put("adv_target_adjustments", SMBDefaults.adv_target_adjustments);
mProfile.put("exercise_mode", SMBDefaults.exercise_mode); mProfile.put("exercise_mode", SMBDefaults.exercise_mode);
mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target); mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target);
mProfile.put("maxCOB", SMBDefaults.maxCOB); mProfile.put("maxCOB", SMBDefaults.maxCOB);
mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps); mProfile.put("skip_neutral_temps", pump.setNeutralTempAtFullHour());
// min_5m_carbimpact is not used within SMB determinebasal // min_5m_carbimpact is not used within SMB determinebasal
//if (mealData.usedMinCarbsImpact > 0) { //if (mealData.usedMinCarbsImpact > 0) {
// mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact);

View file

@ -3,13 +3,17 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class DetermineBasalResultSMB extends APSResult { public class DetermineBasalResultSMB extends APSResult {
@Inject SP sp;
private double eventualBG; private double eventualBG;
private double snoozeBG; private double snoozeBG;
@ -33,7 +37,10 @@ public class DetermineBasalResultSMB extends APSResult {
if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG"); if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG");
if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG"); if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG");
//if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq"); //if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq");
//if (result.has("carbsReq")) carbsReq = result.getDouble("carbsReq");
if (result.has("carbsReq")) carbsReq = result.getInt("carbsReq");
if (result.has("carbsReqWithin")) carbsReqWithin = result.getInt("carbsReqWithin");
if (result.has("rate") && result.has("duration")) { if (result.has("rate") && result.has("duration")) {
tempBasalRequested = true; tempBasalRequested = true;
@ -51,6 +58,9 @@ public class DetermineBasalResultSMB extends APSResult {
} else { } else {
smb = 0d; smb = 0d;
} }
if (result.has("targetBG")) {
targetBG = result.getDouble("targetBG");
}
if (result.has("deliverAt")) { if (result.has("deliverAt")) {
String date = result.getString("deliverAt"); String date = result.getString("deliverAt");

View file

@ -33,6 +33,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@Inject lateinit var dateUtil: DateUtil
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View? {
@ -99,7 +100,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
} }
} }
if (openAPSSMBPlugin.lastAPSRun != 0L) { if (openAPSSMBPlugin.lastAPSRun != 0L) {
openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSSMBPlugin.lastAPSRun) openapsma_lastrun.text = dateUtil.dateAndTimeString(openAPSSMBPlugin.lastAPSRun)
} }
openAPSSMBPlugin.lastAutosensResult?.let { openAPSSMBPlugin.lastAutosensResult?.let {
openapsma_autosensdata.text = JSONFormatter.format(it.json()) openapsma_autosensdata.text = JSONFormatter.format(it.json())

View file

@ -2,6 +2,9 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import android.content.Context; import android.content.Context;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreference;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.json.JSONException; import org.json.JSONException;
@ -30,8 +33,8 @@ import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
@ -42,6 +45,7 @@ import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton @Singleton
public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface {
@ -56,6 +60,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
private final HardLimits hardLimits; private final HardLimits hardLimits;
private final Profiler profiler; private final Profiler profiler;
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final SP sp;
// last values // last values
DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null; DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null;
@ -77,7 +82,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
IobCobCalculatorPlugin iobCobCalculatorPlugin, IobCobCalculatorPlugin iobCobCalculatorPlugin,
HardLimits hardLimits, HardLimits hardLimits,
Profiler profiler, Profiler profiler,
FabricPrivacy fabricPrivacy FabricPrivacy fabricPrivacy,
SP sp
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.APS) .mainType(PluginType.APS)
@ -100,6 +106,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
this.hardLimits = hardLimits; this.hardLimits = hardLimits;
this.profiler = profiler; this.profiler = profiler;
this.fabricPrivacy = fabricPrivacy; this.fabricPrivacy = fabricPrivacy;
this.sp = sp;
} }
@Override @Override
@ -119,6 +126,25 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
return pump.getPumpDescription().isTempBasalCapable; return pump.getPumpDescription().isTempBasalCapable;
} }
@Override
public void preprocessPreferences(@NotNull PreferenceFragmentCompat preferenceFragment) {
super.preprocessPreferences(preferenceFragment);
boolean smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false);
SwitchPreference withCOB = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_with_COB));
if (withCOB != null) {
withCOB.setVisible(!smbAlwaysEnabled);
}
SwitchPreference withTempTarget = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_with_temptarget));
if (withTempTarget != null) {
withTempTarget.setVisible(!smbAlwaysEnabled);
}
SwitchPreference afterCarbs = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_after_carbs));
if (afterCarbs != null) {
afterCarbs.setVisible(!smbAlwaysEnabled);
}
}
@Override @Override
public APSResult getLastAPSResult() { public APSResult getLastAPSResult() {
return lastAPSResult; return lastAPSResult;
@ -174,7 +200,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
long startPart = System.currentTimeMillis(); long startPart = System.currentTimeMillis();
MealData mealData = iobCobCalculatorPlugin.getMealData(); MealData mealData = iobCobCalculatorPlugin.getMealData();
profiler.log(LTag.APS, "getMealData()", startPart); profiler.log(LTag.APS, "getMealData()", startPart);
Constraint<Double> maxIOBAllowedConstraint = constraintChecker.getMaxIOBAllowed(); Constraint<Double> maxIOBAllowedConstraint = constraintChecker.getMaxIOBAllowed();
inputConstraints.copyReasons(maxIOBAllowedConstraint); inputConstraints.copyReasons(maxIOBAllowedConstraint);
@ -219,7 +245,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
} }
IobTotal[] iobArray = iobCobCalculatorPlugin.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget); IobTotal[] iobArray = iobCobCalculatorPlugin.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget);
profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart); profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart);
startPart = System.currentTimeMillis(); startPart = System.currentTimeMillis();
Constraint<Boolean> smbAllowed = new Constraint<>(!tempBasalFallback); Constraint<Boolean> smbAllowed = new Constraint<>(!tempBasalFallback);
@ -234,8 +260,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
constraintChecker.isUAMEnabled(uam); constraintChecker.isUAMEnabled(uam);
inputConstraints.copyReasons(uam); inputConstraints.copyReasons(uam);
profiler.log(LTag.APS, "detectSensitivityandCarbAbsorption()", startPart); profiler.log(LTag.APS, "detectSensitivityandCarbAbsorption()", startPart);
profiler.log(LTag.APS, "SMB data gathering", start); profiler.log(LTag.APS, "SMB data gathering", start);
start = System.currentTimeMillis(); start = System.currentTimeMillis();
try { try {
@ -254,7 +280,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke(); DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke();
profiler.log(LTag.APS, "SMB calculation", start); profiler.log(LTag.APS, "SMB calculation", start);
if (determineBasalResultSMB == null) { if (determineBasalResultSMB == null) {
getAapsLogger().error(LTag.APS, "SMB calculation returned null"); getAapsLogger().error(LTag.APS, "SMB calculation returned null");
lastDetermineBasalAdapterSMBJS = null; lastDetermineBasalAdapterSMBJS = null;

View file

@ -12,6 +12,7 @@ import android.widget.RadioButton
import android.widget.TextView import android.widget.TextView
import androidx.annotation.StringRes import androidx.annotation.StringRes
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.events.EventRebuildTabs
@ -20,9 +21,9 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui
import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.extensions.toVisibility
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.configbuilder_fragment.* import kotlinx.android.synthetic.main.configbuilder_fragment.*
@ -36,6 +37,7 @@ class ConfigBuilderFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var protectionCheck: ProtectionCheck
@Inject lateinit var config: Config
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private val pluginViewHolders = ArrayList<PluginViewHolder>() private val pluginViewHolders = ArrayList<PluginViewHolder>()
@ -86,14 +88,20 @@ class ConfigBuilderFragment : DaggerFragment() {
@Synchronized @Synchronized
private fun updateGUI() { private fun updateGUI() {
configbuilder_categories.removeAllViews() configbuilder_categories.removeAllViews()
createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, activePlugin.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE)) if (!config.NSCLIENT) {
createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, activePlugin.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE))
}
createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, activePlugin.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN)) createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, activePlugin.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN))
createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, activePlugin.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE)) if (!config.NSCLIENT) {
createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, activePlugin.getSpecificPluginsVisibleInList(PluginType.PUMP)) createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, activePlugin.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE))
createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, activePlugin.getSpecificPluginsVisibleInList(PluginType.PUMP))
}
createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, activePlugin.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY)) createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, activePlugin.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY))
createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, activePlugin.getSpecificPluginsVisibleInList(PluginType.APS)) if (config.APS) {
createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP)) createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, activePlugin.getSpecificPluginsVisibleInList(PluginType.APS))
createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS)) createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP))
createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS))
}
createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, activePlugin.getSpecificPluginsVisibleInList(PluginType.TREATMENT)) createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, activePlugin.getSpecificPluginsVisibleInList(PluginType.TREATMENT))
createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, activePlugin.getSpecificPluginsVisibleInList(PluginType.GENERAL)) createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, activePlugin.getSpecificPluginsVisibleInList(PluginType.GENERAL))
} }

View file

@ -36,7 +36,7 @@ class ConfigBuilderPlugin @Inject constructor(
.shortName(R.string.configbuilder_shortname) .shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder), .description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
) { ), ConfigBuilderInterface {
fun initialize() { fun initialize() {
(activePlugin as PluginStore).loadDefaults() (activePlugin as PluginStore).loadDefaults()
@ -52,7 +52,7 @@ class ConfigBuilderPlugin @Inject constructor(
storeSettings("setAlwaysEnabledPluginsEnabled") storeSettings("setAlwaysEnabledPluginsEnabled")
} }
fun storeSettings(from: String) { override fun storeSettings(from: String) {
activePlugin.pluginsList activePlugin.pluginsList
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from") aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from")
activePlugin.verifySelectionInCategories() activePlugin.verifySelectionInCategories()

View file

@ -9,7 +9,8 @@ import javax.inject.Singleton
@Singleton @Singleton
class PluginStore @Inject constructor( class PluginStore @Inject constructor(
val aapsLogger: AAPSLogger private val aapsLogger: AAPSLogger,
private val config: Config
) : ActivePluginProvider { ) : ActivePluginProvider {
lateinit var plugins: List<@JvmSuppressWildcards PluginBase> lateinit var plugins: List<@JvmSuppressWildcards PluginBase>
@ -68,7 +69,7 @@ class PluginStore @Inject constructor(
var pluginsInCategory: ArrayList<PluginBase>? var pluginsInCategory: ArrayList<PluginBase>?
// PluginType.APS // PluginType.APS
if (!Config.NSCLIENT && !Config.PUMPCONTROL) { if (!config.NSCLIENT && !config.PUMPCONTROL) {
pluginsInCategory = getSpecificPluginsList(PluginType.APS) pluginsInCategory = getSpecificPluginsList(PluginType.APS)
activeAPS = getTheOneEnabledInArray(pluginsInCategory, PluginType.APS) as APSInterface? activeAPS = getTheOneEnabledInArray(pluginsInCategory, PluginType.APS) as APSInterface?
if (activeAPS == null) { if (activeAPS == null) {
@ -107,7 +108,7 @@ class PluginStore @Inject constructor(
(activeProfile as PluginBase).setPluginEnabled(PluginType.PROFILE, true) (activeProfile as PluginBase).setPluginEnabled(PluginType.PROFILE, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting ProfileInterface") aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting ProfileInterface")
} }
setFragmentVisiblities((activeSensitivity as PluginBase).name, pluginsInCategory, PluginType.PROFILE) setFragmentVisiblities((activeProfile as PluginBase).name, pluginsInCategory, PluginType.PROFILE)
// PluginType.BGSOURCE // PluginType.BGSOURCE
pluginsInCategory = getSpecificPluginsList(PluginType.BGSOURCE) pluginsInCategory = getSpecificPluginsList(PluginType.BGSOURCE)

View file

@ -22,8 +22,8 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog import info.nightscout.androidaps.dialogs.NtpProgressDialog
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus import info.nightscout.androidaps.events.EventNtpStatus
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask
import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.receivers.ReceiverStatusStore
@ -49,6 +49,8 @@ class ObjectivesFragment : DaggerFragment() {
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var objectivesPlugin: ObjectivesPlugin
@Inject lateinit var receiverStatusStore: ReceiverStatusStore @Inject lateinit var receiverStatusStore: ReceiverStatusStore
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var sntpClient: SntpClient
private val objectivesAdapter = ObjectivesAdapter() private val objectivesAdapter = ObjectivesAdapter()
private val handler = Handler(Looper.getMainLooper()) private val handler = Handler(Looper.getMainLooper())
@ -221,7 +223,7 @@ class ObjectivesFragment : DaggerFragment() {
holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2) holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2)
} }
} }
holder.accomplished.text = resourceHelper.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn)) holder.accomplished.text = resourceHelper.gs(R.string.accomplished, dateUtil.dateAndTimeString(objective.accomplishedOn))
holder.accomplished.setTextColor(-0x3e3e3f) holder.accomplished.setTextColor(-0x3e3e3f)
holder.verify.setOnClickListener { holder.verify.setOnClickListener {
receiverStatusStore.updateNetworkStatus() receiverStatusStore.updateNetworkStatus()
@ -236,7 +238,7 @@ class ObjectivesFragment : DaggerFragment() {
Thread { Thread {
NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck")
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0))
SntpClient.ntpTime(object : SntpClient.Callback() { sntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}")
SystemClock.sleep(300) SystemClock.sleep(300)
@ -275,7 +277,7 @@ class ObjectivesFragment : DaggerFragment() {
Thread { Thread {
NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck")
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0))
SntpClient.ntpTime(object : SntpClient.Callback() { sntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() { override fun run() {
aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}")
SystemClock.sleep(300) SystemClock.sleep(300)

View file

@ -24,13 +24,14 @@ class ObjectivesPlugin @Inject constructor(
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper, resourceHelper: ResourceHelper,
private val activePlugin: ActivePluginProvider, private val activePlugin: ActivePluginProvider,
private val sp: SP private val sp: SP,
private val config: Config
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
.fragmentClass(ObjectivesFragment::class.qualifiedName) .fragmentClass(ObjectivesFragment::class.qualifiedName)
.alwaysEnabled(Config.APS) .alwaysEnabled(config.APS)
.showInList(Config.APS) .showInList(config.APS)
.pluginName(R.string.objectives) .pluginName(R.string.objectives)
.shortName(R.string.objectives_shortname) .shortName(R.string.objectives_shortname)
.description(R.string.description_objectives), .description(R.string.description_objectives),

View file

@ -21,6 +21,7 @@ import javax.inject.Inject
class ObjectivesExamDialog : DaggerDialogFragment() { class ObjectivesExamDialog : DaggerDialogFragment() {
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var dateUtil: DateUtil
companion object { companion object {
var objective: Objective? = null var objective: Objective? = null
@ -76,7 +77,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() {
objectives_exam_hints.addView(h.generate(context)) objectives_exam_hints.addView(h.generate(context))
} }
// Disabled to // Disabled to
objectives_exam_disabledto.text = resourceHelper.gs(R.string.answerdisabledto, DateUtil.timeString(task.disabledTo)) objectives_exam_disabledto.text = resourceHelper.gs(R.string.answerdisabledto, dateUtil.timeString(task.disabledTo))
objectives_exam_disabledto.visibility = if (task.isEnabledAnswer) View.GONE else View.VISIBLE objectives_exam_disabledto.visibility = if (task.isEnabledAnswer) View.GONE else View.VISIBLE
// Buttons // Buttons
objectives_exam_verify.isEnabled = !task.answered && task.isEnabledAnswer objectives_exam_verify.isEnabled = !task.answered && task.isEnabledAnswer

View file

@ -19,7 +19,7 @@ public class Objective2 extends Objective {
@Override @Override
protected void setupTasks(List<Task> tasks) { protected void setupTasks(List<Task> tasks) {
tasks.add(new ExamTask(R.string.dia_label, R.string.dia_whatmeansdia,"dia") tasks.add(new ExamTask(R.string.dia_label_exam, R.string.dia_whatmeansdia,"dia")
.option(new Option(R.string.dia_minimumis3h, false)) .option(new Option(R.string.dia_minimumis3h, false))
.option(new Option(R.string.dia_minimumis5h, true)) .option(new Option(R.string.dia_minimumis5h, true))
.option(new Option(R.string.dia_meaningisequaltodiapump, false)) .option(new Option(R.string.dia_meaningisequaltodiapump, false))
@ -160,7 +160,7 @@ public class Objective2 extends Objective {
.option(new Option(R.string.nsclient_spikeiphone, true)) .option(new Option(R.string.nsclient_spikeiphone, true))
.hint(new Hint(R.string.nsclient_hint1)) .hint(new Hint(R.string.nsclient_hint1))
); );
tasks.add(new ExamTask(R.string.isf_label, R.string.whatistrue,"isf") tasks.add(new ExamTask(R.string.isf_label_exam, R.string.whatistrue,"isf")
.option(new Option(R.string.isf_increasingvalue, true)) .option(new Option(R.string.isf_increasingvalue, true))
.option(new Option(R.string.isf_decreasingvalue, false)) .option(new Option(R.string.isf_decreasingvalue, false))
.option(new Option(R.string.isf_noeffect, false)) .option(new Option(R.string.isf_noeffect, false))
@ -169,7 +169,7 @@ public class Objective2 extends Objective {
.hint(new Hint(R.string.isf_hint1)) .hint(new Hint(R.string.isf_hint1))
.hint(new Hint(R.string.isf_hint2)) .hint(new Hint(R.string.isf_hint2))
); );
tasks.add(new ExamTask(R.string.ic_label, R.string.whatistrue,"ic") tasks.add(new ExamTask(R.string.ic_label_exam, R.string.whatistrue,"ic")
.option(new Option(R.string.ic_increasingvalue, true)) .option(new Option(R.string.ic_increasingvalue, true))
.option(new Option(R.string.ic_decreasingvalue, false)) .option(new Option(R.string.ic_decreasingvalue, false))
.option(new Option(R.string.ic_noeffect, false)) .option(new Option(R.string.ic_noeffect, false))

View file

@ -47,6 +47,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
private HardLimits hardLimits; private HardLimits hardLimits;
private BuildHelper buildHelper; private BuildHelper buildHelper;
private TreatmentsPlugin treatmentsPlugin; private TreatmentsPlugin treatmentsPlugin;
private Config config;
@Inject @Inject
public SafetyPlugin( public SafetyPlugin(
@ -62,7 +63,8 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
ActivePluginProvider activePlugin, ActivePluginProvider activePlugin,
HardLimits hardLimits, HardLimits hardLimits,
BuildHelper buildHelper, BuildHelper buildHelper,
TreatmentsPlugin treatmentsPlugin TreatmentsPlugin treatmentsPlugin,
Config config
) { ) {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.CONSTRAINTS) .mainType(PluginType.CONSTRAINTS)
@ -83,6 +85,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
this.hardLimits = hardLimits; this.hardLimits = hardLimits;
this.buildHelper = buildHelper; this.buildHelper = buildHelper;
this.treatmentsPlugin = treatmentsPlugin; this.treatmentsPlugin = treatmentsPlugin;
this.config = config;
} }
/** /**
@ -159,7 +162,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
absoluteRate.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingbasalratio), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this); absoluteRate.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingbasalratio), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this);
if (Config.APS) { if (config.getAPS()) {
double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d); double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d);
if (maxBasal < profile.getMaxDailyBasal()) { if (maxBasal < profile.getMaxDailyBasal()) {
maxBasal = profile.getMaxDailyBasal(); maxBasal = profile.getMaxDailyBasal();

View file

@ -18,9 +18,9 @@ import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction
import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
@ -54,6 +54,7 @@ class ActionsFragment : DaggerFragment() {
@Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var buildHelper: BuildHelper @Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var protectionCheck: ProtectionCheck
@Inject lateinit var config: Config
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
@ -143,6 +144,12 @@ class ActionsFragment : DaggerFragment() {
actions_exercise.setOnClickListener { actions_exercise.setOnClickListener {
CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions") CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions")
} }
actions_question.setOnClickListener {
CareDialog().setOptions(CareDialog.EventType.QUESTION, R.string.careportal_question).show(childFragmentManager, "Actions")
}
actions_announcement.setOnClickListener {
CareDialog().setOptions(CareDialog.EventType.ANNOUNCEMENT, R.string.careportal_announcement).show(childFragmentManager, "Actions")
}
sp.putBoolean(R.string.key_objectiveuseactions, true) sp.putBoolean(R.string.key_objectiveuseactions, true)
} }
@ -185,23 +192,15 @@ class ActionsFragment : DaggerFragment() {
@Synchronized @Synchronized
fun updateGui() { fun updateGui() {
actions_profileswitch?.visibility = (activePlugin.activeProfileInterface.profile != null).toVisibility()
val profile = profileFunction.getProfile() val profile = profileFunction.getProfile()
val pump = activePlugin.activePump val pump = activePlugin.activePump
actions_temptarget?.visibility = (profile != null).toVisibility() actions_profileswitch?.visibility = (
actions_canceltempbasal.visibility = (profile == null).toVisibility() activePlugin.activeProfileInterface.profile != null &&
actions_settempbasal.visibility = (profile == null).toVisibility() pump.pumpDescription.isSetBasalProfileCapable &&
actions_fill.visibility = (profile == null).toVisibility() pump.isInitialized &&
actions_extendedbolus.visibility = (profile == null).toVisibility() !pump.isSuspended).toVisibility()
actions_extendedbolus_cancel.visibility = (profile == null).toVisibility()
actions_historybrowser.visibility = (profile == null).toVisibility()
actions_tddstats.visibility = (profile == null).toVisibility()
val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE
if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized || pump.isSuspended || pump.isFakingTempsByExtendedBoluses) { if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized || pump.isSuspended || pump.isFakingTempsByExtendedBoluses) {
actions_extendedbolus?.visibility = View.GONE actions_extendedbolus?.visibility = View.GONE
@ -235,12 +234,11 @@ class ActionsFragment : DaggerFragment() {
} }
} }
actions_fill?.visibility = actions_historybrowser.visibility = (profile != null).toVisibility()
if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE actions_fill?.visibility = (pump.pumpDescription.isRefillingCapable && pump.isInitialized && !pump.isSuspended).toVisibility()
else View.VISIBLE actions_temptarget?.visibility = (profile != null && config.APS).toVisibility()
actions_temptarget?.visibility = Config.APS.toVisibility()
actions_tddstats?.visibility = pump.pumpDescription.supportsTDDs.toVisibility() actions_tddstats?.visibility = pump.pumpDescription.supportsTDDs.toVisibility()
statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, null, careportal_sensorage, careportal_pbage, null) statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, null, careportal_sensorage, careportal_pbage, null)
checkPumpCustomActions() checkPumpCustomActions()
} }

View file

@ -15,12 +15,13 @@ import javax.inject.Singleton
class ActionsPlugin @Inject constructor( class ActionsPlugin @Inject constructor(
injector: HasAndroidInjector, injector: HasAndroidInjector,
aapsLogger: AAPSLogger, aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper resourceHelper: ResourceHelper,
config: Config
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(ActionsFragment::class.qualifiedName) .fragmentClass(ActionsFragment::class.qualifiedName)
.enableByDefault(Config.APS || Config.PUMPCONTROL) .enableByDefault(config.APS || config.PUMPCONTROL)
.visibleByDefault(Config.APS || Config.PUMPCONTROL) .visibleByDefault(config.APS || config.PUMPCONTROL)
.pluginName(R.string.actions) .pluginName(R.string.actions)
.shortName(R.string.actions_shortname) .shortName(R.string.actions_shortname)
.description(R.string.description_actions), .description(R.string.description_actions),

View file

@ -4,6 +4,8 @@ import android.content.Context
import android.content.Intent import android.content.Intent
import android.os.Build import android.os.Build
import android.os.Handler import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventBTChange import info.nightscout.androidaps.events.EventBTChange
@ -37,10 +39,8 @@ import io.reactivex.schedulers.Schedulers
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONException import org.json.JSONException
import org.json.JSONObject import org.json.JSONObject
import java.util.*
import javax.inject.Inject import javax.inject.Inject
import javax.inject.Singleton import javax.inject.Singleton
import kotlin.collections.ArrayList
@Singleton @Singleton
class AutomationPlugin @Inject constructor( class AutomationPlugin @Inject constructor(
@ -52,7 +52,8 @@ class AutomationPlugin @Inject constructor(
private val loopPlugin: LoopPlugin, private val loopPlugin: LoopPlugin,
private val rxBus: RxBusWrapper, private val rxBus: RxBusWrapper,
private val constraintChecker: ConstraintChecker, private val constraintChecker: ConstraintChecker,
aapsLogger: AAPSLogger aapsLogger: AAPSLogger,
private val dateUtil: DateUtil
) : PluginBase(PluginDescription() ) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(AutomationFragment::class.qualifiedName) .fragmentClass(AutomationFragment::class.qualifiedName)
@ -71,7 +72,7 @@ class AutomationPlugin @Inject constructor(
var executionLog: MutableList<String> = ArrayList() var executionLog: MutableList<String> = ArrayList()
var btConnects : MutableList<EventBTChange> = ArrayList() var btConnects : MutableList<EventBTChange> = ArrayList()
private val loopHandler = Handler() private val loopHandler : Handler = Handler(HandlerThread(AutomationPlugin::class.java.simpleName + "Handler").also { it.start() }.looper)
private lateinit var refreshLoop: Runnable private lateinit var refreshLoop: Runnable
init { init {
@ -177,10 +178,9 @@ class AutomationPlugin @Inject constructor(
@Synchronized @Synchronized
private fun processActions() { private fun processActions() {
if (!isEnabled(PluginType.GENERAL)) if (loopPlugin.isSuspended || !loopPlugin.isEnabled()) {
return
if (loopPlugin.isSuspended || !loopPlugin.isEnabled(PluginType.LOOP)) {
aapsLogger.debug(LTag.AUTOMATION, "Loop deactivated") aapsLogger.debug(LTag.AUTOMATION, "Loop deactivated")
executionLog.add(resourceHelper.gs(R.string.smscommunicator_loopisdisabled))
return return
} }
val enabled = constraintChecker.isAutomationEnabled() val enabled = constraintChecker.isAutomationEnabled()
@ -197,7 +197,7 @@ class AutomationPlugin @Inject constructor(
action.doAction(object : Callback() { action.doAction(object : Callback() {
override fun run() { override fun run() {
val sb = StringBuilder() val sb = StringBuilder()
sb.append(DateUtil.timeString(DateUtil.now())) sb.append(dateUtil.timeString(DateUtil.now()))
sb.append(" ") sb.append(" ")
sb.append(if (result.success) "" else "") sb.append(if (result.success) "" else "")
sb.append(" <b>") sb.append(" <b>")
@ -212,6 +212,7 @@ class AutomationPlugin @Inject constructor(
} }
}) })
} }
SystemClock.sleep(1100)
event.lastRun = DateUtil.now() event.lastRun = DateUtil.now()
} }
} }

View file

@ -8,7 +8,6 @@ import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject import javax.inject.Inject

View file

@ -12,7 +12,6 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithE
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage
import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
@ -23,6 +22,7 @@ import javax.inject.Inject
class ActionNotification(injector: HasAndroidInjector) : Action(injector) { class ActionNotification(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var nsUpload: NSUpload
var text = InputString(injector) var text = InputString(injector)
@ -33,7 +33,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) {
override fun doAction(callback: Callback) { override fun doAction(callback: Callback) {
val notification = NotificationUserMessage(text.value) val notification = NotificationUserMessage(text.value)
rxBus.send(EventNewNotification(notification)) rxBus.send(EventNewNotification(notification))
NSUpload.uploadError(text.value) nsUpload.uploadError(text.value)
rxBus.send(EventRefreshOverview("ActionNotification")) rxBus.send(EventRefreshOverview("ActionNotification"))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
} }

View file

@ -7,7 +7,7 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
@ -27,7 +27,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) {
override fun friendlyName(): Int = R.string.profilename override fun friendlyName(): Int = R.string.profilename
override fun shortDescription(): String = resourceHelper.gs(R.string.changengetoprofilename, inputProfileName.value) override fun shortDescription(): String = resourceHelper.gs(R.string.changengetoprofilename, inputProfileName.value)
@DrawableRes override fun icon(): Int = R.drawable.icon_actions_profileswitch @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch
override fun doAction(callback: Callback) { override fun doAction(callback: Callback) {
val activeProfileName = profileFunction.getProfileName() val activeProfileName = profileFunction.getProfileName()

View file

@ -30,7 +30,7 @@ class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector
if (duration.value == 0) resourceHelper.gs(R.string.startprofileforever, pct.value.toInt()) if (duration.value == 0) resourceHelper.gs(R.string.startprofileforever, pct.value.toInt())
else resourceHelper.gs(R.string.startprofile, pct.value.toInt(), duration.value) else resourceHelper.gs(R.string.startprofile, pct.value.toInt(), duration.value)
@DrawableRes override fun icon(): Int = R.drawable.icon_actions_profileswitch @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch
init { init {
precondition = TriggerProfilePercent(injector, 100.0, Comparator.Compare.IS_EQUAL) precondition = TriggerProfilePercent(injector, 100.0, Comparator.Compare.IS_EQUAL)

View file

@ -26,7 +26,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) {
override fun doAction(callback: Callback) { override fun doAction(callback: Callback) {
val result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.value) val result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.value)
callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.danar_error))?.run() callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.error))?.run()
} }
override fun toJSON(): String { override fun toJSON(): String {

View file

@ -37,7 +37,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) {
override fun friendlyName(): Int = R.string.starttemptarget override fun friendlyName(): Int = R.string.starttemptarget
override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper) override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper)
@DrawableRes override fun icon(): Int = R.drawable.icon_cp_cgm_target @DrawableRes override fun icon(): Int = R.drawable.ic_cp_cgm_target
override fun doAction(callback: Callback) { override fun doAction(callback: Callback) {
activePlugin.activeTreatments.addToHistoryTempTarget(tt()) activePlugin.activeTreatments.addToHistoryTempTarget(tt())

View file

@ -74,7 +74,7 @@ class Comparator(injector: HasAndroidInjector) : Element(injector) {
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = Compare.values()[position] value = Compare.values()[position]
} }

View file

@ -48,7 +48,7 @@ class ComparatorConnect(injector: HasAndroidInjector) : Element(injector) {
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = Compare.values()[position] value = Compare.values()[position]
} }

View file

@ -48,7 +48,7 @@ class ComparatorExists(injector: HasAndroidInjector) : Element(injector) {
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = Compare.values()[position] value = Compare.values()[position]
} }

View file

@ -4,8 +4,8 @@ import android.widget.LinearLayout
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat import java.text.DecimalFormat
import javax.inject.Inject import javax.inject.Inject

View file

@ -18,6 +18,7 @@ import javax.inject.Inject
class InputDateTime(injector: HasAndroidInjector) : Element(injector) { class InputDateTime(injector: HasAndroidInjector) : Element(injector) {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var context: Context @Inject lateinit var context: Context
@Inject lateinit var dateUtil: DateUtil
var value: Long = DateUtil.now() var value: Long = DateUtil.now()
@ -30,7 +31,7 @@ class InputDateTime(injector: HasAndroidInjector) : Element(injector) {
val dateButton = TextView(root.context) val dateButton = TextView(root.context)
val timeButton = TextView(root.context) val timeButton = TextView(root.context)
dateButton.text = DateUtil.dateString(value) dateButton.text = DateUtil.dateString(value)
timeButton.text = DateUtil.timeString(value) timeButton.text = dateUtil.timeString(value)
// create an OnDateSetListener // create an OnDateSetListener
val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
@ -63,7 +64,7 @@ class InputDateTime(injector: HasAndroidInjector) : Element(injector) {
cal.set(Calendar.MINUTE, minute) cal.set(Calendar.MINUTE, minute)
cal.set(Calendar.SECOND, 0) // randomize seconds to prevent creating record of the same time, if user choose time manually cal.set(Calendar.SECOND, 0) // randomize seconds to prevent creating record of the same time, if user choose time manually
value = cal.timeInMillis value = cal.timeInMillis
timeButton.text = DateUtil.timeString(value) timeButton.text = dateUtil.timeString(value)
} }
timeButton.setOnClickListener { timeButton.setOnClickListener {

View file

@ -9,7 +9,7 @@ import android.widget.Spinner
import androidx.annotation.StringRes import androidx.annotation.StringRes
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.ui.NumberPicker
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.text.DecimalFormat import java.text.DecimalFormat
import java.util.* import java.util.*
@ -76,7 +76,7 @@ class InputDelta(injector: HasAndroidInjector) : Element(injector) {
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
deltaType = DeltaType.values()[position] deltaType = DeltaType.values()[position]
} }

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.elements
import android.widget.LinearLayout import android.widget.LinearLayout
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat import java.text.DecimalFormat
class InputDouble(injector: HasAndroidInjector) : Element(injector) { class InputDouble(injector: HasAndroidInjector) : Element(injector) {

View file

@ -38,7 +38,7 @@ class InputDropdownMenu(injector: HasAndroidInjector) : Element(injector) {
).also { it.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) } ).also { it.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) }
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
setValue(itemList[position].toString()) setValue(itemList[position].toString())
} }

View file

@ -3,7 +3,8 @@ package info.nightscout.androidaps.plugins.general.automation.elements
import android.widget.LinearLayout import android.widget.LinearLayout
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.ui.MinutesNumberPicker
import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat import java.text.DecimalFormat
class InputDuration(injector: HasAndroidInjector) : Element(injector) { class InputDuration(injector: HasAndroidInjector) : Element(injector) {
@ -20,11 +21,14 @@ class InputDuration(injector: HasAndroidInjector) : Element(injector) {
var value: Int = 0 var value: Int = 0
override fun addToLayout(root: LinearLayout) { override fun addToLayout(root: LinearLayout) {
val numberPicker = NumberPicker(root.context, null) val numberPicker : NumberPicker
if (unit == TimeUnit.MINUTES) if (unit == TimeUnit.MINUTES) {
numberPicker = MinutesNumberPicker(root.context, null)
numberPicker.setParams(0.0, 0.0, 24 * 60.0, 10.0, DecimalFormat("0"), false, root.findViewById(R.id.ok)) numberPicker.setParams(0.0, 0.0, 24 * 60.0, 10.0, DecimalFormat("0"), false, root.findViewById(R.id.ok))
else } else {
numberPicker = NumberPicker(root.context, null)
numberPicker.setParams(0.0, 0.0, 24.0, 1.0, DecimalFormat("0"), false, root.findViewById(R.id.ok)) numberPicker.setParams(0.0, 0.0, 24.0, 1.0, DecimalFormat("0"), false, root.findViewById(R.id.ok))
}
numberPicker.value = value.toDouble() numberPicker.value = value.toDouble()
numberPicker.setOnValueChangedListener { value: Double -> this.value = value.toInt() } numberPicker.setOnValueChangedListener { value: Double -> this.value = value.toInt() }
root.addView(numberPicker) root.addView(numberPicker)

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.elements
import android.widget.LinearLayout import android.widget.LinearLayout
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat import java.text.DecimalFormat
class InputInsulin(injector: HasAndroidInjector) : Element(injector) { class InputInsulin(injector: HasAndroidInjector) : Element(injector) {

View file

@ -62,7 +62,7 @@ class InputLocationMode(injector: HasAndroidInjector) : Element(injector) {
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = Mode.values()[position] value = Mode.values()[position]
} }

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.elements
import android.widget.LinearLayout import android.widget.LinearLayout
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat import java.text.DecimalFormat
class InputPercent(injector: HasAndroidInjector) : Element(injector) { class InputPercent(injector: HasAndroidInjector) : Element(injector) {

View file

@ -36,7 +36,7 @@ class InputProfileName(injector: HasAndroidInjector) : Element(injector) {
spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4))
spinner.layoutParams = spinnerParams spinner.layoutParams = spinnerParams
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
value = profileList[position].toString() value = profileList[position].toString()
} }

View file

@ -4,14 +4,18 @@ import android.widget.LinearLayout
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.NumberPicker import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat import java.text.DecimalFormat
import javax.inject.Inject
class InputTempTarget(injector: HasAndroidInjector) : Element(injector) { class InputTempTarget(injector: HasAndroidInjector) : Element(injector) {
var units = Constants.MGDL var units = Constants.MGDL
var value = 0.0 var value = 0.0
@Inject lateinit var profileFunction: ProfileFunction
init { init {
units = profileFunction.getUnits()
value = if (units == Constants.MMOL) 6.0 else 110.0 value = if (units == Constants.MMOL) 6.0 else 110.0
} }

View file

@ -12,7 +12,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
@ -20,17 +19,18 @@ import javax.inject.Inject
class InputTime(injector: HasAndroidInjector) : Element(injector) { class InputTime(injector: HasAndroidInjector) : Element(injector) {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var context: Context @Inject lateinit var context: Context
@Inject lateinit var dateUtil: DateUtil
var value: Int = getMinSinceMidnight(DateUtil.now()) var value: Int = getMinSinceMidnight(DateUtil.now())
override fun addToLayout(root: LinearLayout) { override fun addToLayout(root: LinearLayout) {
val label = TextView(root.context) val label = TextView(root.context)
val startButton = TextView(root.context) val startButton = TextView(root.context)
startButton.text = DateUtil.timeString(toMills(value)) startButton.text = dateUtil.timeString(toMills(value))
val startTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> val startTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
value = 60 * hour + minute value = 60 * hour + minute
startButton.text = DateUtil.timeString(toMills(value)) startButton.text = dateUtil.timeString(toMills(value))
} }
startButton.setOnClickListener { startButton.setOnClickListener {

View file

@ -12,7 +12,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.MidnightTime import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
@ -20,6 +19,7 @@ import javax.inject.Inject
class InputTimeRange(injector: HasAndroidInjector) : Element(injector) { class InputTimeRange(injector: HasAndroidInjector) : Element(injector) {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var context: Context @Inject lateinit var context: Context
@Inject lateinit var dateUtil: DateUtil
var start: Int = getMinSinceMidnight(DateUtil.now()) var start: Int = getMinSinceMidnight(DateUtil.now())
var end: Int = getMinSinceMidnight(DateUtil.now()) var end: Int = getMinSinceMidnight(DateUtil.now())
@ -28,13 +28,13 @@ class InputTimeRange(injector: HasAndroidInjector) : Element(injector) {
val label = TextView(root.context) val label = TextView(root.context)
val startButton = TextView(root.context) val startButton = TextView(root.context)
val endButton = TextView(root.context) val endButton = TextView(root.context)
startButton.text = DateUtil.timeString(toMills(start)) startButton.text = dateUtil.timeString(toMills(start))
@Suppress("SetTextI18n") @Suppress("SetTextI18n")
endButton.text = resourceHelper.gs(R.string.and) + " " + DateUtil.timeString(toMills(end)) endButton.text = resourceHelper.gs(R.string.and) + " " + dateUtil.timeString(toMills(end))
val startTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> val startTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
start = 60 * hour + minute start = 60 * hour + minute
startButton.text = DateUtil.timeString(toMills(start)) startButton.text = dateUtil.timeString(toMills(start))
} }
startButton.setOnClickListener { startButton.setOnClickListener {
@ -51,7 +51,7 @@ class InputTimeRange(injector: HasAndroidInjector) : Element(injector) {
val endTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> val endTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute ->
end = 60 * hour + minute end = 60 * hour + minute
endButton.text = DateUtil.timeString(toMills(end)) endButton.text = dateUtil.timeString(toMills(end))
} }
endButton.setOnClickListener { endButton.setOnClickListener {

View file

@ -13,7 +13,7 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone
@ -98,7 +98,7 @@ abstract class Trigger(val injector: HasAndroidInjector) {
) )
params.gravity = Gravity.CENTER params.gravity = Gravity.CENTER
buttonAdd.layoutParams = params buttonAdd.layoutParams = params
buttonAdd.setImageResource(R.drawable.add) buttonAdd.setImageResource(R.drawable.ic_add)
buttonAdd.contentDescription = resourceHelper.gs(R.string.add_short) buttonAdd.contentDescription = resourceHelper.gs(R.string.add_short)
buttonAdd.setOnClickListener { buttonAdd.setOnClickListener {
scanForActivity(context)?.supportFragmentManager?.let { scanForActivity(context)?.supportFragmentManager?.let {
@ -124,7 +124,7 @@ abstract class Trigger(val injector: HasAndroidInjector) {
) )
params.gravity = Gravity.CENTER params.gravity = Gravity.CENTER
buttonRemove.layoutParams = params buttonRemove.layoutParams = params
buttonRemove.setImageResource(R.drawable.remove) buttonRemove.setImageResource(R.drawable.ic_remove)
buttonRemove.contentDescription = resourceHelper.gs(R.string.delete_short) buttonRemove.contentDescription = resourceHelper.gs(R.string.delete_short)
buttonRemove.setOnClickListener { buttonRemove.setOnClickListener {
rxBus.send(EventTriggerRemove(trigger)) rxBus.send(EventTriggerRemove(trigger))
@ -141,7 +141,7 @@ abstract class Trigger(val injector: HasAndroidInjector) {
) )
params.gravity = Gravity.CENTER params.gravity = Gravity.CENTER
buttonClone.layoutParams = params buttonClone.layoutParams = params
buttonClone.setImageResource(R.drawable.clone) buttonClone.setImageResource(R.drawable.ic_clone)
buttonClone.contentDescription = resourceHelper.gs(R.string.copy_short) buttonClone.contentDescription = resourceHelper.gs(R.string.copy_short)
buttonClone.setOnClickListener { buttonClone.setOnClickListener {
rxBus.send(EventTriggerClone(trigger)) rxBus.send(EventTriggerClone(trigger))

View file

@ -68,7 +68,7 @@ class TriggerAutosensValue(injector: HasAndroidInjector) : Trigger(injector) {
override fun friendlyDescription(): String = override fun friendlyDescription(): String =
resourceHelper.gs(R.string.autosenscompared, resourceHelper.gs(comparator.value.stringRes), autosens.value) resourceHelper.gs(R.string.autosenscompared, resourceHelper.gs(comparator.value.stringRes), autosens.value)
override fun icon(): Optional<Int?> = Optional.of(R.drawable.`as`) override fun icon(): Optional<Int?> = Optional.of(R.drawable.`ic_as`)
override fun duplicate(): Trigger = TriggerAutosensValue(injector, this) override fun duplicate(): Trigger = TriggerAutosensValue(injector, this)

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