diff --git a/.gitignore b/.gitignore index c7ed9df2f5..961dd40194 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ build/ .idea/* !.idea/codeStyles/ -app/src/main/jniLibs full/ debug/ release/ diff --git a/app/build.gradle b/app/build.gradle index 20c70ab9b6..ddd3aae0cc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -124,11 +124,11 @@ android { ndkVersion "21.1.6352462" defaultConfig { - minSdkVersion 23 + minSdkVersion 24 targetSdkVersion 28 multiDexEnabled true versionCode 1500 - version "2.6.5-dev" + version "2.6.6-dev" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' @@ -242,6 +242,9 @@ dependencies { wearApp project(':wear') implementation project(':core') + implementation project(':dana') + implementation project(':danars') + implementation project(':danar') implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.google.android.gms:play-services-wearable:17.0.0' @@ -266,7 +269,6 @@ dependencies { implementation "androidx.activity:activity-ktx:${activityVersion}" implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.android.material:material:1.1.0' - implementation 'com.wdullaer:materialdatetimepicker:4.2.3' implementation "io.reactivex.rxjava2:rxandroid:2.1.1" @@ -355,30 +357,6 @@ dependencies { 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 task clearMainAppData(type: Exec) { @@ -410,8 +388,6 @@ tasks.whenTaskAdded { task -> } } */ -clean.dependsOn full_clean -preBuild.dependsOn copyLibs printf('--------------\n') printf('isMaster: %s\n', isMaster().toString()) diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index 9158c5f119..0a99af2948 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugi import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.source.RandomBgPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin @@ -42,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\"}" - @Inject lateinit var pump : DanaRv2Plugin + @Inject lateinit var pump : info.nightscout.androidaps.danaRv2.DanaRv2Plugin @Inject lateinit var randomBgPlugin :RandomBgPlugin @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var profileFunction: ProfileFunction diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index d2d419b0c0..cb31b1ce3c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -58,15 +58,6 @@ - - - - - @@ -74,14 +65,6 @@ - - - - - - - - @@ -152,22 +135,6 @@ - - - - diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 85d8f83ed7..126ba47d22 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -7,26 +7,21 @@ import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; -import androidx.annotation.StringRes; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.j256.ormlite.android.apptools.OpenHelperManager; import net.danlew.android.joda.JodaTimeAndroid; -import org.jetbrains.annotations.NotNull; - import java.util.List; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; -import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.StaticInjector; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -45,7 +40,7 @@ import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; -public class MainApp extends DaggerApplication implements DatabaseHelperInterface { +public class MainApp extends DaggerApplication { static MainApp sInstance; private static Resources sResources; @@ -57,12 +52,13 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac @Inject ActivityMonitor activityMonitor; @Inject VersionCheckerUtils versionCheckersUtils; @Inject SP sp; + @Inject NSUpload nsUpload; @Inject ConfigBuilderPlugin configBuilderPlugin; @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; @Inject List plugins; - @Inject StaticInjector staticInjector; // TODO remove , fake only to initialize + @Inject StaticInjector staticInjector; // TODO avoid , here fake only to initialize @Override public void onCreate() { @@ -99,7 +95,7 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac pluginStore.setPlugins(plugins); configBuilderPlugin.initialize(); - NSUpload.uploadAppStart(); + nsUpload.uploadAppStart(); new Thread(() -> keepAliveManager.setAlarm(this)).start(); doMigrations(); @@ -107,7 +103,6 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac private void doMigrations() { - } @Override @@ -118,6 +113,7 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac .build(); } + @SuppressWarnings("deprecation") private void registerLocalBroadcastReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_NEW_TREATMENT); @@ -152,16 +148,6 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac 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() { return sDatabaseHelper; } @@ -173,8 +159,4 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac keepAliveManager.cancelAlarm(this); super.onTerminate(); } - - @NotNull @Override public List getAllBgreadingsDataFromTime(long mills, boolean ascending) { - return getDbHelper().getAllBgreadingsDataFromTime(mills, ascending); - } } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 0b8fc440ca..0af1782c90 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -25,7 +25,6 @@ import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin 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.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus @@ -35,13 +34,12 @@ import info.nightscout.androidaps.plugins.general.wear.WearPlugin import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin 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.danar.DanaRPlugin +import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin +import info.nightscout.androidaps.danars.DanaRSPlugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin 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.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin @@ -74,7 +72,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var danaRv2Plugin: DanaRv2Plugin @Inject lateinit var danaRSPlugin: DanaRSPlugin - @Inject lateinit var careportalPlugin: CareportalPlugin @Inject lateinit var comboPlugin: ComboPlugin @Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin @Inject lateinit var loopPlugin: LoopPlugin @@ -162,7 +159,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreferencesFromResourceIfEnabled(tomatoPlugin, rootKey) addPreferencesFromResourceIfEnabled(poctechPlugin, rootKey) addPreferencesFromResourceIfEnabled(glimpPlugin, rootKey) - addPreferencesFromResourceIfEnabled(careportalPlugin, rootKey) addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, config.APS) diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index abc6df92c9..50a7d3ed47 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -17,7 +17,6 @@ import com.j256.ormlite.table.TableUtils; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.sql.SQLException; import java.util.ArrayList; @@ -29,11 +28,13 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import javax.inject.Inject; + import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.dana.comm.RecordTypes; import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; @@ -46,13 +47,12 @@ import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.interfaces.ProfileStore; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; -import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID; import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset; import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID; @@ -61,7 +61,6 @@ import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.PercentageSplitter; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.ToastUtils; /** * This Helper contains all resource to provide a central DB management functionality. Only methods handling @@ -72,7 +71,9 @@ import info.nightscout.androidaps.utils.ToastUtils; * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATABASE); + @Inject AAPSLogger aapsLogger; + @Inject RxBusWrapper rxBus; + @Inject VirtualPumpPlugin virtualPumpPlugin; public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_BGREADINGS = "BgReadings"; @@ -115,6 +116,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); + StaticInjector.Companion.getInstance().androidInjector().inject(this); onCreate(getWritableDatabase(), getConnectionSource()); //onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1); } @@ -122,8 +124,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { - if (L.isEnabled(LTag.DATABASE)) - log.info("onCreate"); + aapsLogger.info(LTag.DATABASE, "onCreate"); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); @@ -142,7 +143,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")"); } catch (SQLException e) { - log.error("Can't create database", e); + aapsLogger.error("Can't create database", e); throw new RuntimeException(e); } } @@ -154,7 +155,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { this.newVersion = newVersion; if (oldVersion < 7) { - log.info(DatabaseHelper.class.getName(), "onUpgrade"); + aapsLogger.info(LTag.DATABASE, "onUpgrade"); TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.dropTable(connectionSource, BgReading.class, true); TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true); @@ -177,15 +178,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\""); } } catch (SQLException e) { - log.error("Can't drop databases", e); + aapsLogger.error("Can't drop databases", e); throw new RuntimeException(e); } } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { - log.info("Do nothing for downgrading..."); - log.debug("oldVersion: {}, newVersion: {}", oldVersion, newVersion); + aapsLogger.info(LTag.DATABASE, "Do nothing for downgrading..."); + aapsLogger.info(LTag.DATABASE, "oldVersion: {}, newVersion: {}", oldVersion, newVersion); } public int getOldVersion() { @@ -226,9 +227,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, PodHistory.class); updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true); + virtualPumpPlugin.setFakingStatus(true); scheduleBgChange(null); // trigger refresh scheduleTemporaryBasalChange(); scheduleExtendedBolusChange(); @@ -239,7 +240,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { new java.util.TimerTask() { @Override public void run() { - RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("resetDatabases", false)); + rxBus.send(new EventRefreshOverview("resetDatabases", false)); } }, 3000 @@ -251,7 +252,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleTemporaryTargetChange(); } @@ -262,9 +263,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(false); + virtualPumpPlugin.setFakingStatus(false); scheduleTemporaryBasalChange(); } @@ -274,7 +275,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleExtendedBolusChange(); } @@ -284,7 +285,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, CareportalEvent.class, true); TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleCareportalEventChange(); } @@ -294,7 +295,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleProfileSwitchChange(); } @@ -304,7 +305,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, TDD.class, true); TableUtils.createTableIfNotExists(connectionSource, TDD.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -362,11 +363,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return getDao(PodHistory.class); } - public static long roundDateToSec(long date) { + public long roundDateToSec(long date) { long rounded = date - date % 1000; if (rounded != date) - if (L.isEnabled(LTag.DATABASE)) - log.debug("Rounding " + date + " to " + rounded); + aapsLogger.debug(LTag.DATABASE, "Rounding " + date + " to " + rounded); return rounded; } // ------------------- BgReading handling ----------------------- @@ -377,23 +377,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { BgReading old = getDaoBgReadings().queryForId(bgReading.date); if (old == null) { getDaoBgReadings().create(bgReading); - if (L.isEnabled(LTag.DATABASE)) - log.debug("BG: New record from: " + from + " " + bgReading.toString()); + aapsLogger.debug(LTag.DATABASE, "BG: New record from: " + from + " " + bgReading.toString()); scheduleBgChange(bgReading); return true; } if (!old.isEqual(bgReading)) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("BG: Similiar found: " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "BG: Similiar found: " + old.toString()); old.copyFrom(bgReading); getDaoBgReadings().update(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("BG: Updating record from: " + from + " New data: " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "BG: Updating record from: " + from + " New data: " + old.toString()); scheduleBgChange(bgReading); return false; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -403,16 +400,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoBgReadings().update(bgReading); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - private static void scheduleBgChange(@Nullable final BgReading bgReading) { + private void scheduleBgChange(@Nullable final BgReading bgReading) { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventNewBg"); - RxBus.Companion.getINSTANCE().send(new EventNewBG(bgReading)); + aapsLogger.debug(LTag.DATABASE, "Firing EventNewBg"); + rxBus.send(new EventNewBG(bgReading)); scheduledBgPost = null; } } @@ -438,7 +434,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -455,7 +451,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -472,7 +468,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -483,8 +479,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Dao dao = getDaoTDD(); dao.createOrUpdate(tdd); } catch (SQLException e) { - ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception"); - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -497,7 +492,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); tddList = getDaoTDD().query(preparedQuery); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); tddList = new ArrayList<>(); } return tddList; @@ -516,7 +511,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); tddList = getDaoTDD().query(preparedQuery); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); tddList = new ArrayList<>(); } return tddList; @@ -532,7 +527,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoDbRequest().delete(dbr); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0; } @@ -541,7 +536,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoDbRequest().deleteById(nsClientId); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0; } @@ -558,7 +553,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { delete(r); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -566,7 +561,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { TableUtils.clearTable(connectionSource, DbRequest.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -574,7 +569,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoDbRequest().closeableIterator(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); return null; } } @@ -605,7 +600,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempTargets = daoTempTargets.query(preparedQuery); return tempTargets; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -622,7 +617,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempTargets = daoTempTargets.query(preparedQuery); return tempTargets; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -639,8 +634,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(old); // need to delete/create because date may change too old.copyFrom(tempTarget); getDaoTempTargets().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; } @@ -659,28 +653,25 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(old); // need to delete/create because date may change too old.copyFrom(tempTarget); getDaoTempTargets().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; } } } getDaoTempTargets().create(tempTarget); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } if (tempTarget.source == Source.USER) { getDaoTempTargets().create(tempTarget); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -690,16 +681,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(tempTarget); scheduleTemporaryTargetChange(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - private static void scheduleTemporaryTargetChange() { + private void scheduleTemporaryTargetChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventTempTargetChange"); - RxBus.Companion.getINSTANCE().send(new EventTempTargetChange()); + aapsLogger.debug(LTag.DATABASE, "Firing EventTempTargetChange"); + rxBus.send(new EventTempTargetChange()); scheduledTemTargetPost = null; } } @@ -741,14 +731,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .source(Source.NIGHTSCOUT); createOrUpdate(tempTarget); } catch (JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteTempTargetById(String _id) { TempTarget stored = findTempTargetById(_id); if (stored != null) { - log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: Removing TempTarget record from database: " + stored.toString()); delete(stored); scheduleTemporaryTargetChange(); } @@ -768,7 +758,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -785,7 +775,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -800,7 +790,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); historyList = getDaoDanaRHistory().query(preparedQuery); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); historyList = new ArrayList<>(); } return historyList; @@ -823,8 +813,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List trList = getDaoTemporaryBasal().query(preparedQuery); if (trList.size() > 0) { // do nothing, pump history record cannot be changed - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); return false; } @@ -841,8 +830,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { old.copyFromPump(tempBasal); old.source = Source.PUMP; - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); getDaoTemporaryBasal().update(old); @@ -853,8 +841,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; @@ -871,8 +858,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too old.copyFrom(tempBasal); getDaoTemporaryBasal().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleTemporaryBasalChange(); @@ -894,8 +880,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too old.copyFrom(tempBasal); getDaoTemporaryBasal().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleTemporaryBasalChange(); @@ -904,22 +889,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; } if (tempBasal.source == Source.USER) { getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -929,7 +912,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(tempBasal); updateEarliestDataChange(tempBasal.date); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleTemporaryBasalChange(); } @@ -945,7 +928,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempbasals = getDaoTemporaryBasal().query(preparedQuery); return tempbasals; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -961,20 +944,19 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempbasals = getDaoTemporaryBasal().query(preparedQuery); return tempbasals; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } - private static void scheduleTemporaryBasalChange() { + private void scheduleTemporaryBasalChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventTempBasalChange"); - RxBus.Companion.getINSTANCE().send(new EventReloadTempBasalData()); - RxBus.Companion.getINSTANCE().send(new EventTempBasalChange()); + aapsLogger.debug(LTag.DATABASE, "Firing EventTempBasalChange"); + rxBus.send(new EventReloadTempBasalData()); + rxBus.send(new EventTempBasalChange()); if (earliestDataChange != null) - RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(earliestDataChange)); + rxBus.send(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; scheduledTemBasalsPost = null; } @@ -1008,7 +990,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { try { if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal - ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance()) + ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance()) .source(Source.NIGHTSCOUT) .date(trJson.getLong("mills")) .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0) @@ -1016,14 +998,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .insulin(trJson.getDouble("originalExtendedAmount")) ._id(trJson.getString("_id")); // if faking found in NS, adapt AAPS to use it too - if (!VirtualPumpPlugin.Companion.getPlugin().getFakingStatus()) { - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true); + if (!virtualPumpPlugin.getFakingStatus()) { + virtualPumpPlugin.setFakingStatus(true); updateEarliestDataChange(0); scheduleTemporaryBasalChange(); } createOrUpdate(extendedBolus); } else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end - ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance()); + ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance()); extendedBolus.source = Source.NIGHTSCOUT; extendedBolus.date = trJson.getLong("mills"); extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; @@ -1031,14 +1013,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { extendedBolus.insulin = 0; extendedBolus._id = trJson.getString("_id"); // if faking found in NS, adapt AAPS to use it too - if (!VirtualPumpPlugin.Companion.getPlugin().getFakingStatus()) { - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true); + if (!virtualPumpPlugin.getFakingStatus()) { + virtualPumpPlugin.setFakingStatus(true); updateEarliestDataChange(0); scheduleTemporaryBasalChange(); } createOrUpdate(extendedBolus); } else { - TemporaryBasal tempBasal = new TemporaryBasal( MainApp.instance()) + TemporaryBasal tempBasal = new TemporaryBasal(StaticInjector.Companion.getInstance()) .date(trJson.getLong("mills")) .source(Source.NIGHTSCOUT) .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0); @@ -1057,15 +1039,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { createOrUpdate(tempBasal); } } catch (JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteTempBasalById(String _id) { TemporaryBasal stored = findTempBasalById(_id); if (stored != null) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); scheduleTemporaryBasalChange(); @@ -1087,7 +1068,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return list.get(0); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1109,7 +1090,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1119,8 +1100,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public boolean createOrUpdate(ExtendedBolus extendedBolus) { try { - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); ExtendedBolus old; extendedBolus.date = roundDateToSec(extendedBolus.date); @@ -1139,13 +1119,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); List trList = getDaoExtendedBolus().query(preparedQuery); if (trList.size() > 1) { - log.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId); + aapsLogger.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId); return false; } getDaoExtendedBolus().createOrUpdate(extendedBolus); } - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; @@ -1158,8 +1137,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(old); // need to delete/create because date may change too old.copyFrom(extendedBolus); getDaoExtendedBolus().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleExtendedBolusChange(); @@ -1181,8 +1159,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(old); // need to delete/create because date may change too old.copyFrom(extendedBolus); getDaoExtendedBolus().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleExtendedBolusChange(); @@ -1191,22 +1168,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoExtendedBolus().create(extendedBolus); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; } if (extendedBolus.source == Source.USER) { getDaoExtendedBolus().create(extendedBolus); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -1217,7 +1192,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .where().eq("pumpId", pumpId) .queryForFirst(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1227,7 +1202,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(extendedBolus); updateEarliestDataChange(extendedBolus.date); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleExtendedBolusChange(); } @@ -1243,7 +1218,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { extendedBoluses = getDaoExtendedBolus().query(preparedQuery); return extendedBoluses; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -1259,7 +1234,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { extendedBoluses = getDaoExtendedBolus().query(preparedQuery); return extendedBoluses; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -1267,8 +1242,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void deleteExtendedBolusById(String _id) { ExtendedBolus stored = findExtendedBolusById(_id); if (stored != null) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); scheduleExtendedBolusChange(); @@ -1290,7 +1264,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1313,19 +1287,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { */ public void createExtendedBolusFromJsonIfNotExists(JSONObject json) { - ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(MainApp.instance(), json); + ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(StaticInjector.Companion.getInstance(), json); if (extendedBolus != null) createOrUpdate(extendedBolus); } - private static void scheduleExtendedBolusChange() { + private void scheduleExtendedBolusChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventExtendedBolusChange"); - RxBus.Companion.getINSTANCE().send(new EventReloadTreatmentData(new EventExtendedBolusChange())); + aapsLogger.debug(LTag.DATABASE, "Firing EventExtendedBolusChange"); + rxBus.send(new EventReloadTreatmentData(new EventExtendedBolusChange())); if (earliestDataChange != null) - RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(earliestDataChange)); + rxBus.send(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; scheduledExtendedBolusPost = null; } @@ -1348,7 +1321,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoCareportalEvents().createOrUpdate(careportalEvent); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleCareportalEventChange(); } @@ -1357,7 +1330,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoCareportalEvents().delete(careportalEvent); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleCareportalEventChange(); } @@ -1366,7 +1339,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoCareportalEvents().queryForId(timestamp); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1387,7 +1360,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { else return null; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1404,7 +1377,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1421,7 +1394,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1450,7 +1423,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1467,7 +1440,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1483,15 +1456,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (list.size() == 1) { CareportalEvent record = list.get(0); - if (L.isEnabled(LTag.DATABASE)) - log.debug("Removing CareportalEvent record from database: " + record.toString()); + aapsLogger.debug(LTag.DATABASE, "Removing CareportalEvent record from database: " + record.toString()); delete(record); } else { - if (L.isEnabled(LTag.DATABASE)) - log.debug("CareportalEvent not found database: " + _id); + aapsLogger.debug(LTag.DATABASE, "CareportalEvent not found database: " + _id); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1505,17 +1476,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List list = getDaoCareportalEvents().query(preparedQuery); CareportalEvent careportalEvent; if (list.size() == 0) { - careportalEvent = new CareportalEvent(MainApp.instance()); + careportalEvent = new CareportalEvent(StaticInjector.Companion.getInstance()); careportalEvent.source = Source.NIGHTSCOUT; - if (L.isEnabled(LTag.DATABASE)) - log.debug("Adding CareportalEvent record to database: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "Adding CareportalEvent record to database: " + trJson.toString()); // Record does not exists. add } else if (list.size() == 1) { careportalEvent = list.get(0); - if (L.isEnabled(LTag.DATABASE)) - log.debug("Updating CareportalEvent record in database: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "Updating CareportalEvent record in database: " + trJson.toString()); } else { - log.error("Something went wrong"); + aapsLogger.error("Something went wrong"); return; } careportalEvent.date = trJson.getLong("mills"); @@ -1524,16 +1493,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvent._id = trJson.getString("_id"); createOrUpdate(careportalEvent); } catch (SQLException | JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } - private static void scheduleCareportalEventChange() { + private void scheduleCareportalEventChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing scheduleCareportalEventChange"); - RxBus.Companion.getINSTANCE().send(new EventCareportalEventChange()); + aapsLogger.debug(LTag.DATABASE, "Firing scheduleCareportalEventChange"); + rxBus.send(new EventCareportalEventChange()); scheduledCareportalEventPost = null; } } @@ -1568,7 +1536,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } return profileSwitches; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1590,7 +1558,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { else return null; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1608,7 +1576,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitches = daoProfileSwitch.query(preparedQuery); return profileSwitches; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1626,7 +1594,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitches = daoProfileSwitch.query(preparedQuery); return profileSwitches; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1644,8 +1612,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; } @@ -1664,8 +1631,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoProfileSwitch().delete(old); // need to delete/create because date may change too old.copyFrom(profileSwitch); getDaoProfileSwitch().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; } @@ -1674,20 +1640,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // look for already added percentage from NS profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName); getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } if (profileSwitch.source == Source.USER) { getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -1697,17 +1661,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoProfileSwitch().delete(profileSwitch); scheduleProfileSwitchChange(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - private static void scheduleProfileSwitchChange() { + private void scheduleProfileSwitchChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventProfileNeedsUpdate"); - RxBus.Companion.getINSTANCE().send(new EventReloadProfileSwitchData()); - RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate()); + aapsLogger.debug(LTag.DATABASE, "Firing EventProfileNeedsUpdate"); + rxBus.send(new EventReloadProfileSwitchData()); + rxBus.send(new EventProfileNeedsUpdate()); scheduledProfileSwitchEventPost = null; } } @@ -1733,9 +1696,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } */ - public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, JSONObject trJson) { + public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, NSUpload nsUpload, JSONObject trJson) { try { - ProfileSwitch profileSwitch = new ProfileSwitch(MainApp.instance()); + ProfileSwitch profileSwitch = new ProfileSwitch(StaticInjector.Companion.getInstance()); profileSwitch.date = trJson.getLong("mills"); if (trJson.has("duration")) profileSwitch.durationInMinutes = trJson.getInt("duration"); @@ -1756,18 +1719,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Profile profile = store.getSpecificProfile(profileSwitch.profileName); if (profile != null) { profileSwitch.profileJson = profile.getData().toString(); - if (L.isEnabled(LTag.DATABASE)) - log.debug("Profile switch prefilled with JSON from local store"); + aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store"); // Update data in NS - NSUpload.updateProfileSwitch(profileSwitch); + nsUpload.updateProfileSwitch(profileSwitch); } else { - if (L.isEnabled(LTag.DATABASE)) - log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } else { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } @@ -1775,15 +1735,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profilePlugin = trJson.getString("profilePlugin"); createOrUpdate(profileSwitch); } catch (JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteProfileSwitchById(String _id) { ProfileSwitch stored = findProfileSwitchById(_id); if (stored != null) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); delete(stored); scheduleTemporaryTargetChange(); } @@ -1803,7 +1762,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1814,7 +1773,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoInsightHistoryOffset().createOrUpdate(offset); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1822,7 +1781,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoInsightHistoryOffset().queryForId(pumpSerial); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1831,7 +1790,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoInsightBolusID().createOrUpdate(bolusID); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1843,7 +1802,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .and().between("timestamp", timestamp - 259200000, timestamp + 259200000) .queryForFirst(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1852,7 +1811,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoInsightPumpID().createOrUpdate(pumpID); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1865,7 +1824,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .and().lt("timestamp", before) .queryForFirst(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1878,7 +1837,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoPodHistory().createOrUpdate(podHistory); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1896,7 +1855,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { podHistories = daoPodHistory.query(preparedQuery); return podHistories; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java new file mode 100644 index 0000000000..d174f170f5 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -0,0 +1,72 @@ +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 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 getDanaRHistoryRecordsByType(byte type) { + return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type); + } + + @NotNull @Override public List 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 getDbRequestInterator() { + return MainApp.getDbHelper().getDbRequestInterator(); + } + + @Override public long roundDateToSec(long date) { + return MainApp.getDbHelper().roundDateToSec(date); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt index 7315329ab2..0e55e30b85 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt @@ -17,12 +17,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread abstract class APSModule { @ContributesAndroidInjector abstract fun loggerCallbackInjector(): LoggerCallback - @ContributesAndroidInjector abstract fun apsResultInjector(): APSResult @ContributesAndroidInjector abstract fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector abstract fun determineBasalResultAMAInjector(): DetermineBasalResultAMA @ContributesAndroidInjector abstract fun determineBasalAdapterAMAJSInjector(): DetermineBasalAdapterAMAJS @ContributesAndroidInjector abstract fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS - @ContributesAndroidInjector abstract fun autosensDataInjector(): AutosensData @ContributesAndroidInjector abstract fun iobCobThreadInjector(): IobCobThread @ContributesAndroidInjector abstract fun iobCobOref1ThreadInjector(): IobCobOref1Thread } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt index 2f6d515b0e..593d1e09e1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -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.pump.common.dialog.RileyLinkBLEScanActivity 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.InsightPairingActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity @@ -25,11 +21,6 @@ import info.nightscout.androidaps.setupwizard.SetupWizardActivity @Suppress("unused") 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 contributesInsightAlertActivity(): InsightAlertActivity @ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity @@ -37,7 +28,6 @@ abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity @ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity - @ContributesAndroidInjector abstract fun contributesPairingHelperActivity(): PairingHelperActivity @ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity @ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity @ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity @@ -48,6 +38,5 @@ abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesSmsCommunicatorOtpActivity(): SmsCommunicatorOtpActivity @ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity @ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity - @ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity @ContributesAndroidInjector abstract fun contributesPrefImportListActivity(): PrefImportListActivity } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 1dec3bf9bb..24dadb14d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,14 +5,18 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.core.dependencyInjection.CoreModule +import info.nightscout.androidaps.core.di.CoreModule +import info.nightscout.androidaps.dana.di.DanaModule +import info.nightscout.androidaps.danar.di.DanaRServicesModule +import info.nightscout.androidaps.danars.di.DanaRSModule import javax.inject.Singleton @Singleton @Component( modules = [ AndroidInjectionModule::class, - CoreModule::class, + PluginsModule::class, + SkinsModule::class, ActivitiesModule::class, FragmentsModule::class, AppModule::class, @@ -28,7 +32,11 @@ import javax.inject.Singleton OverviewModule::class, DataClassesModule::class, SMSModule::class, - UIModule::class + UIModule::class, + CoreModule::class, + DanaModule::class, + DanaRServicesModule::class, + DanaRSModule::class ] ) interface AppComponent : AndroidInjector { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index e405ab91fd..4fb00e9bb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -8,45 +8,34 @@ import dagger.Provides import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.db.DatabaseHelperProvider import info.nightscout.androidaps.interfaces.* -import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.PluginStore -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation +import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.CommandQueue -import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.sharedPreferences.SP +import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.Storage import javax.inject.Singleton @Module(includes = [ - AppModule.AppBindings::class, - PluginsModule::class, - SkinsModule::class + AppModule.AppBindings::class ]) open class AppModule { - @Provides - @Singleton - fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy): ProfileFunction { - return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin, fabricPrivacy) - } - @Provides fun providesPlugins(configInterface: ConfigInterface, @PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>, @PluginsModule.PumpDriver pumpDrivers: Lazy>, @PluginsModule.NotNSClient notNsClient: Lazy>, - @PluginsModule.NSClient nsClient: Lazy>, @PluginsModule.APS aps: Lazy>) : List<@JvmSuppressWildcards PluginBase> { val plugins = allConfigs.toMutableMap() if (configInterface.PUMPDRIVERS) plugins += pumpDrivers.get() if (configInterface.APS) plugins += aps.get() if (!configInterface.NSCLIENT) plugins += notNsClient.get() - if (configInterface.NSCLIENT) plugins += nsClient.get() return plugins.toList().sortedBy { it.first }.map { it.second } } @@ -61,11 +50,13 @@ open class AppModule { @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector - @Binds fun bindDatabaseHelperInterface(mainApp: MainApp): DatabaseHelperInterface @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider - @Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider - @Binds fun configInterfaceProvider(config: Config): ConfigInterface - @Binds fun treatmentInterfaceProvider(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface - + @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 } } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt index b0850bacc2..e9339e187b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.commands.* @@ -10,8 +9,6 @@ import info.nightscout.androidaps.queue.commands.* @Suppress("unused") abstract class CommandQueueModule { - @ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResult - @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt index 536454413c..c63e70ace8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt @@ -3,14 +3,10 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.db.* import info.nightscout.androidaps.interfaces.ProfileStore -import info.nightscout.androidaps.db.BgReading -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.db.Treatment +import info.nightscout.androidaps.plugins.general.food.FoodService import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @@ -19,19 +15,11 @@ import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @Suppress("unused") abstract class DataClassesModule { - @ContributesAndroidInjector abstract fun profileInjector(): Profile @ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus - @ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore - - // TODO move to Core - @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 foodServiceInjector(): FoodService @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index f9753fda61..3fb97d8a32 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment 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.general.actions.ActionsFragment import info.nightscout.androidaps.plugins.general.automation.AutomationFragment import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseActionDialog @@ -18,8 +18,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.EditEventDialog 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.maintenance.MaintenanceFragment import info.nightscout.androidaps.plugins.general.nsclient.NSClientFragment @@ -34,7 +32,7 @@ import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment 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.RileyLinkStatusHistoryFragment -import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment +import info.nightscout.androidaps.danars.dialogs.PairingProgressDialog import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic @@ -54,13 +52,11 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment @ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment @ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment - @ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment @ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment @ContributesAndroidInjector abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment - @ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment @ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment @ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment @ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment @@ -89,7 +85,6 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment - @ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog @@ -100,17 +95,13 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog - @ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog @ContributesAndroidInjector abstract fun contributesChooseActionDialog(): ChooseActionDialog @ContributesAndroidInjector abstract fun contributesChooseTriggerDialog(): ChooseTriggerDialog @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog - @ContributesAndroidInjector abstract fun contributesNewNSTreatmentDialog(): NewNSTreatmentDialog - @ContributesAndroidInjector abstract fun contributesNtpProgressDialog(): NtpProgressDialog @ContributesAndroidInjector abstract fun contributesObjectivesExamDialog(): ObjectivesExamDialog @ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog - @ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog @ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog @ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog @ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt index de00d631e4..1e02c6100d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -4,6 +4,10 @@ import dagger.Binds import dagger.Module import dagger.multibindings.IntKey import dagger.multibindings.IntoMap +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.interfaces.PluginBase import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin @@ -17,7 +21,6 @@ import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintP import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin 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.food.FoodPlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin @@ -34,14 +37,9 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin 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.mdi.MDIPlugin 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.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin @@ -161,12 +159,6 @@ abstract class PluginsModule { @IntKey(170) abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase - @Binds - @NSClient - @IntoMap - @IntKey(180) - abstract fun bindCareportalPlugin(plugin: CareportalPlugin): PluginBase - @Binds @APS @IntoMap @@ -227,7 +219,6 @@ abstract class PluginsModule { @IntKey(280) abstract fun bindSmsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase - @Binds @APS @IntoMap @@ -357,9 +348,6 @@ abstract class PluginsModule { @Qualifier annotation class NotNSClient - @Qualifier - annotation class NSClient - @Qualifier annotation class APS diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt index 5faee82d58..4c6e67608c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt @@ -16,7 +16,6 @@ abstract class ReceiversModule { @ContributesAndroidInjector abstract fun contributesChargingStateReceiver(): ChargingStateReceiver @ContributesAndroidInjector abstract fun contributesDataReceiver(): DataReceiver @ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver - @ContributesAndroidInjector abstract fun contributesNetworkChangeReceiver(): NetworkChangeReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt index 25d102e3ef..f961c3a863 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt @@ -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.wear.wearintegration.WatchUpdaterService 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.connection_service.InsightConnectionService import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService @@ -24,17 +19,12 @@ import info.nightscout.androidaps.services.LocationService @Suppress("unused") abstract class ServicesModule { - @ContributesAndroidInjector abstract fun contributesAbstractDanaRExecutionService(): AbstractDanaRExecutionService @ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService @ContributesAndroidInjector abstract fun contributesDataService(): DataService @ContributesAndroidInjector abstract fun contributesDismissNotificationService(): DismissNotificationService @ContributesAndroidInjector abstract fun contributesDummyService(): DummyService @ContributesAndroidInjector abstract fun contributesLocationService(): LocationService @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 contributesInsightAlertService(): InsightAlertService @ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt deleted file mode 100644 index 6ee0c902dc..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt +++ /dev/null @@ -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. \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index 28abd8eb60..31ced947d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -40,6 +40,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var carbsGenerator: CarbsGenerator companion object { @@ -233,7 +234,7 @@ class CarbsDialog : DialogFragmentWithDate() { } else { aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration") 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) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index 1eda2e060e..ed2b96d1e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -20,8 +20,8 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.Translator +import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_care.* import kotlinx.android.synthetic.main.notes.* @@ -36,6 +36,7 @@ class CareDialog : DialogFragmentWithDate() { @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var translator: Translator enum class EventType { @@ -43,10 +44,13 @@ class CareDialog : DialogFragmentWithDate() { SENSOR_INSERT, BATTERY_CHANGE, NOTE, - EXERCISE + EXERCISE, + QUESTION, + ANNOUNCEMENT } private var options: EventType = EventType.BGCHECK + @StringRes private var event: Int = R.string.none @@ -84,6 +88,8 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> R.drawable.icon_cp_pump_battery EventType.NOTE -> R.drawable.icon_cp_note EventType.EXERCISE -> R.drawable.icon_cp_exercise + EventType.QUESTION -> R.drawable.icon_cp_question + EventType.ANNOUNCEMENT -> R.drawable.icon_cp_announcement }) actions_care_title.text = resourceHelper.gs(when (options) { EventType.BGCHECK -> R.string.careportal_bgcheck @@ -91,9 +97,13 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange EventType.NOTE -> R.string.careportal_note EventType.EXERCISE -> R.string.careportal_exercise + EventType.QUESTION -> R.string.careportal_question + EventType.ANNOUNCEMENT -> R.string.careportal_announcement }) when (options) { + EventType.QUESTION, + EventType.ANNOUNCEMENT, EventType.BGCHECK -> { action_care_duration_layout.visibility = View.GONE } @@ -133,7 +143,7 @@ class CareDialog : DialogFragmentWithDate() { } actions_care_duration.setParams(savedInstanceState?.getDouble("actions_care_duration") ?: 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 } @@ -143,7 +153,7 @@ class CareDialog : DialogFragmentWithDate() { val json = JSONObject() val actions: LinkedList = LinkedList() - if (options == EventType.BGCHECK) { + if (options == EventType.BGCHECK || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT) { val type = when { actions_care_meter.isChecked -> "Finger" @@ -177,6 +187,8 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE EventType.NOTE -> CareportalEvent.NOTE EventType.EXERCISE -> CareportalEvent.EXERCISE + EventType.QUESTION -> CareportalEvent.QUESTION + EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT }) json.put("units", profileFunction.getUnits()) if (enteredBy.isNotEmpty()) @@ -193,11 +205,13 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE EventType.NOTE -> CareportalEvent.NOTE EventType.EXERCISE -> CareportalEvent.EXERCISE + EventType.QUESTION -> CareportalEvent.QUESTION + EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT } careportalEvent.json = json.toString() aapsLogger.debug("USER ENTRY: CAREPORTAL ${careportalEvent.eventType} json: ${careportalEvent.json}") MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadCareportalEntryToNS(json) + nsUpload.uploadCareportalEntryToNS(json) }, null) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 1300ee1612..580b27228c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -23,9 +23,10 @@ import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.alertDialogs.OKDialog 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.sharedPreferences.SP import kotlinx.android.synthetic.main.dialog_fill.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* @@ -39,9 +40,9 @@ class FillDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var ctx: Context + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var activePlugin: ActivePluginProvider - @Inject lateinit var injector: HasAndroidInjector override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) @@ -123,12 +124,12 @@ class FillDialog : DialogFragmentWithDate() { } if (siteChange) { aapsLogger.debug("USER ENTRY: SITE CHANGE") - generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes) + nsUpload.generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes) } if (insulinChange) { // add a second for case of both checked aapsLogger.debug("USER ENTRY: INSULIN CHANGE") - generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes) + nsUpload.generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes) } }, 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 - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt index 3e6a2c374e..14f0897cc5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -89,19 +89,19 @@ class TempBasalDialog : DialogFragmentWithDate() { if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text) 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)) if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) } else { val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text) 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)) if (abs(absolute - basalAbsoluteInput) > 0.01) actions.add("" + resourceHelper.gs(R.string.constraintapllied) + "") } activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { val callback: Callback = object : Callback() { override fun run() { if (!result.success) { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index d2e9c0454f..a16c6ac471 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -16,7 +16,6 @@ import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog @@ -123,7 +122,7 @@ class TempTargetDialog : DialogFragmentWithDate() { val duration = overview_temptarget_duration.value.toInt() if (target != 0.0 && duration != 0) { 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)) } else { actions.add(resourceHelper.gs(R.string.stoptemptarget)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java index 815cf2fa24..2fa1816ad5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java @@ -4,7 +4,7 @@ import org.mozilla.javascript.ScriptableObject; 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.LTag; @@ -26,7 +26,7 @@ public class LoggerCallback extends ScriptableObject { //empty constructor needed for Rhino errorBuffer = new StringBuffer(); logBuffer = new StringBuffer(); - MainApp.instance().androidInjector().inject(this); + StaticInjector.Companion.getInstance().androidInjector().inject(this); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 4b70bb5ff9..1912d26b7a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -21,6 +21,7 @@ import javax.inject.Singleton; import dagger.Lazy; import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -40,9 +41,11 @@ import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; +import info.nightscout.androidaps.interfaces.LoopInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; @@ -52,7 +55,6 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.interfaces.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; @@ -67,15 +69,15 @@ import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import info.nightscout.androidaps.utils.HardLimits; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @Singleton -public class LoopPlugin extends PluginBase { +public class LoopPlugin extends PluginBase implements LoopInterface { private final HasAndroidInjector injector; private final SP sp; private final RxBusWrapper rxBus; @@ -91,6 +93,7 @@ public class LoopPlugin extends PluginBase { private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final ReceiverStatusStore receiverStatusStore; private final FabricPrivacy fabricPrivacy; + private final NSUpload nsUpload; private final HardLimits hardLimits; private Notification notification; @@ -106,21 +109,15 @@ public class LoopPlugin extends PluginBase { private long carbsSuggestionsSuspendedUntil = 0; - public class LastRun { - public APSResult request = null; - public APSResult constraintsProcessed = null; - public PumpEnactResult tbrSetByPump = null; - public PumpEnactResult smbSetByPump = null; - public String source = null; - public long lastAPSRun = DateUtil.now(); - public long lastTBREnact = 0; - public long lastSMBEnact = 0; - public long lastTBRRequest = 0; - public long lastSMBRequest = 0; - public long lastOpenModeAccept; + @Nullable private LastRun lastRun = null; + + @Nullable @Override public LastRun getLastRun() { + return lastRun; } - @Nullable public LastRun lastRun = null; + @Override public void setLastRun(@Nullable LastRun lastRun) { + this.lastRun = lastRun; + } @Inject public LoopPlugin( @@ -140,6 +137,7 @@ public class LoopPlugin extends PluginBase { IobCobCalculatorPlugin iobCobCalculatorPlugin, ReceiverStatusStore receiverStatusStore, FabricPrivacy fabricPrivacy, + NSUpload nsUpload, HardLimits hardLimits ) { super(new PluginDescription() @@ -166,6 +164,7 @@ public class LoopPlugin extends PluginBase { this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.receiverStatusStore = receiverStatusStore; this.fabricPrivacy = fabricPrivacy; + this.nsUpload = nsUpload; this.hardLimits = hardLimits; loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L); @@ -297,7 +296,7 @@ public class LoopPlugin extends PluginBase { return true; } - public boolean isLGS(){ + public boolean isLGS() { Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); String APSmode = sp.getString(R.string.key_aps_mode, "open"); @@ -408,18 +407,18 @@ public class LoopPlugin extends PluginBase { } if (lastRun == null) lastRun = new LastRun(); - lastRun.request = result; - 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; + 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); + nsUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); if (isSuspended()) { getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended)); @@ -503,27 +502,27 @@ public class LoopPlugin extends PluginBase { final PumpEnactResult waiting = new PumpEnactResult(getInjector()); waiting.queued = true; if (resultAfterConstraints.tempBasalRequested) - lastRun.tbrSetByPump = waiting; + lastRun.setTbrSetByPump(waiting); if (resultAfterConstraints.bolusRequested) - lastRun.smbSetByPump = waiting; + lastRun.setSmbSetByPump(waiting); rxBus.send(new EventLoopUpdateGui()); fabricPrivacy.logCustom("APSRequest"); applyTBRRequest(resultAfterConstraints, profile, new Callback() { @Override public void run() { if (result.enacted || result.success) { - lastRun.tbrSetByPump = result; - lastRun.lastTBRRequest = lastRun.lastAPSRun; - lastRun.lastTBREnact = DateUtil.now(); + lastRun.setTbrSetByPump(result); + lastRun.setLastTBRRequest(lastRun.getLastAPSRun()); + lastRun.setLastTBREnact(DateUtil.now()); rxBus.send(new EventLoopUpdateGui()); applySMBRequest(resultAfterConstraints, new Callback() { @Override public void run() { //Callback is only called if a bolus was acutally requested if (result.enacted || result.success) { - lastRun.smbSetByPump = result; - lastRun.lastSMBRequest = lastRun.lastAPSRun; - lastRun.lastSMBEnact = DateUtil.now(); + lastRun.setTbrSetByPump(result); + lastRun.setLastTBRRequest(lastRun.getLastAPSRun()); + lastRun.setLastTBREnact(DateUtil.now()); } else { new Thread(() -> { SystemClock.sleep(1000); @@ -538,8 +537,8 @@ public class LoopPlugin extends PluginBase { } }); } else { - lastRun.tbrSetByPump = null; - lastRun.smbSetByPump = null; + lastRun.setTbrSetByPump(null); + lastRun.setSmbSetByPump(null); } } else { if (resultAfterConstraints.isChangeRequested() && allowNotification) { @@ -609,15 +608,15 @@ public class LoopPlugin extends PluginBase { public void acceptChangeRequest() { Profile profile = profileFunction.getProfile(); final LoopPlugin lp = this; - applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() { + applyTBRRequest(lastRun.getConstraintsProcessed(), profile, new Callback() { @Override public void run() { if (result.enacted) { - lastRun.tbrSetByPump = result; - lastRun.lastTBRRequest = lastRun.lastAPSRun; - lastRun.lastTBREnact = DateUtil.now(); - lastRun.lastOpenModeAccept = DateUtil.now(); - NSUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore); + lastRun.setTbrSetByPump(result); + lastRun.setLastTBRRequest(lastRun.getLastAPSRun()); + lastRun.setLastTBREnact(DateUtil.now()); + lastRun.setLastOpenModeAccept(DateUtil.now()); + nsUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); sp.incInt(R.string.key_ObjectivesmanualEnacts); } rxBus.send(new EventAcceptOpenLoopChange()); @@ -851,6 +850,7 @@ public class LoopPlugin extends PluginBase { event.eventType = CareportalEvent.OPENAPSOFFLINE; event.json = data.toString(); MainApp.getDbHelper().createOrUpdate(event); - NSUpload.uploadOpenAPSOffline(event); + nsUpload.uploadOpenAPSOffline(event); } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt index 5d274d933b..598ddf085f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt @@ -36,7 +36,7 @@ class ConfigBuilderPlugin @Inject constructor( .shortName(R.string.configbuilder_shortname) .description(R.string.description_config_builder), aapsLogger, resourceHelper, injector -) { +), ConfigBuilderInterface { fun initialize() { (activePlugin as PluginStore).loadDefaults() @@ -52,7 +52,7 @@ class ConfigBuilderPlugin @Inject constructor( storeSettings("setAlwaysEnabledPluginsEnabled") } - fun storeSettings(from: String) { + override fun storeSettings(from: String) { activePlugin.pluginsList aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from") activePlugin.verifySelectionInCategories() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index 1e01d814f6..69a8892bdc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -22,8 +22,8 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog -import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog -import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus +import info.nightscout.androidaps.dialogs.NtpProgressDialog +import info.nightscout.androidaps.events.EventNtpStatus import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask import info.nightscout.androidaps.receivers.ReceiverStatusStore diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index f14f7732dd..47651ef9ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -144,6 +144,12 @@ class ActionsFragment : DaggerFragment() { actions_exercise.setOnClickListener { 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) } @@ -192,13 +198,7 @@ class ActionsFragment : DaggerFragment() { val pump = activePlugin.activePump actions_temptarget?.visibility = (profile != null).toVisibility() - actions_canceltempbasal.visibility = (profile == null).toVisibility() - actions_settempbasal.visibility = (profile == null).toVisibility() - actions_fill.visibility = (profile == null).toVisibility() - actions_extendedbolus.visibility = (profile == null).toVisibility() - actions_extendedbolus_cancel.visibility = (profile == null).toVisibility() - actions_historybrowser.visibility = (profile == null).toVisibility() - actions_tddstats.visibility = (profile == null).toVisibility() + actions_historybrowser.visibility = (profile != null).toVisibility() val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt index 7a730585c1..43342f35e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt @@ -22,6 +22,7 @@ import javax.inject.Inject class ActionNotification(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var nsUpload: NSUpload var text = InputString(injector) @@ -32,7 +33,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) { override fun doAction(callback: Callback) { val notification = NotificationUserMessage(text.value) rxBus.send(EventNewNotification(notification)) - NSUpload.uploadError(text.value) + nsUpload.uploadError(text.value) rxBus.send(EventRefreshOverview("ActionNotification")) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt index 5db3c14add..61f727c9a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt @@ -26,7 +26,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) { override fun doAction(callback: Callback) { 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 { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.kt deleted file mode 100644 index 4007e43b45..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.kt +++ /dev/null @@ -1,134 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal - -import android.os.Bundle -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.R -import info.nightscout.androidaps.events.EventCareportalEventChange -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog -import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler -import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers -import io.reactivex.disposables.CompositeDisposable -import kotlinx.android.synthetic.main.careportal_fragment.* -import kotlinx.android.synthetic.main.careportal_stats_fragment.* -import javax.inject.Inject - -class CareportalFragment : DaggerFragment(), View.OnClickListener { - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var statusLightHandler: StatusLightHandler - @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var activePlugin: ActivePluginProvider - - private val disposable = CompositeDisposable() - - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - return inflater.inflate(R.layout.careportal_fragment, container, false) - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - careportal_bgcheck.setOnClickListener(this) - careportal_announcement.setOnClickListener(this) - careportal_cgmsensorinsert.setOnClickListener(this) - careportal_cgmsensorstart.setOnClickListener(this) - careportal_combobolus.setOnClickListener(this) - careportal_correctionbolus.setOnClickListener(this) - careportal_carbscorrection.setOnClickListener(this) - careportal_exercise.setOnClickListener(this) - careportal_insulincartridgechange.setOnClickListener(this) - careportal_pumpbatterychange.setOnClickListener(this) - careportal_mealbolus.setOnClickListener(this) - careportal_note.setOnClickListener(this) - careportal_profileswitch.setOnClickListener(this) - careportal_pumpsitechange.setOnClickListener(this) - careportal_question.setOnClickListener(this) - careportal_snackbolus.setOnClickListener(this) - careportal_tempbasalend.setOnClickListener(this) - careportal_tempbasalstart.setOnClickListener(this) - careportal_openapsoffline.setOnClickListener(this) - careportal_temporarytarget.setOnClickListener(this) - - val profileStore = activePlugin.activeProfileInterface.profile - if (profileStore == null) { - profileview_noprofile.visibility = View.VISIBLE - careportal_buttons.visibility = View.GONE - } else { - profileview_noprofile.visibility = View.GONE - careportal_buttons.visibility = View.VISIBLE - } - } - - @Synchronized override fun onResume() { - super.onResume() - disposable.add(rxBus - .toObservable(EventCareportalEventChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }) { fabricPrivacy.logException(it) } - ) - updateGUI() - } - - @Synchronized override fun onPause() { - super.onPause() - disposable.clear() - } - - override fun onClick(view: View) { - val BGCHECK = OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck).date().bg() - val SNACKBOLUS = OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus).date().bg().insulin().carbs().prebolus() - val MEALBOLUS = OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus).date().bg().insulin().carbs().prebolus() - val CORRECTIONBOLUS = OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus).date().bg().insulin().carbs().prebolus() - val CARBCORRECTION = OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection).date().bg().carbs() - val COMBOBOLUS = OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus).date().bg().insulin().carbs().prebolus().duration().split() - val ANNOUNCEMENT = OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement).date().bg() - val NOTE = OptionsToShow(R.id.careportal_note, R.string.careportal_note).date().bg().duration() - val QUESTION = OptionsToShow(R.id.careportal_question, R.string.careportal_question).date().bg() - val EXERCISE = OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise).date().duration() - val SITECHANGE = OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange).date().bg() - val SENSORSTART = OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart).date().bg() - val SENSORCHANGE = OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert).date().bg() - val INSULINCHANGE = OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange).date().bg() - val PUMPBATTERYCHANGE = OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange).date().bg() - val TEMPBASALSTART = OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart).date().bg().duration().percent().absolute() - val TEMPBASALEND = OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend).date().bg() - val PROFILESWITCH = OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch).date().duration().profile() - val OPENAPSOFFLINE = OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline).date().duration() - val TEMPTARGET = OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget).date().duration().tempTarget() - - val newDialog = NewNSTreatmentDialog() - when (view.id) { - R.id.careportal_bgcheck -> newDialog.setOptions(BGCHECK, R.string.careportal_bgcheck) - R.id.careportal_announcement -> newDialog.setOptions(ANNOUNCEMENT, R.string.careportal_announcement) - R.id.careportal_cgmsensorinsert -> newDialog.setOptions(SENSORCHANGE, R.string.careportal_cgmsensorinsert) - R.id.careportal_cgmsensorstart -> newDialog.setOptions(SENSORSTART, R.string.careportal_cgmsensorstart) - R.id.careportal_combobolus -> newDialog.setOptions(COMBOBOLUS, R.string.careportal_combobolus) - R.id.careportal_correctionbolus -> newDialog.setOptions(CORRECTIONBOLUS, R.string.careportal_correctionbolus) - R.id.careportal_carbscorrection -> newDialog.setOptions(CARBCORRECTION, R.string.careportal_carbscorrection) - R.id.careportal_exercise -> newDialog.setOptions(EXERCISE, R.string.careportal_exercise) - R.id.careportal_insulincartridgechange -> newDialog.setOptions(INSULINCHANGE, R.string.careportal_insulincartridgechange) - R.id.careportal_pumpbatterychange -> newDialog.setOptions(PUMPBATTERYCHANGE, R.string.careportal_pumpbatterychange) - R.id.careportal_mealbolus -> newDialog.setOptions(MEALBOLUS, R.string.careportal_mealbolus) - R.id.careportal_note -> newDialog.setOptions(NOTE, R.string.careportal_note) - R.id.careportal_profileswitch -> newDialog.setOptions(PROFILESWITCH, R.string.careportal_profileswitch) - R.id.careportal_pumpsitechange -> newDialog.setOptions(SITECHANGE, R.string.careportal_pumpsitechange) - R.id.careportal_question -> newDialog.setOptions(QUESTION, R.string.careportal_question) - R.id.careportal_snackbolus -> newDialog.setOptions(SNACKBOLUS, R.string.careportal_snackbolus) - R.id.careportal_tempbasalstart -> newDialog.setOptions(TEMPBASALSTART, R.string.careportal_tempbasalstart) - R.id.careportal_tempbasalend -> newDialog.setOptions(TEMPBASALEND, R.string.careportal_tempbasalend) - R.id.careportal_openapsoffline -> newDialog.setOptions(OPENAPSOFFLINE, R.string.careportal_openapsoffline) - R.id.careportal_temporarytarget -> newDialog.setOptions(TEMPTARGET, R.string.careportal_temporarytarget) - } - NewNSTreatmentDialog().show(childFragmentManager, "CareportalFragment") - } - - private fun updateGUI() { - statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, null, careportal_sensorage, careportal_pbage, null) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt deleted file mode 100644 index 897f28b0ae..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.Config -import info.nightscout.androidaps.R -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.utils.resources.ResourceHelper -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class CareportalPlugin @Inject constructor( - injector: HasAndroidInjector, - aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper, - config: Config -) : PluginBase(PluginDescription() - .mainType(PluginType.GENERAL) - .fragmentClass(CareportalFragment::class.java.name) - .pluginName(R.string.careportal) - .shortName(R.string.careportal_shortname) - .visibleByDefault(config.NSCLIENT) - .enableByDefault(config.NSCLIENT) - .description(R.string.description_careportal), - aapsLogger, resourceHelper, injector -) \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java deleted file mode 100644 index 8fe577ced3..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ /dev/null @@ -1,739 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal.Dialogs; - - -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.text.format.DateFormat; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.RadioButton; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.StringRes; -import androidx.fragment.app.DialogFragment; - -import com.google.common.collect.Lists; -import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; -import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import dagger.android.support.DaggerDialogFragment; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.interfaces.ProfileFunction; -import info.nightscout.androidaps.interfaces.ProfileStore; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DefaultValueHelper; -import info.nightscout.androidaps.utils.HardLimits; -import info.nightscout.androidaps.utils.JsonHelper; -import info.nightscout.androidaps.utils.NumberPicker; -import info.nightscout.androidaps.utils.SafeParse; -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.sharedPreferences.SP; - -public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { - @Inject HasAndroidInjector injector; - @Inject AAPSLogger aapsLogger; - @Inject DefaultValueHelper defaultValueHelper; - @Inject ProfileFunction profileFunction; - @Inject ResourceHelper resourceHelper; - @Inject ConstraintChecker constraintChecker; - @Inject SP sp; - @Inject ActivePluginProvider activePlugin; - @Inject TreatmentsPlugin treatmentsPlugin; - @Inject HardLimits hardLimits; - @Inject Translator translator; - @Inject DateUtil dateUtil; - - private static OptionsToShow options; - private static @StringRes int event; - - private Profile profile; - public ProfileStore profileStore; - - TextView eventTypeText; - LinearLayout layoutPercent; - LinearLayout layoutAbsolute; - LinearLayout layoutReuse; - - - TextView dateButton; - TextView timeButton; - - TextView bgUnitsView; - RadioButton meterRadioButton; - RadioButton sensorRadioButton; - RadioButton otherRadioButton; - EditText notesEdit; - Spinner profileSpinner; - Spinner reasonSpinner; - Button reuseButton; - - NumberPicker editBg; - NumberPicker editCarbs; - NumberPicker editInsulin; - NumberPicker editSplit; - NumberPicker editDuration; - NumberPicker editPercent; - NumberPicker editAbsolute; - NumberPicker editCarbTime; - NumberPicker editTemptarget; - NumberPicker editPercentage; - NumberPicker editTimeshift; - - Date eventTime; - - private static Integer seconds = null; - - public NewNSTreatmentDialog setOptions(OptionsToShow options, int event) { - this.options = options; - this.event = event; - return this; - } - - public NewNSTreatmentDialog() { - super(); - - if (seconds == null) { - seconds = Double.valueOf(Math.random() * 59).intValue(); - } - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - if (options == null) return null; - getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); - getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); - setCancelable(true); - getDialog().setCanceledOnTouchOutside(false); - setStyle(DialogFragment.STYLE_NORMAL, getTheme()); - View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false); - - layoutPercent = view.findViewById(R.id.careportal_newnstreatment_percent_layout); - layoutAbsolute = view.findViewById(R.id.careportal_newnstreatment_absolute_layout); - - layoutReuse = view.findViewById(R.id.careportal_newnstreatment_reuse_layout); - - eventTypeText = view.findViewById(R.id.careportal_newnstreatment_eventtype); - eventTypeText.setText(event); - bgUnitsView = view.findViewById(R.id.careportal_newnstreatment_bgunits); - meterRadioButton = view.findViewById(R.id.careportal_newnstreatment_meter); - sensorRadioButton = view.findViewById(R.id.careportal_newnstreatment_sensor); - otherRadioButton = view.findViewById(R.id.careportal_newnstreatment_other); - profileSpinner = view.findViewById(R.id.careportal_newnstreatment_profile); - - reuseButton = view.findViewById(R.id.careportal_newnstreatment_reusebutton); - - notesEdit = view.findViewById(R.id.careportal_newnstreatment_notes); - - reasonSpinner = view.findViewById(R.id.careportal_newnstreatment_temptarget_reason); - - eventTime = new Date(); - dateButton = view.findViewById(R.id.careportal_newnstreatment_eventdate); - timeButton = view.findViewById(R.id.careportal_newnstreatment_eventtime); - dateButton.setText(DateUtil.dateString(eventTime)); - timeButton.setText(dateUtil.timeString(eventTime)); - dateButton.setOnClickListener(this); - timeButton.setOnClickListener(this); - - view.findViewById(R.id.ok).setOnClickListener(this); - view.findViewById(R.id.cancel).setOnClickListener(this); - - // profile - profile = profileFunction.getProfile(); - profileStore = activePlugin.getActiveProfileInterface().getProfile(); - if (profileStore == null) { - if (options.eventType == R.id.careportal_profileswitch) { - aapsLogger.error("Profile switch called but plugin doesn't contain valid profile"); - } - } else { - ArrayList profileList; - profileList = profileStore.getProfileList(); - ArrayAdapter adapter = new ArrayAdapter<>(getContext(), - R.layout.spinner_centered, profileList); - profileSpinner.setAdapter(adapter); - // set selected to actual profile - for (int p = 0; p < profileList.size(); p++) { - if (profileList.get(p).equals(profileFunction.getProfileName(false))) - profileSpinner.setSelection(p); - } - } - final Double bg = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); - - // temp target - final List reasonList = Lists.newArrayList( - resourceHelper.gs(R.string.manual), - resourceHelper.gs(R.string.eatingsoon), - resourceHelper.gs(R.string.activity), - resourceHelper.gs(R.string.hypo)); - ArrayAdapter adapterReason = new ArrayAdapter<>(getContext(), - R.layout.spinner_centered, reasonList); - reasonSpinner.setAdapter(adapterReason); - reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - double defaultDuration; - double defaultTarget; - if (profile != null && editTemptarget.getValue().equals(bg)) { - defaultTarget = bg; - } else { - //prevent changes on screen rotate - defaultTarget = editTemptarget.getValue(); - } - boolean erase = false; - - if (resourceHelper.gs(R.string.eatingsoon).equals(reasonList.get(position))) { - defaultDuration = defaultValueHelper.determineEatingSoonTTDuration(); - defaultTarget = defaultValueHelper.determineEatingSoonTT(); - } else if (resourceHelper.gs(R.string.activity).equals(reasonList.get(position))) { - defaultDuration = defaultValueHelper.determineActivityTTDuration(); - defaultTarget = defaultValueHelper.determineActivityTT(); - } else if (resourceHelper.gs(R.string.hypo).equals(reasonList.get(position))) { - defaultDuration = defaultValueHelper.determineHypoTTDuration(); - defaultTarget = defaultValueHelper.determineHypoTT(); - } else if (editDuration.getValue() != 0) { - defaultDuration = editDuration.getValue(); - } else { - defaultDuration = 0; - erase = true; - } - - if (defaultTarget != 0 || erase) { - editTemptarget.setValue(defaultTarget); - } - if (defaultDuration != 0) { - editDuration.setValue(defaultDuration); - } else if (erase) { - editDuration.setValue(0d); - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - // bg - bgUnitsView.setText(profileFunction.getUnits()); - - TextWatcher bgTextWatcher = new TextWatcher() { - - public void afterTextChanged(Editable s) { - } - - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true); - } - }; - editBg = view.findViewById(R.id.careportal_newnstreatment_bginput); - editTemptarget = view.findViewById(R.id.careportal_newnstreatment_temptarget); - if (profile == null) { - editBg.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok), bgTextWatcher); - editTemptarget.setParams(Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok)); - } else if (profileFunction.getUnits().equals(Constants.MMOL)) { - editBg.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok), bgTextWatcher); - editTemptarget.setParams(Constants.MIN_TT_MMOL, Constants.MIN_TT_MMOL, Constants.MAX_TT_MMOL, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok)); - } else { - editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok), bgTextWatcher); - editTemptarget.setParams(Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - } - - sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { - double bg1 = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); - if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) { - editBg.setValue(savedInstanceState.getDouble("editBg")); - } else { - editBg.setValue(bg1); - } - }); - - Integer maxCarbs = constraintChecker.getMaxCarbsAllowed().value(); - editCarbs = view.findViewById(R.id.careportal_newnstreatment_carbsinput); - editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - Double maxInsulin = constraintChecker.getMaxBolusAllowed().value(); - editInsulin = view.findViewById(R.id.careportal_newnstreatment_insulininput); - editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false, view.findViewById(R.id.ok)); - - editSplit = view.findViewById(R.id.careportal_newnstreatment_splitinput); - editSplit.setParams(100d, 0d, 100d, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok)); - editDuration = view.findViewById(R.id.careportal_newnstreatment_durationinput); - editDuration.setParams(0d, 0d, Constants.MAX_PROFILE_SWITCH_DURATION, 10d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - TextWatcher percentTextWatcher = new TextWatcher() { - @Override - public void afterTextChanged(Editable s) { - } - - @Override - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, - int before, int count) { - layoutPercent.setVisibility(View.VISIBLE); - layoutAbsolute.setVisibility(View.GONE); - } - }; - - Integer maxPercent = 200; - if (profile != null) - maxPercent = constraintChecker.getMaxBasalPercentAllowed(profile).value(); - editPercent = view.findViewById(R.id.careportal_newnstreatment_percentinput); - editPercent.setParams(0d, -100d, (double) maxPercent, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok), percentTextWatcher); - - TextWatcher absoluteTextWatcher = new TextWatcher() { - @Override - public void afterTextChanged(Editable s) { - } - - @Override - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, - int before, int count) { - layoutPercent.setVisibility(View.GONE); - layoutAbsolute.setVisibility(View.VISIBLE); - } - }; - - Double maxAbsolute = hardLimits.maxBasal(); - if (profile != null) - maxAbsolute = constraintChecker.getMaxBasalAllowed(profile).value(); - editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput); - editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, view.findViewById(R.id.ok), absoluteTextWatcher); - - editCarbTime = view.findViewById(R.id.careportal_newnstreatment_carbtimeinput); - editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - editPercentage = view.findViewById(R.id.careportal_newnstreatment_percentage); - editPercentage.setParams(100d, (double) Constants.CPP_MIN_PERCENTAGE, (double) Constants.CPP_MAX_PERCENTAGE, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - editTimeshift = view.findViewById(R.id.careportal_newnstreatment_timeshift); - editTimeshift.setParams(0d, (double) Constants.CPP_MIN_TIMESHIFT, (double) Constants.CPP_MAX_TIMESHIFT, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - ProfileSwitch ps = treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now()); - if (ps != null && ps.isCPP) { - final int percentage = ps.percentage; - final int timeshift = ps.timeshift; - reuseButton.setText(reuseButton.getText() + " " + percentage + "% " + timeshift + "h"); - reuseButton.setOnClickListener(v -> { - editPercentage.setValue((double) percentage); - editTimeshift.setValue((double) timeshift); - }); - } - if (ps == null) { - options.duration = false; - } - - showOrHide(view.findViewById(R.id.careportal_newnstreatment_eventtime_layout), options.date); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_bg_layout), options.bg); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_bgsource_layout), options.bg); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_insulin_layout), options.insulin); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_carbs_layout), options.carbs); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_split_layout), options.split); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_duration_layout), options.duration); - showOrHide(layoutPercent, options.percent); - showOrHide(layoutAbsolute, options.absolute); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_carbtime_layout), options.prebolus); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_profile_layout), options.profile); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_percentage_layout), options.profile); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_timeshift_layout), options.profile); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_reuse_layout), options.profile && ps != null && ps.isCPP); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_temptarget_layout), options.tempTarget); - - setCancelable(true); - getDialog().setCanceledOnTouchOutside(false); - //recovering state if there is something - // only numberPickers and editTexts - if (savedInstanceState != null) { - editBg.setValue(savedInstanceState.getDouble("editBg")); - editTemptarget.setValue(savedInstanceState.getDouble("editTemptarget")); - notesEdit.setText(savedInstanceState.getString("notesEdit")); - editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); - editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); - editInsulin.setValue(savedInstanceState.getDouble("editInsulin")); - editDuration.setValue(savedInstanceState.getDouble("editDuration")); - editPercent.setValue(savedInstanceState.getDouble("editPercent")); - editAbsolute.setValue(savedInstanceState.getDouble("editAbsolute")); - editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime")); - editPercentage.setValue(savedInstanceState.getDouble("editPercentage")); - editTimeshift.setValue(savedInstanceState.getDouble("editTimeshift")); - // time and date - dateButton.setText(savedInstanceState.getString("dateButton")); - timeButton.setText(savedInstanceState.getString("timeButton")); - } - return view; - } - - @Override - public void onResume() { - super.onResume(); - getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - - } - - @Override - public void onClick(View view) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(eventTime); - switch (view.getId()) { - case R.id.careportal_newnstreatment_eventdate: - DatePickerDialog dpd = DatePickerDialog.newInstance( - this, - calendar.get(Calendar.YEAR), - calendar.get(Calendar.MONTH), - calendar.get(Calendar.DAY_OF_MONTH) - ); - dpd.setThemeDark(true); - dpd.dismissOnPause(true); - dpd.show(getActivity().getSupportFragmentManager(), "Datepickerdialog"); - break; - case R.id.careportal_newnstreatment_eventtime: - TimePickerDialog tpd = TimePickerDialog.newInstance( - this, - calendar.get(Calendar.HOUR_OF_DAY), - calendar.get(Calendar.MINUTE), - DateFormat.is24HourFormat(getContext()) - ); - tpd.setThemeDark(true); - tpd.dismissOnPause(true); - tpd.show(getActivity().getSupportFragmentManager(), "Timepickerdialog"); - break; - case R.id.ok: - confirmNSTreatmentCreation(); - dismiss(); - break; - case R.id.cancel: - dismiss(); - break; - } - } - - private void showOrHide(ViewGroup layout, boolean visible) { - if (visible) layout.setVisibility(View.VISIBLE); - else layout.setVisibility(View.GONE); - } - - private void updateBGforDateTime() { - long millis = eventTime.getTime() - (150 * 1000L); // 2,5 * 60 * 1000 - List data = MainApp.getDbHelper().getBgreadingsDataFromTime(millis, true); - if ((data.size() > 0) && - (data.get(0).date > millis - 7 * 60 * 1000L) && - (data.get(0).date < millis + 7 * 60 * 1000L)) { - editBg.setValue(Profile.fromMgdlToUnits(data.get(0).value, profileFunction.getUnits())); - } - } - - @Override - public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { - eventTime.setYear(year - 1900); - eventTime.setMonth(monthOfYear); - eventTime.setDate(dayOfMonth); - dateButton.setText(DateUtil.dateString(eventTime)); - updateBGforDateTime(); - } - - @Override - public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) { - eventTime.setHours(hourOfDay); - eventTime.setMinutes(minute); - eventTime.setSeconds(this.seconds++); // randomize seconds to prevent creating record of the same time, if user choose time manually - timeButton.setText(dateUtil.timeString(eventTime)); - updateBGforDateTime(); - } - - private JSONObject gatherData() { - String enteredBy = sp.getString("careportal_enteredby", ""); - JSONObject data = new JSONObject(); - try { - boolean allowZeroDuration = false; - data.put("created_at", DateUtil.toISOString(eventTime)); - switch (options.eventType) { - case R.id.careportal_bgcheck: - data.put("eventType", CareportalEvent.BGCHECK); - break; - case R.id.careportal_announcement: - data.put("eventType", CareportalEvent.ANNOUNCEMENT); - data.put("isAnnouncement", true); - break; - case R.id.careportal_cgmsensorinsert: - data.put("eventType", CareportalEvent.SENSORCHANGE); - break; - case R.id.careportal_cgmsensorstart: - data.put("eventType", "Sensor Start"); - break; - case R.id.careportal_combobolus: - data.put("splitNow", SafeParse.stringToDouble(editSplit.getText())); - data.put("splitExt", 100 - SafeParse.stringToDouble(editSplit.getText())); - data.put("eventType", CareportalEvent.COMBOBOLUS); - break; - case R.id.careportal_correctionbolus: - data.put("eventType", "Correction Bolus"); - break; - case R.id.careportal_carbscorrection: - data.put("eventType", "Carb Correction"); - break; - case R.id.careportal_exercise: - data.put("eventType", CareportalEvent.EXERCISE); - break; - case R.id.careportal_insulincartridgechange: - data.put("eventType", CareportalEvent.INSULINCHANGE); - break; - case R.id.careportal_pumpbatterychange: - data.put("eventType", CareportalEvent.PUMPBATTERYCHANGE); - break; - case R.id.careportal_mealbolus: - data.put("eventType", "Meal Bolus"); - break; - case R.id.careportal_note: - data.put("eventType", CareportalEvent.NOTE); - break; - case R.id.careportal_profileswitch: - data.put("eventType", CareportalEvent.PROFILESWITCH); - allowZeroDuration = true; - break; - case R.id.careportal_pumpsitechange: - data.put("eventType", CareportalEvent.SITECHANGE); - break; - case R.id.careportal_question: - data.put("eventType", CareportalEvent.QUESTION); - break; - case R.id.careportal_snackbolus: - data.put("eventType", "Snack Bolus"); - break; - case R.id.careportal_tempbasalstart: - data.put("eventType", CareportalEvent.TEMPBASAL); - break; - case R.id.careportal_tempbasalend: - data.put("eventType", CareportalEvent.TEMPBASAL); - break; - case R.id.careportal_openapsoffline: - data.put("eventType", CareportalEvent.OPENAPSOFFLINE); - break; - case R.id.careportal_temporarytarget: - data.put("eventType", CareportalEvent.TEMPORARYTARGET); - if (!reasonSpinner.getSelectedItem().toString().equals("")) - data.put("reason", reasonSpinner.getSelectedItem().toString()); - if (SafeParse.stringToDouble(editTemptarget.getText()) != 0d) { - data.put("targetBottom", SafeParse.stringToDouble(editTemptarget.getText())); - data.put("targetTop", SafeParse.stringToDouble(editTemptarget.getText())); - } - allowZeroDuration = true; - break; - } - if (options.bg && SafeParse.stringToDouble(editBg.getText()) != 0d) { - data.put("glucose", SafeParse.stringToDouble(editBg.getText())); - if (meterRadioButton.isChecked()) data.put("glucoseType", "Finger"); - if (sensorRadioButton.isChecked()) data.put("glucoseType", "Sensor"); - if (otherRadioButton.isChecked()) data.put("glucoseType", "Manual"); - } - if (SafeParse.stringToDouble(editCarbs.getText()) != 0d) - data.put("carbs", SafeParse.stringToDouble(editCarbs.getText())); - if (SafeParse.stringToDouble(editInsulin.getText()) != 0d) - data.put("insulin", SafeParse.stringToDouble(editInsulin.getText())); - if (allowZeroDuration || SafeParse.stringToDouble(editDuration.getText()) != 0d) - data.put("duration", SafeParse.stringToDouble(editDuration.getText())); - if (layoutPercent.getVisibility() != View.GONE) - data.put("percent", SafeParse.stringToDouble(editPercent.getText())); - if (layoutAbsolute.getVisibility() != View.GONE) - data.put("absolute", SafeParse.stringToDouble(editAbsolute.getText())); - if (options.profile && profileSpinner.getSelectedItem() != null) - data.put("profile", profileSpinner.getSelectedItem().toString()); - if (options.profile) - data.put("percentage", SafeParse.stringToInt(editPercentage.getText())); - if (options.profile) - data.put("timeshift", SafeParse.stringToInt(editTimeshift.getText())); - if (SafeParse.stringToDouble(editCarbTime.getText()) != 0d) - data.put("preBolus", SafeParse.stringToDouble(editCarbTime.getText())); - if (!notesEdit.getText().toString().equals("")) - data.put("notes", notesEdit.getText().toString()); - data.put("units", profileFunction.getUnits()); - if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); - if (options.eventType == R.id.careportal_combobolus) { - Double enteredInsulin = SafeParse.stringToDouble(editInsulin.getText()); - data.put("enteredinsulin", enteredInsulin); - data.put("insulin", enteredInsulin * SafeParse.stringToDouble(editSplit.getText()) / 100); - data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(editSplit.getText())) / 100 / SafeParse.stringToDouble(editDuration.getText()) * 60); - } - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - } - return data; - } - - private String buildConfirmText(JSONObject data) { - String ret = ""; -// if (data.has("eventType")) { -// ret += resourceHelper.gs(R.string.careportal_newnstreatment_eventtype); -// ret += ": "; -// ret += Translator.translate(JsonHelper.safeGetString(data, "eventType", "")); -// ret += "\n"; -// } - if (data.has("glucose")) { - ret += resourceHelper.gs(R.string.treatments_wizard_bg_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "glucose", ""); - ret += " " + profileFunction.getUnits() + "\n"; - } - if (data.has("glucoseType")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype); - ret += ": "; - ret += translator.translate(JsonHelper.safeGetString(data, "glucoseType", "")); - ret += "\n"; - } - if (data.has("carbs")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_carbs_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "carbs", ""); - ret += " g\n"; - } - if (data.has("insulin")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_insulin_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "insulin", ""); - ret += " U\n"; - } - if (data.has("duration")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_duration_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "duration", ""); - ret += " min\n"; - } - if (data.has("percent")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_percent_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "percent", ""); - ret += " %\n"; - } - if (data.has("absolute")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_absolute_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "absolute", ""); - ret += " U/h\n"; - } - if (data.has("preBolus")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_carbtime_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "preBolus", ""); - ret += " min\n"; - } - if (data.has("notes")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_notes_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "notes", ""); - ret += "\n"; - } - if (data.has("profile")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_profile_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "profile", ""); - ret += "\n"; - } - if (data.has("percentage")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_percentage_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "percentage", ""); - ret += " %\n"; - } - if (data.has("timeshift")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "timeshift", ""); - ret += " h\n"; - } - if (data.has("targetBottom") && data.has("targetTop")) { - ret += resourceHelper.gs(R.string.target_range); - ret += " "; - ret += JsonHelper.safeGetObject(data, "targetBottom", ""); - ret += " - "; - ret += JsonHelper.safeGetObject(data, "targetTop", ""); - ret += "\n"; - } - if (data.has("created_at")) { - ret += resourceHelper.gs(R.string.event_time_label); - ret += ": "; - ret += dateUtil.dateAndTimeString(eventTime); - ret += "\n"; - } - if (data.has("enteredBy")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_enteredby_title); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "enteredBy", ""); - ret += "\n"; - } - - return ret; - } - - private void confirmNSTreatmentCreation() { - final JSONObject data = gatherData(); - OKDialog.showConfirmation(getContext(), translator.translate(JsonHelper.safeGetString(data, "eventType", resourceHelper.gs(R.string.overview_treatment_label))), buildConfirmText(data), () -> NSUpload.createNSTreatment(data, profileStore, profileFunction, eventTime.getTime())); - } - - - @Override - public void onSaveInstanceState(Bundle savedInstanceState) { - savedInstanceState.putString("notesEdit", notesEdit.getText().toString()); - savedInstanceState.putString("dateButton", dateButton.getText().toString()); - savedInstanceState.putString("timeButton", timeButton.getText().toString()); - savedInstanceState.putDouble("editBg", editBg.getValue()); - savedInstanceState.putDouble("editCarbs", editCarbs.getValue()); - savedInstanceState.putDouble("editInsulin", editInsulin.getValue()); - savedInstanceState.putDouble("editDuration", editDuration.getValue()); - savedInstanceState.putDouble("editPercent", editPercent.getValue()); - savedInstanceState.putDouble("editAbsolute", editAbsolute.getValue()); - savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue()); - savedInstanceState.putDouble("editTemptarget", editTemptarget.getValue()); - savedInstanceState.putDouble("editPercentage", editPercentage.getValue()); - savedInstanceState.putDouble("editTimeshift", editTimeshift.getValue()); - super.onSaveInstanceState(savedInstanceState); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/OptionsToShow.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/OptionsToShow.java deleted file mode 100644 index e1effcd561..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/OptionsToShow.java +++ /dev/null @@ -1,81 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal; - -/** - * Created by mike on 05.11.2016. - */ - -public class OptionsToShow { - public int eventType; - public int eventName; - public boolean date; - public boolean bg; - public boolean insulin; - public boolean carbs; - public boolean prebolus; - public boolean duration; - public boolean percent; - public boolean absolute; - public boolean profile; - public boolean split; - public boolean tempTarget; - - public OptionsToShow(int eventType, int eventName) { - this.eventType = eventType; - this.eventName = eventName; - } - - public OptionsToShow date() { - date = true; - return this; - } - - public OptionsToShow bg() { - bg = true; - return this; - } - - public OptionsToShow insulin() { - insulin = true; - return this; - } - - public OptionsToShow carbs() { - carbs = true; - return this; - } - - public OptionsToShow prebolus() { - prebolus = true; - return this; - } - - public OptionsToShow duration() { - duration = true; - return this; - } - - public OptionsToShow percent() { - percent = true; - return this; - } - - public OptionsToShow absolute() { - absolute = true; - return this; - } - - public OptionsToShow profile() { - profile = true; - return this; - } - - public OptionsToShow split() { - split = true; - return this; - } - - public OptionsToShow tempTarget() { - tempTarget = true; - return this; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt index 3843f4c946..c7c7a7689d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt @@ -35,6 +35,7 @@ class FoodFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var foodPlugin: FoodPlugin + @Inject lateinit var nsUpload: NSUpload private val disposable = CompositeDisposable() private lateinit var unfiltered: List @@ -200,7 +201,7 @@ class FoodFragment : DaggerFragment() { activity?.let { activity -> showConfirmation(activity, resourceHelper.gs(R.string.confirmation), resourceHelper.gs(R.string.removerecord) + "\n" + food.name, DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> if (food._id != null && food._id != "") { - NSUpload.removeFoodFromNS(food._id) + nsUpload.removeFoodFromNS(food._id) } foodPlugin.service?.delete(food) }, null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index 9c41df2666..3482a9b11a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -28,6 +28,6 @@ class FoodPlugin @Inject constructor( override fun onStart() { super.onStart() - service = FoodService() + service = FoodService(injector) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java index 405fc22b50..8b69403960 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java @@ -15,7 +15,6 @@ import com.j256.ormlite.table.TableUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.sql.SQLException; import java.util.ArrayList; @@ -25,15 +24,17 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventNsFood; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.utils.FabricPrivacy; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @@ -43,16 +44,20 @@ import io.reactivex.schedulers.Schedulers; */ public class FoodService extends OrmLiteBaseService { - private Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATAFOOD); + @Inject AAPSLogger aapsLogger; + @Inject RxBusWrapper rxBus; + @Inject FabricPrivacy fabricPrivacy; + private CompositeDisposable disposable = new CompositeDisposable(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledFoodEventPost = null; - public FoodService() { + public FoodService(HasAndroidInjector injector) { + injector.androidInjector().inject(this); onCreate(); dbInitialize(); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventNsFood.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -62,7 +67,7 @@ public class FoodService extends OrmLiteBaseService { this.createFoodFromJsonIfNotExists(array); else this.deleteNS(array); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); } @@ -88,7 +93,7 @@ public class FoodService extends OrmLiteBaseService { try { return DaoManager.createDao(this.getConnectionSource(), Food.class); } catch (SQLException e) { - log.error("Cannot create Dao for Food.class"); + aapsLogger.error("Cannot create Dao for Food.class"); } return null; @@ -98,18 +103,16 @@ public class FoodService extends OrmLiteBaseService { public void onCreate() { super.onCreate(); try { - if (L.isEnabled(LTag.DATAFOOD)) - log.info("onCreate"); + aapsLogger.info(LTag.DATAFOOD, "onCreate"); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); } catch (SQLException e) { - log.error("Can't create database", e); + aapsLogger.error("Can't create database", e); throw new RuntimeException(e); } } public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { - if (L.isEnabled(LTag.DATAFOOD)) - log.info("onUpgrade"); + aapsLogger.info(LTag.DATAFOOD, "onUpgrade"); // this.resetFood(); } @@ -122,7 +125,7 @@ public class FoodService extends OrmLiteBaseService { TableUtils.dropTable(this.getConnectionSource(), Food.class, true); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleFoodChange(); } @@ -147,9 +150,8 @@ public class FoodService extends OrmLiteBaseService { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("Firing EventFoodChange"); - RxBus.Companion.getINSTANCE().send(event); + aapsLogger.debug(LTag.DATAFOOD, "Firing EventFoodChange"); + rxBus.send(event); callback.setPost(null); } } @@ -183,7 +185,7 @@ public class FoodService extends OrmLiteBaseService { try { return this.getDao().queryForAll(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); @@ -208,7 +210,7 @@ public class FoodService extends OrmLiteBaseService { Food food = Food.createFromJson(json); this.createFoodFromJsonIfNotExists(food); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -220,7 +222,7 @@ public class FoodService extends OrmLiteBaseService { this.createFoodFromJsonIfNotExists(food); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -233,7 +235,7 @@ public class FoodService extends OrmLiteBaseService { String _id = json.getString("_id"); this.deleteByNSId(_id); } catch (JSONException | SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -244,7 +246,7 @@ public class FoodService extends OrmLiteBaseService { this.deleteNS(json); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -258,8 +260,7 @@ public class FoodService extends OrmLiteBaseService { public void deleteByNSId(String _id) throws SQLException { Food stored = this.findByNSId(_id); if (stored != null) { - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("Removing Food record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATAFOOD, "Removing Food record from database: " + stored.toString()); this.delete(stored); } } @@ -276,7 +277,7 @@ public class FoodService extends OrmLiteBaseService { this.getDao().delete(food); this.scheduleFoodChange(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -312,10 +313,9 @@ public class FoodService extends OrmLiteBaseService { public void createOrUpdate(Food food) { try { this.getDao().createOrUpdate(food); - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("Created or Updated: " + food.toString()); + aapsLogger.debug(LTag.DATAFOOD, "Created or Updated: " + food.toString()); } catch (SQLException e) { - log.error("Unable to createOrUpdate Food", e); + aapsLogger.error("Unable to createOrUpdate Food", e); } this.scheduleFoodChange(); } @@ -323,10 +323,9 @@ public class FoodService extends OrmLiteBaseService { public void create(Food food) { try { this.getDao().create(food); - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("New record: " + food.toString()); + aapsLogger.debug(LTag.DATAFOOD, "New record: " + food.toString()); } catch (SQLException e) { - log.error("Unable to create Food", e); + aapsLogger.error("Unable to create Food", e); } this.scheduleFoodChange(); } @@ -346,7 +345,7 @@ public class FoodService extends OrmLiteBaseService { return list.get(0); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt index 4d9021bb71..4fa6c43fce 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt @@ -20,7 +20,6 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.maintenance.formats.* -import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt index ec88c07bec..122bfe74d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt @@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.general.maintenance.formats import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.CryptoUtil -import info.nightscout.androidaps.utils.hexStringToByteArray +import info.nightscout.androidaps.utils.extensions.hexStringToByteArray +import info.nightscout.androidaps.utils.extensions.toHex import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.storage.Storage -import info.nightscout.androidaps.utils.toHex import org.json.JSONException import org.json.JSONObject import java.io.File @@ -55,13 +55,13 @@ class EncryptedPrefsFormat @Inject constructor( for ((metaKey, metaEntry) in prefs.metadata) { if (metaKey == PrefsMetadataKey.FILE_FORMAT) - continue; + continue if (metaKey == PrefsMetadataKey.ENCRYPTION) - continue; + continue meta.put(metaKey.key, metaEntry.value) } - container.put(PrefsMetadataKey.FILE_FORMAT.key, if (encrypted) FORMAT_KEY_ENC else FORMAT_KEY_NOENC); + container.put(PrefsMetadataKey.FILE_FORMAT.key, if (encrypted) FORMAT_KEY_ENC else FORMAT_KEY_NOENC) container.put("metadata", meta) val security = JSONObject() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java index 89d0f65bc7..4ba13a8fb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientN import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.alertDialogs.OKDialog; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -33,6 +34,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList @Inject SP sp; @Inject ResourceHelper resourceHelper; @Inject RxBusWrapper rxBus; + @Inject UploadQueue uploadQueue; @Inject FabricPrivacy fabricPrivacy; private CompositeDisposable disposable = new CompositeDisposable(); @@ -119,13 +121,13 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList break; case R.id.nsclientinternal_clearqueue: OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.nsclientinternal), resourceHelper.gs(R.string.clearqueueconfirm), () -> { - UploadQueue.clearQueue(); + uploadQueue.clearQueue(); updateGui(); fabricPrivacy.logCustom("NSClientClearQueue"); }); break; case R.id.nsclientinternal_showqueue: - rxBus.send(new EventNSClientNewLog("QUEUE", nsClientPlugin.queue().textList())); + rxBus.send(new EventNSClientNewLog("QUEUE", uploadQueue.textList())); break; } } @@ -154,7 +156,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList logScrollview.fullScroll(ScrollView.FOCUS_DOWN); } urlTextView.setText(nsClientPlugin.url()); - Spanned queuetext = Html.fromHtml(resourceHelper.gs(R.string.queue) + " " + UploadQueue.size() + ""); + Spanned queuetext = HtmlHelper.INSTANCE.fromHtml(resourceHelper.gs(R.string.queue) + " " + uploadQueue.size() + ""); queueTextView.setText(queuetext); statusTextView.setText(nsClientPlugin.status); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index da77936384..1764142432 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -7,7 +7,6 @@ import android.content.ServiceConnection; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; -import android.text.Html; import android.text.Spanned; import androidx.preference.PreferenceFragmentCompat; @@ -42,6 +41,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientS import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -56,13 +56,14 @@ public class NSClientPlugin extends PluginBase { private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; private final Context context; + private final FabricPrivacy fabricPrivacy; private final SP sp; private final Config config; public Handler handler; private final List listLog = new ArrayList<>(); - Spanned textLog = Html.fromHtml(""); + Spanned textLog = HtmlHelper.INSTANCE.fromHtml(""); public boolean paused; boolean autoscroll; @@ -80,6 +81,7 @@ public class NSClientPlugin extends PluginBase { RxBusWrapper rxBus, ResourceHelper resourceHelper, Context context, + FabricPrivacy fabricPrivacy, SP sp, NsClientReceiverDelegate nsClientReceiverDelegate, Config config @@ -98,6 +100,7 @@ public class NSClientPlugin extends PluginBase { this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.context = context; + this.fabricPrivacy = fabricPrivacy; this.sp = sp; this.nsClientReceiverDelegate = nsClientReceiverDelegate; this.config = config; @@ -134,17 +137,17 @@ public class NSClientPlugin extends PluginBase { .subscribe(event -> { status = event.getStatus(resourceHelper); rxBus.send(new EventNSClientUpdateGUI()); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNetworkChange.class) .observeOn(Schedulers.io()) - .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) .observeOn(Schedulers.io()) - .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventAppExit.class) @@ -153,7 +156,7 @@ public class NSClientPlugin extends PluginBase { if (nsClientService != null) { context.unbindService(mConnection); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientNewLog.class) @@ -161,17 +164,17 @@ public class NSClientPlugin extends PluginBase { .subscribe(event -> { addToLog(event); aapsLogger.debug(LTag.NSCLIENT, event.getAction() + " " + event.getLogText()); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventChargingState.class) .observeOn(Schedulers.io()) - .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientResend.class) .observeOn(Schedulers.io()) - .subscribe(event -> resend(event.getReason()), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> resend(event.getReason()), fabricPrivacy::logException) ); } @@ -236,7 +239,7 @@ public class NSClientPlugin extends PluginBase { newTextLog.append(log.toPreparedHtml()); } } - textLog = Html.fromHtml(newTextLog.toString()); + textLog = HtmlHelper.INSTANCE.fromHtml(newTextLog.toString()); } catch (OutOfMemoryError e) { ToastUtils.showToastInUiThread(context, rxBus, "Out of memory!\nStop using this phone !!!", R.raw.error); } @@ -253,10 +256,6 @@ public class NSClientPlugin extends PluginBase { rxBus.send(new EventPreferenceChange(resourceHelper, R.string.key_nsclientinternal_paused)); } - public UploadQueue queue() { - return NSClientService.uploadQueue; - } - public String url() { return NSClientService.nsURL; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java index 0786aae250..08fecd9283 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java @@ -8,70 +8,86 @@ import com.j256.ormlite.dao.CloseableIterator; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.sql.SQLException; -import info.nightscout.androidaps.MainApp; +import javax.inject.Inject; + import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DbRequest; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; +import info.nightscout.androidaps.interfaces.UploadQueueInterface; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 21.02.2016. */ -public class UploadQueue { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); +public class UploadQueue implements UploadQueueInterface { + private final AAPSLogger aapsLogger; + private final DatabaseHelperInterface databaseHelper; + private final Context context; + private final SP sp; + private final RxBusWrapper rxBus; - public static String status() { - return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); + @Inject + public UploadQueue( + AAPSLogger aapsLogger, + DatabaseHelperInterface databaseHelper, + Context context, + SP sp, + RxBusWrapper rxBus + ) { + this.aapsLogger = aapsLogger; + this.databaseHelper = databaseHelper; + this.context = context; + this.sp = sp; + this.rxBus = rxBus; } - public static long size() { - return MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); + public String status() { + return "QUEUE: " + databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS); } - private static void startService() { + public long size() { + return databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS); + } + + private void startService() { if (NSClientService.handler == null) { - Context context = MainApp.instance(); context.startService(new Intent(context, NSClientService.class)); SystemClock.sleep(2000); } } - public static void add(final DbRequest dbr) { - if (SP.getBoolean(R.string.key_ns_noupload, false)) return; - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Adding to queue: " + dbr.log()); + public void add(final DbRequest dbr) { + if (sp.getBoolean(R.string.key_ns_noupload, false)) return; + aapsLogger.debug(LTag.NSCLIENT, "Adding to queue: " + dbr.log()); try { - MainApp.getDbHelper().create(dbr); + databaseHelper.create(dbr); } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } - RxBus.getINSTANCE().send(new EventNSClientResend("newdata")); + rxBus.send(new EventNSClientResend("newdata")); } - static void clearQueue() { + void clearQueue() { startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("ClearQueue"); - MainApp.getDbHelper().deleteAllDbRequests(); - if (L.isEnabled(LTag.NSCLIENT)) - log.debug(status()); + aapsLogger.debug(LTag.NSCLIENT, "ClearQueue"); + databaseHelper.deleteAllDbRequests(); + aapsLogger.debug(LTag.NSCLIENT, status()); }); } } - public static void removeID(final JSONObject record) { + public void removeID(final JSONObject record) { startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { @@ -82,26 +98,24 @@ public class UploadQueue { } else { return; } - if (MainApp.getDbHelper().deleteDbRequest(id) == 1) { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Removed item from UploadQueue. " + UploadQueue.status()); + if (databaseHelper.deleteDbRequest(id) == 1) { + aapsLogger.debug(LTag.NSCLIENT, "Removed item from UploadQueue. " + status()); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } }); } } - public static void removeID(final String action, final String _id) { + public void removeID(final String action, final String _id) { if (_id == null || _id.equals("")) return; startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { - MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status()); + databaseHelper.deleteDbRequestbyMongoId(action, _id); + aapsLogger.debug(LTag.NSCLIENT, "Removing " + _id + " from UploadQueue. " + status()); }); } } @@ -110,7 +124,7 @@ public class UploadQueue { String result = ""; CloseableIterator iterator; try { - iterator = MainApp.getDbHelper().getDbRequestInterator(); + iterator = databaseHelper.getDbRequestInterator(); try { while (iterator.hasNext()) { DbRequest dbr = iterator.next(); @@ -123,7 +137,7 @@ public class UploadQueue { iterator.close(); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return result; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java index 8541253f81..dbd9151938 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java @@ -2,13 +2,11 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONArray; import org.json.JSONObject; -import org.slf4j.Logger; import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import io.socket.client.Ack; @@ -16,16 +14,23 @@ import io.socket.client.Ack; * Created by mike on 29.12.2015. */ public class NSAddAck extends Event implements Ack { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + public String _id = null; public String nsClientID = null; public JSONObject json = null; + public NSAddAck(AAPSLogger aapsLogger, RxBusWrapper rxBus) { + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; + } + public void call(Object... args) { // Regular response try { JSONArray responsearray = (JSONArray) (args[0]); - JSONObject response = null; + JSONObject response; if (responsearray.length() > 0) { response = responsearray.getJSONObject(0); _id = response.getString("_id"); @@ -34,10 +39,10 @@ public class NSAddAck extends Event implements Ack { nsClientID = response.getString("NSCLIENT_ID"); } } - RxBus.Companion.getINSTANCE().send(this); + rxBus.send(this); return; } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } // Check for not authorized try { @@ -45,15 +50,13 @@ public class NSAddAck extends Event implements Ack { if (response.has("result")) { _id = null; if (response.getString("result").contains("Not")) { - RxBus.Companion.getINSTANCE().send(new EventNSClientRestart()); + rxBus.send(new EventNSClientRestart()); return; } - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("DBACCESS " + response.getString("result")); + aapsLogger.debug(LTag.NSCLIENT, "DBACCESS " + response.getString("result")); } - return; } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java index dd6267308a..ea47305be4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java @@ -3,19 +3,26 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONObject; import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import io.socket.client.Ack; -public class NSAuthAck extends Event implements Ack{ +public class NSAuthAck extends Event implements Ack { + + private final RxBusWrapper rxBus; + public boolean read = false; public boolean write = false; public boolean write_treatment = false; - public void call(Object...args) { - JSONObject response = (JSONObject)args[0]; + public NSAuthAck(RxBusWrapper rxBus) { + this.rxBus = rxBus; + } + + public void call(Object... args) { + JSONObject response = (JSONObject) args[0]; read = response.optBoolean("read"); write = response.optBoolean("write"); write_treatment = response.optBoolean("write_treatment"); - RxBus.Companion.getINSTANCE().send(this); + rxBus.send(this); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java index bc79bd2739..95a00279cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java @@ -2,19 +2,20 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import io.socket.client.Ack; /** * Created by mike on 21.02.2016. */ public class NSUpdateAck extends Event implements Ack { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + public boolean result = false; public String _id; public String action; @@ -27,17 +28,19 @@ public class NSUpdateAck extends Event implements Ack { result = true; else if (response.getString("result").equals("Missing _id")) { result = true; - log.debug("Internal error: Missing _id returned on dbUpdate ack"); + aapsLogger.debug(LTag.NSCLIENT, "Internal error: Missing _id returned on dbUpdate ack"); } - RxBus.Companion.getINSTANCE().send(this); + rxBus.send(this); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - public NSUpdateAck(String action, String _id) { + public NSUpdateAck(String action, String _id, AAPSLogger aapsLogger, RxBusWrapper rxBus) { super(); this.action = action; this._id = _id; + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java index 8e5da2448d..7195435515 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -158,7 +159,7 @@ public class NSDeviceStatus { public Spanned getExtendedPumpStatus() { if (deviceStatusPumpData != null && deviceStatusPumpData.extended != null) return deviceStatusPumpData.extended; - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); } public Spanned getPumpStatus() { @@ -170,7 +171,7 @@ public class NSDeviceStatus { string.append(": "); if (deviceStatusPumpData == null) - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); // test warning level int level = Levels.INFO; @@ -225,7 +226,7 @@ public class NSDeviceStatus { string.append(""); // color - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } static class DeviceStatusPumpData { @@ -273,7 +274,7 @@ public class NSDeviceStatus { String value = extendedJson.getString(key); exteneded.append("").append(key).append(": ").append(value).append("
"); } - deviceStatusPumpData.extended = Html.fromHtml(exteneded.toString()); + deviceStatusPumpData.extended = HtmlHelper.INSTANCE.fromHtml(exteneded.toString()); } } catch (Exception e) { aapsLogger.error("Unhandled exception", e); @@ -345,7 +346,7 @@ public class NSDeviceStatus { } string.append(""); // color - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } public static long getOpenApsTimestamp() { @@ -365,11 +366,11 @@ public class NSDeviceStatus { string.append("").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append(" ").append(deviceStatusOpenAPSData.enacted.getString("reason")).append("
"); if (deviceStatusOpenAPSData.suggested != null) string.append("").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append(" ").append(deviceStatusOpenAPSData.suggested.getString("reason")).append("
"); - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); } // ********* Uploader data *********** @@ -441,7 +442,7 @@ public class NSDeviceStatus { string.append(minBattery); string.append("%"); - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } public Spanned getExtendedUploaderStatus() { @@ -455,7 +456,7 @@ public class NSDeviceStatus { string.append("").append(device).append(": ").append(uploader.battery).append("%
"); } - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } public static APSResult getAPSResult(HasAndroidInjector injector) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 3187ccc924..cc5057f7eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -19,7 +19,6 @@ import com.j256.ormlite.dao.CloseableIterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.net.URISyntaxException; import java.sql.SQLException; @@ -31,19 +30,17 @@ import javax.inject.Inject; import dagger.android.DaggerService; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; @@ -83,16 +80,17 @@ public class NSClientService extends DaggerService { @Inject AAPSLogger aapsLogger; @Inject NSSettingsStatus nsSettingsStatus; @Inject NSDeviceStatus nsDeviceStatus; - @Inject MainApp mainApp; + @Inject DatabaseHelperInterface databaseHelper; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; @Inject SP sp; + @Inject FabricPrivacy fabricPrivacy; @Inject NSClientPlugin nsClientPlugin; @Inject BuildHelper buildHelper; @Inject Config config; @Inject DateUtil dateUtil; + @Inject UploadQueue uploadQueue; - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); private CompositeDisposable disposable = new CompositeDisposable(); static public PowerManager.WakeLock mWakeLock; @@ -124,8 +122,6 @@ public class NSClientService extends DaggerService { private String nsAPIhashCode = ""; - public static UploadQueue uploadQueue = new UploadQueue(); - private final ArrayList reconnections = new ArrayList<>(); private int WATCHDOG_INTERVAL_MINUTES = 2; private int WATCHDOG_RECONNECT_IN = 15; @@ -143,7 +139,7 @@ public class NSClientService extends DaggerService { @Override public void onCreate() { super.onCreate(); - PowerManager powerManager = (PowerManager) mainApp.getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService"); mWakeLock.acquire(); @@ -158,7 +154,7 @@ public class NSClientService extends DaggerService { destroy(); initialize(); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) @@ -172,17 +168,16 @@ public class NSClientService extends DaggerService { destroy(); initialize(); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("EventAppExit received"); + aapsLogger.debug(LTag.NSCLIENT, "EventAppExit received"); destroy(); stopSelf(); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientRestart.class) @@ -190,22 +185,22 @@ public class NSClientService extends DaggerService { .subscribe(event -> { latestDateInReceivedData = 0; restart(); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSAuthAck.class) .observeOn(Schedulers.io()) - .subscribe(this::processAuthAck, exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::processAuthAck, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSUpdateAck.class) .observeOn(Schedulers.io()) - .subscribe(this::processUpdateAck, exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::processUpdateAck, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSAddAck.class) .observeOn(Schedulers.io()) - .subscribe(this::processAddAck, exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::processAddAck, fabricPrivacy::logException) ); } @@ -275,6 +270,7 @@ public class NSClientService extends DaggerService { return START_STICKY; } + @SuppressWarnings("deprecation") public void initialize() { dataCounter = 0; @@ -333,7 +329,7 @@ public class NSClientService extends DaggerService { String socketId = mSocket != null ? mSocket.id() : "NULL"; rxBus.send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId)); if (mSocket != null) - sendAuthMessage(new NSAuthAck()); + sendAuthMessage(new NSAuthAck(rxBus)); watchdog(); } }; @@ -367,8 +363,7 @@ public class NSClientService extends DaggerService { private Emitter.Listener onDisconnect = new Emitter.Listener() { @Override public void call(Object... args) { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("disconnect reason: {}", args); + aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: {}", args); rxBus.send(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } }; @@ -402,7 +397,7 @@ public class NSClientService extends DaggerService { authMessage.put("from", latestDateInReceivedData); // send data newer than authMessage.put("secret", nsAPIhashCode); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); return; } rxBus.send(new EventNSClientNewLog("AUTH", "requesting auth")); @@ -456,8 +451,7 @@ public class NSClientService extends DaggerService { data = (JSONObject) args[0]; handleAnnouncement(data); } catch (Exception e) { - log.error("Unhandled exception", e); - return; + aapsLogger.error("Unhandled exception", e); } } }; @@ -483,8 +477,7 @@ public class NSClientService extends DaggerService { data = (JSONObject) args[0]; handleAlarm(data); } catch (Exception e) { - log.error("Unhandled exception", e); - return; + aapsLogger.error("Unhandled exception", e); } } }; @@ -495,7 +488,7 @@ public class NSClientService extends DaggerService { data = (JSONObject) args[0]; handleUrgentAlarm(data); } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } }; @@ -518,8 +511,7 @@ public class NSClientService extends DaggerService { rxBus.send(new EventDismissNotification(Notification.NSURGENTALARM)); aapsLogger.debug(LTag.NSCLIENT, data.toString()); } catch (Exception e) { - log.error("Unhandled exception", e); - return; + aapsLogger.error("Unhandled exception", e); } } }; @@ -528,7 +520,7 @@ public class NSClientService extends DaggerService { @Override public void call(final Object... args) { NSClientService.handler.post(() -> { - PowerManager powerManager = (PowerManager) mainApp.getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService_onDataUpdate"); wakeLock.acquire(); @@ -604,7 +596,7 @@ public class NSClientService extends DaggerService { NSTreatment treatment = new NSTreatment(jsonTreatment); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonTreatment); + uploadQueue.removeID(jsonTreatment); //Find latest date in treatment if (treatment.getMills() != null && treatment.getMills() < System.currentTimeMillis()) if (treatment.getMills() > latestDateInReceivedData) @@ -636,7 +628,7 @@ public class NSClientService extends DaggerService { for (Integer index = 0; index < devicestatuses.length(); index++) { JSONObject jsonStatus = devicestatuses.getJSONObject(index); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonStatus); + uploadQueue.removeID(jsonStatus); } nsDeviceStatus.handleNewData(devicestatuses); } @@ -652,7 +644,7 @@ public class NSClientService extends DaggerService { JSONObject jsonFood = foods.getJSONObject(index); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonFood); + uploadQueue.removeID(jsonFood); String action = JsonHelper.safeGetString(jsonFood, "action"); @@ -684,7 +676,7 @@ public class NSClientService extends DaggerService { for (Integer index = 0; index < mbgs.length(); index++) { JSONObject jsonMbg = mbgs.getJSONObject(index); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonMbg); + uploadQueue.removeID(jsonMbg); } handleNewMbg(mbgs, isDelta); } @@ -695,7 +687,7 @@ public class NSClientService extends DaggerService { // Retreive actual calibration for (Integer index = 0; index < cals.length(); index++) { // remove from upload queue if Ack is failing - UploadQueue.removeID(cals.optJSONObject(index)); + uploadQueue.removeID(cals.optJSONObject(index)); } handleNewCal(cals, isDelta); } @@ -709,7 +701,7 @@ public class NSClientService extends DaggerService { NSSgv sgv = new NSSgv(jsonSgv); // Handle new sgv here // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonSgv); + uploadQueue.removeID(jsonSgv); //Find latest date in sgv if (sgv.getMills() != null && sgv.getMills() < System.currentTimeMillis()) if (sgv.getMills() > latestDateInReceivedData) @@ -724,7 +716,7 @@ public class NSClientService extends DaggerService { } rxBus.send(new EventNSClientNewLog("LAST", dateUtil.dateAndTimeString(latestDateInReceivedData))); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } //rxBus.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); } finally { @@ -744,7 +736,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbUpdate", message, ack); rxBus.send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -758,7 +750,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbUpdateUnset", message, ack); rxBus.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -771,7 +763,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbRemove", message, ack); rxBus.send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -784,7 +776,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbAdd", message, ack); rxBus.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -795,7 +787,7 @@ public class NSClientService extends DaggerService { } public void resend(final String reason) { - if (UploadQueue.size() == 0) + if (uploadQueue.size() == 0) return; if (!isConnected || !hasWriteAuth) return; @@ -804,8 +796,7 @@ public class NSClientService extends DaggerService { if (mSocket == null || !mSocket.connected()) return; if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); + aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } lastResendTime = System.currentTimeMillis(); @@ -815,21 +806,21 @@ public class NSClientService extends DaggerService { CloseableIterator iterator; int maxcount = 30; try { - iterator = mainApp.getDbHelper().getDbRequestInterator(); + iterator = databaseHelper.getDbRequestInterator(); try { while (iterator.hasNext() && maxcount > 0) { DbRequest dbr = iterator.next(); if (dbr.action.equals("dbAdd")) { - NSAddAck addAck = new NSAddAck(); + NSAddAck addAck = new NSAddAck(aapsLogger, rxBus); dbAdd(dbr, addAck); } else if (dbr.action.equals("dbRemove")) { - NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id); + NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus); dbRemove(dbr, removeAck); } else if (dbr.action.equals("dbUpdate")) { - NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id); + NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus); dbUpdate(dbr, updateAck); } else if (dbr.action.equals("dbUpdateUnset")) { - NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id); + NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus); dbUpdateUnset(dbr, updateUnsetAck); } maxcount--; @@ -838,7 +829,7 @@ public class NSClientService extends DaggerService { iterator.close(); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } rxBus.send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); @@ -852,7 +843,7 @@ public class NSClientService extends DaggerService { private void handleAnnouncement(JSONObject announcement) { NSAlarm nsAlarm = new NSAlarm(announcement); - Notification notification = new NotificationWithAction(mainApp, nsAlarm); + Notification notification = new NotificationWithAction(injector, nsAlarm); rxBus.send(new EventNewNotification(notification)); rxBus.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(announcement, "message", "received"))); aapsLogger.debug(LTag.NSCLIENT, announcement.toString()); @@ -862,7 +853,7 @@ public class NSClientService extends DaggerService { long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L); if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { NSAlarm nsAlarm = new NSAlarm(alarm); - Notification notification = new NotificationWithAction(mainApp, nsAlarm); + Notification notification = new NotificationWithAction(injector, nsAlarm); rxBus.send(new EventNewNotification(notification)); } rxBus.send(new EventNSClientNewLog("ALARM", JsonHelper.safeGetString(alarm, "message", "received"))); @@ -873,7 +864,7 @@ public class NSClientService extends DaggerService { long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L); if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { NSAlarm nsAlarm = new NSAlarm(alarm); - Notification notification = new NotificationWithAction(mainApp, nsAlarm); + Notification notification = new NotificationWithAction(injector, nsAlarm); rxBus.send(new EventNewNotification(notification)); } rxBus.send(new EventNSClientNewLog("URGENTALARM", JsonHelper.safeGetString(alarm, "message", "received"))); @@ -887,7 +878,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_CAL); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } public void handleNewMbg(JSONArray mbgs, boolean isDelta) { @@ -897,7 +888,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_MBG); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } public void handleNewProfile(ProfileStore profile, boolean isDelta) { @@ -907,7 +898,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_PROFILE); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { bundle = new Bundle(); @@ -916,7 +907,7 @@ public class NSClientService extends DaggerService { intent = new Intent(Intents.ACTION_NEW_PROFILE); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.sendBroadcast(intent); + this.sendBroadcast(intent); } } @@ -929,7 +920,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_SGV); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -940,7 +931,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_SGV); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.sendBroadcast(intent); + this.sendBroadcast(intent); } } } @@ -954,7 +945,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -966,7 +957,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.getApplicationContext().sendBroadcast(intent); + this.getApplicationContext().sendBroadcast(intent); } } } @@ -980,7 +971,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -992,7 +983,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.getApplicationContext().sendBroadcast(intent); + this.getApplicationContext().sendBroadcast(intent); } } } @@ -1004,7 +995,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -1014,7 +1005,7 @@ public class NSClientService extends DaggerService { intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.getApplicationContext().sendBroadcast(intent); + this.getApplicationContext().sendBroadcast(intent); } } @@ -1040,7 +1031,7 @@ public class NSClientService extends DaggerService { ret.add(newarr); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); ret = new ArrayList<>(); ret.add(array); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index 663bc52c6b..a2fe9ce136 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -21,6 +21,7 @@ import android.view.View.OnLongClickListener import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView +import androidx.core.text.toSpanned import androidx.recyclerview.widget.LinearLayoutManager import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector @@ -351,8 +352,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList if (loopPlugin.isEnabled(PluginType.LOOP)) { val lastRun = loopPlugin.lastRun loopPlugin.invoke("Accept temp button", false) - if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed.isChangeRequested) { - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), lastRun.constraintsProcessed.toSpanned(), Runnable { + if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned() + ?: "".toSpanned(), Runnable { aapsLogger.debug("USER ENTRY: ACCEPT TEMP BASAL") overview_accepttempbutton?.visibility = View.GONE (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) @@ -449,7 +451,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val showAcceptButton = !closedLoopEnabled.value() && // Open mode needed lastRun != null && (lastRun.lastOpenModeAccept == 0L || lastRun.lastOpenModeAccept < lastRun.lastAPSRun) &&// never accepted or before last result - lastRun.constraintsProcessed.isChangeRequested // change is requested + lastRun.constraintsProcessed?.isChangeRequested == true // change is requested if (showAcceptButton && pump.isInitialized && !pump.isSuspended && loopPlugin.isEnabled(PluginType.LOOP)) { overview_accepttempbutton?.visibility = View.VISIBLE @@ -669,9 +671,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_basebasal?.text = activeTemp?.let { if (resourceHelper.shortTextMode()) "T:" + activeTemp.toStringVeryShort() else activeTemp.toStringFull() } ?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal) overview_basal_llayout?.setOnClickListener { - var fullText = "${resourceHelper.gs(R.string.pump_basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}" + var fullText = "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}" if (activeTemp != null) - fullText += "\n" + resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull() + fullText += "\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + activeTemp.toStringFull() activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.basal), fullText) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt index 69c6f84cb2..1cc60f0400 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt @@ -206,7 +206,7 @@ class OverviewMenus @Inject constructor( R.id.overview_activeprofile -> { menu.setHeaderTitle(resourceHelper.gs(R.string.profile)) - menu.add(resourceHelper.gs(R.string.danar_viewprofile)) + menu.add(resourceHelper.gs(R.string.viewprofile)) if (activePlugin.activeProfileInterface.profile != null) { menu.add(resourceHelper.gs(R.string.careportal_profileswitch)) } @@ -341,18 +341,18 @@ class OverviewMenus @Inject constructor( return true } - resourceHelper.gs(R.string.disconnectpumpfor3h) -> { + resourceHelper.gs(R.string.disconnectpumpfor3h) -> { aapsLogger.debug("USER ENTRY: DISCONNECT 3h") loopPlugin.disconnectPump(180, profile) rxBus.send(EventRefreshOverview("suspendmenu")) return true } - resourceHelper.gs(R.string.careportal_profileswitch) -> { + resourceHelper.gs(R.string.careportal_profileswitch) -> { ProfileSwitchDialog().show(manager, "Overview") } - resourceHelper.gs(R.string.danar_viewprofile) -> { + resourceHelper.gs(R.string.viewprofile) -> { val args = Bundle() args.putLong("time", DateUtil.now()) args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) @@ -361,7 +361,7 @@ class OverviewMenus @Inject constructor( pvd.show(manager, "ProfileViewDialog") } - resourceHelper.gs(R.string.eatingsoon) -> { + resourceHelper.gs(R.string.eatingsoon) -> { aapsLogger.debug("USER ENTRY: TEMP TARGET EATING SOON") val target = Profile.toMgdl(defaultValueHelper.determineEatingSoonTT(), profileFunction.getUnits()) val tempTarget = TempTarget() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index 02ccf1480f..70e4f9f8fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -16,10 +16,10 @@ import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.LoopInterface import info.nightscout.androidaps.interfaces.TreatmentsInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin.LastRun import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.graphExtensions.* @@ -197,7 +197,7 @@ class GraphData(injector: HasAndroidInjector, private val graph: GraphView, priv basalScale.setMultiplier(maxY * scale / maxBasalValueFound) } - fun addTargetLine(fromTime: Long, toTimeParam: Long, profile: Profile, lastRun: LastRun?) { + fun addTargetLine(fromTime: Long, toTimeParam: Long, profile: Profile, lastRun: LoopInterface.LastRun?) { var toTime = toTimeParam val targetsSeriesArray: MutableList = ArrayList() var lastTarget = -1.0 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt index 8d4c605057..8a4524d9e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt @@ -50,9 +50,9 @@ class DummyService : DaggerService() { stopForeground(true) } - override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) startForeground(notificationHolder.notificationID, notificationHolder.notification) return Service.START_STICKY } -} \ No newline at end of file +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index e8d32ed386..ca4b8c1720 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -14,7 +14,6 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.events.* import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index 8aed0f5288..29ed323ee1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R +import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent @@ -23,11 +24,10 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -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.danar.DanaRPlugin +import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin +import info.nightscout.androidaps.danars.DanaRSPlugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.queue.Callback @@ -65,7 +65,7 @@ class ActionStringHandler @Inject constructor( private val danaRKoreanPlugin: DanaRKoreanPlugin, private val danaRv2Plugin: DanaRv2Plugin, private val danaRSPlugin: DanaRSPlugin, - private val danaRPump: DanaRPump, + private val danaPump: DanaPump, private val hardLimits: HardLimits, private val carbsGenerator: CarbsGenerator, private val dateUtil: DateUtil, @@ -326,7 +326,7 @@ class ActionStringHandler @Inject constructor( message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "\n" } else if (pump is DanaRPlugin) { - val tdd = danaRPump.dailyTotalUnits + val tdd = danaPump.dailyTotalUnits message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "\n" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index abff22eae3..02b201f5ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -104,7 +104,7 @@ class WearPlugin @Inject constructor( .observeOn(Schedulers.io()) .subscribe({ event: EventDismissBolusProgressIfRunning -> if (event.result == null) return@subscribe - val status: String = if (event.result.success) { + val status: String = if (event.result!!.success) { resourceHelper.gs(R.string.success) } else { resourceHelper.gs(R.string.nosuccess) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index e0a0657826..dd0babf951 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -531,9 +531,9 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } - final LoopPlugin.LastRun finalLastRun = loopPlugin.lastRun; - if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.request.hasPredictions && finalLastRun.constraintsProcessed != null) { - List predArray = finalLastRun.constraintsProcessed.getPredictions(); + final LoopPlugin.LastRun finalLastRun = loopPlugin.getLastRun(); + if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().hasPredictions && finalLastRun.getConstraintsProcessed() != null) { + List predArray = finalLastRun.getConstraintsProcessed().getPredictions(); if (!predArray.isEmpty()) { for (BgReading bg : predArray) { @@ -715,7 +715,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog //OpenAPS status if (config.getAPS()) { //we are AndroidAPS - openApsStatus = loopPlugin.lastRun != null && loopPlugin.lastRun.lastTBREnact != 0 ? loopPlugin.lastRun.lastTBREnact : -1; + openApsStatus = loopPlugin.getLastRun() != null && loopPlugin.getLastRun().getLastTBREnact() != 0 ? loopPlugin.getLastRun().getLastTBREnact() : -1; } else { //NSClient or remote openApsStatus = NSDeviceStatus.getOpenApsTimestamp(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index ef64d4a690..057fe53ee0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt @@ -45,7 +45,7 @@ class LocalProfileFragment : DaggerFragment() { private val save = Runnable { doEdit() - basalView?.updateLabel(resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel()) + basalView?.updateLabel(resourceHelper.gs(R.string.basal_label) + ": " + sumLabel()) } private val textWatch = object : TextWatcher { @@ -106,14 +106,14 @@ class LocalProfileFragment : DaggerFragment() { localprofile_name.addTextChangedListener(textWatch) localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, hardLimits.MINDIA, hardLimits.MAXDIA, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch) localprofile_dia.tag = "LP_DIA" - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label), localProfilePlugin.currentProfile().ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save) - basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.ic_label), localProfilePlugin.currentProfile().ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save) + basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) if (units == Constants.MGDL) { - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save) - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label), localProfilePlugin.currentProfile().isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) } else { - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save) - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save) } // Spinner @@ -190,10 +190,10 @@ class LocalProfileFragment : DaggerFragment() { localprofile_units.text = resourceHelper.gs(R.string.units_colon) + " " + (if (localProfilePlugin.currentProfile().mgdl) resourceHelper.gs(R.string.mgdl) else resourceHelper.gs(R.string.mmol)) localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, MIN_DIA, 12.0, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch) localprofile_dia.tag = "LP_DIA" - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label) + ":", localProfilePlugin.currentProfile().ic, null, 0.5, 50.0, 0.1, DecimalFormat("0.0"), save) - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label) + ":", localProfilePlugin.currentProfile().isf, null, 0.5, 500.0, 0.1, DecimalFormat("0.0"), save) - basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) - TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label) + ":", localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, 3.0, 200.0, 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.ic_label) + ":", localProfilePlugin.currentProfile().ic, null, 0.5, 50.0, 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label) + ":", localProfilePlugin.currentProfile().isf, null, 0.5, 500.0, 0.1, DecimalFormat("0.0"), save) + basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label) + ":", localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, 3.0, 200.0, 0.1, DecimalFormat("0.0"), save) updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index 8d2761cfa3..7944707e57 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -37,7 +37,8 @@ class LocalProfilePlugin @Inject constructor( private val rxBus: RxBusWrapper, resourceHelper: ResourceHelper, private val sp: SP, - private val profileFunction: ProfileFunction + private val profileFunction: ProfileFunction, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.PROFILE) .fragmentClass(LocalProfileFragment::class.java.name) @@ -140,7 +141,7 @@ class LocalProfilePlugin @Inject constructor( if (name.contains(".")) namesOK = false } if (namesOK) - rawProfile?.let { NSUpload.uploadProfileStore(it.data) } + rawProfile?.let { nsUpload.uploadProfileStore(it.data) } else activity?.let { OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index ace9df0a97..50f40318d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -485,7 +485,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr getAapsLogger().error("deliverTreatment: Invalid input"); return new PumpEnactResult(getInjector()).success(false).enacted(false) .bolusDelivered(0d).carbsDelivered(0d) - .comment(getResourceHelper().gs(R.string.danar_invalidinput)); + .comment(getResourceHelper().gs(R.string.invalidinput)); } else if (detailedBolusInfo.insulin > 0) { // bolus needed, ask pump to deliver it return deliverBolus(detailedBolusInfo); @@ -1259,7 +1259,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr } @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { if (!pump.initialized) { return null; } @@ -1281,7 +1281,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr pumpJson.put("status", statusJson); JSONObject extendedJson = new JSONObject(); - extendedJson.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extendedJson.put("Version", version); extendedJson.put("ActiveProfile", profileFunction.getProfileName()); PumpState ps = pump.state; if (ps.tbrActive) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index 0bb38acb76..6227d2ea2a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -324,7 +324,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { if ((getPumpStatusData().lastConnection + 5 * 60 * 1000L) < System.currentTimeMillis()) { return new JSONObject(); @@ -337,7 +337,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI try { battery.put("percent", getPumpStatusData().batteryRemaining); status.put("status", getPumpStatusData().pumpStatusType != null ? getPumpStatusData().pumpStatusType.getStatus() : "normal"); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extended.put("Version", version); try { extended.put("ActiveProfile", profileName); } catch (Exception ignored) { @@ -413,7 +413,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI // neither carbs nor bolus requested aapsLogger.error("deliverTreatment: Invalid input"); return new PumpEnactResult(getInjector()).success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d) - .comment(getResourceHelper().gs(R.string.danar_invalidinput)); + .comment(getResourceHelper().gs(R.string.invalidinput)); } else if (detailedBolusInfo.insulin > 0) { // bolus needed, ask pump to deliver it return deliverBolus(detailedBolusInfo); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java index bbe96c41c5..9958d290e4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java @@ -3,8 +3,8 @@ package info.nightscout.androidaps.plugins.pump.common.defs; import java.util.ArrayList; import java.util.List; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.utils.resources.ResourceHelper; /** @@ -16,58 +16,49 @@ import info.nightscout.androidaps.R; public enum PumpHistoryEntryGroup { - All(R.string.medtronic_history_group_all), // - Bolus(R.string.danar_history_bolus), // - Basal(R.string.medtronic_history_group_basal), // - Prime(R.string.danar_history_prime), // - Configuration(R.string.medtronic_history_group_configuration), // - Alarm(R.string.danar_history_alarm), // - Glucose(R.string.danar_history_glucose), // - Notification(R.string.medtronic_history_group_notification), // + All(R.string.medtronic_history_group_all), + Bolus(R.string.danar_history_bolus), + Basal(R.string.medtronic_history_group_basal), + Prime(R.string.danar_history_prime), + Configuration(R.string.medtronic_history_group_configuration), + Alarm(R.string.danar_history_alarm), + Glucose(R.string.danar_history_glucose), + Notification(R.string.medtronic_history_group_notification), Statistic(R.string.medtronic_history_group_statistic), - Unknown(R.string.medtronic_history_group_unknown), // + Unknown(R.string.medtronic_history_group_unknown), ; private int resourceId; private String translated; - public static boolean doNotTranslate = false; - - private static List list; - - static { - list = new ArrayList<>(); - - for (PumpHistoryEntryGroup pumpHistoryEntryGroup : values()) { - //if (doNotTranslate) { - pumpHistoryEntryGroup.translated = MainApp.gs(pumpHistoryEntryGroup.resourceId); - //} - list.add(pumpHistoryEntryGroup); - } - } - + private static List translatedList; PumpHistoryEntryGroup(int resourceId) { this.resourceId = resourceId; - // this.translated = MainApp.gs(resourceId); } + private static void doTranslation(ResourceHelper resourceHelper) { + translatedList = new ArrayList<>(); - public static List getList() { - return list; + for (PumpHistoryEntryGroup pumpHistoryEntryGroup : values()) { + pumpHistoryEntryGroup.translated = resourceHelper.gs(pumpHistoryEntryGroup.resourceId); + translatedList.add(pumpHistoryEntryGroup); + } } + public static List getTranslatedList(ResourceHelper resourceHelper) { + if (translatedList == null) doTranslation(resourceHelper); + return translatedList; + } public int getResourceId() { return resourceId; } - public String getTranslated() { return translated; } - public String toString() { return this.translated; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java index ccb47a7d4a..c70b7e033a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEScanActivity.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.common.dialog; -import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.le.BluetoothLeScanner; @@ -9,8 +8,6 @@ import android.bluetooth.le.ScanFilter; import android.bluetooth.le.ScanResult; import android.bluetooth.le.ScanSettings; import android.content.Context; -import android.content.Intent; -import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.ParcelUuid; @@ -26,13 +23,11 @@ import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.widget.Toolbar; -import androidx.core.app.ActivityCompat; -import androidx.core.content.ContextCompat; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -46,13 +41,12 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; +import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice; -import info.nightscout.androidaps.plugins.pump.common.utils.LocationHelper; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged; import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodPumpValuesChanged; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -65,6 +59,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { @Inject SP sp; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; + @Inject BlePreCheck blePrecheck; @Inject RileyLinkUtil rileyLinkUtil; @Inject ActivePluginProvider activePlugin; @@ -117,17 +112,17 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { PumpInterface activePump = activePlugin.getActivePump(); - if (activePump.manufacturer()== ManufacturerType.Medtronic) { - RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice)activePump; + if (activePump.manufacturer() == ManufacturerType.Medtronic) { + RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice) activePump; rileyLinkPump.getRileyLinkService().verifyConfiguration(); // force reloading of address - rxBus.send(new EventMedtronicPumpConfigurationChanged()); + rxBus.send(new EventMedtronicPumpConfigurationChanged()); - } else if (activePlugin.getActivePump().manufacturer()== ManufacturerType.Insulet) { - if (activePump.model()== PumpType.Insulet_Omnipod_Dash) { + } else if (activePlugin.getActivePump().manufacturer() == ManufacturerType.Insulet) { + if (activePump.model() == PumpType.Insulet_Omnipod_Dash) { aapsLogger.error("Omnipod Dash not yet implemented."); } else { - RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice)activePump; + RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice) activePump; rileyLinkPump.getRileyLinkService().verifyConfiguration(); // force reloading of address rxBus.send(new EventOmnipodPumpValuesChanged()); @@ -175,36 +170,13 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { public void prepareForScanning() { - // https://developer.android.com/training/permissions/requesting.html - // http://developer.radiusnetworks.com/2015/09/29/is-your-beacon-app-ready-for-android-6.html - if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { - Toast.makeText(this, R.string.rileylink_scanner_ble_not_supported, Toast.LENGTH_SHORT).show(); - } else { - // Use this check to determine whether BLE is supported on the device. Then - // you can selectively disable BLE-related features. - if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // your code that requires permission - ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, - PERMISSION_REQUEST_COARSE_LOCATION); - } + boolean checkOK = blePrecheck.prerequisitesCheck(this); - // Ensures Bluetooth is available on the device and it is enabled. If not, - // displays a dialog requesting user permission to enable Bluetooth. - if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { - Toast.makeText(this, R.string.rileylink_scanner_ble_not_enabled, Toast.LENGTH_SHORT).show(); - } else { - - // Will request that GPS be enabled for devices running Marshmallow or newer. - if (!LocationHelper.isLocationEnabled(this)) { - LocationHelper.requestLocationForBluetooth(this); - } - - mLEScanner = mBluetoothAdapter.getBluetoothLeScanner(); - settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); - filters = Arrays.asList(new ScanFilter.Builder().setServiceUuid( - ParcelUuid.fromString(GattAttributes.SERVICE_RADIO)).build()); - - } + if (checkOK) { + mLEScanner = mBluetoothAdapter.getBluetoothLeScanner(); + settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); + filters = Collections.singletonList(new ScanFilter.Builder().setServiceUuid( + ParcelUuid.fromString(GattAttributes.SERVICE_RADIO)).build()); } // disable currently selected RL, so that we can discover it @@ -212,19 +184,6 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity { } - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - super.onActivityResult(requestCode, resultCode, data); - if (requestCode == REQUEST_ENABLE_BT) { - if (resultCode == RESULT_OK) { - // User allowed Bluetooth to turn on - } else if (resultCode == RESULT_CANCELED) { - // Error, or user said "NO" - finish(); - } - } - } - private ScanCallback mScanCallback2 = new ScanCallback() { @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java index d352250071..12a0f0f4d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/RileyLinkCommunicationManager.java @@ -59,23 +59,23 @@ public abstract class RileyLinkCommunicationManager { // All pump communications go through this function. - protected E sendAndListen(RLMessage msg, int timeout_ms, Class clazz) + protected RLMessage sendAndListen(RLMessage msg, int timeout_ms) throws RileyLinkCommunicationException { - return sendAndListen(msg, timeout_ms, null, clazz); + return sendAndListen(msg, timeout_ms, null); } - private E sendAndListen(RLMessage msg, int timeout_ms, Integer extendPreamble_ms, Class clazz) + private RLMessage sendAndListen(RLMessage msg, int timeout_ms, Integer extendPreamble_ms) throws RileyLinkCommunicationException { - return sendAndListen(msg, timeout_ms, 0, extendPreamble_ms, clazz); + return sendAndListen(msg, timeout_ms, 0, extendPreamble_ms); } // For backward compatibility - private E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, Integer extendPreamble_ms, Class clazz) + private RLMessage sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, Integer extendPreamble_ms) throws RileyLinkCommunicationException { - return sendAndListen(msg, timeout_ms, repeatCount, 0, extendPreamble_ms, clazz); + return sendAndListen(msg, timeout_ms, repeatCount, 0, extendPreamble_ms); } - protected E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class clazz) + protected RLMessage sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms) throws RileyLinkCommunicationException { // internal flag @@ -88,7 +88,7 @@ public abstract class RileyLinkCommunicationManager { (byte) 0, (byte) repeatCount, (byte) 0, (byte) 0, timeout_ms, (byte) retryCount, extendPreamble_ms); RadioResponse radioResponse = rfSpyResponse.getRadioResponse(injector); - E response = createResponseMessage(radioResponse.getPayload(), clazz); + RLMessage response = createResponseMessage(radioResponse.getPayload()); if (response.isValid()) { // Mark this as the last time we heard from the pump. @@ -124,7 +124,7 @@ public abstract class RileyLinkCommunicationManager { } - public abstract E createResponseMessage(byte[] payload, Class clazz); + public abstract RLMessage createResponseMessage(byte[] payload); public abstract void setPumpDeviceState(PumpDeviceState pumpDeviceState); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java index 5482e224e3..fcfe1915a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java @@ -5,6 +5,7 @@ import java.util.Map; import info.nightscout.androidaps.R; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.utils.resources.ResourceHelper; public enum RileyLinkEncodingType { @@ -20,33 +21,31 @@ public enum RileyLinkEncodingType { private static Map encodingTypeMap; - static { - encodingTypeMap = new HashMap<>(); - - for (RileyLinkEncodingType encType : values()) { - if (encType.resourceId!=null) { - encodingTypeMap.put(MainApp.gs(encType.resourceId), encType); - } - } - } - - RileyLinkEncodingType(int value) { this.value = (byte)value; } - RileyLinkEncodingType(int value, Integer resourceId) { this.value = (byte)value; this.resourceId = resourceId; } - public static RileyLinkEncodingType getByDescription(String description) { + private static void doTranslation(ResourceHelper resourceHelper) { + encodingTypeMap = new HashMap<>(); + + for (RileyLinkEncodingType encType : values()) { + if (encType.resourceId!=null) { + encodingTypeMap.put(resourceHelper.gs(encType.resourceId), encType); + } + } + } + + public static RileyLinkEncodingType getByDescription(String description, ResourceHelper resourceHelper) { + if (encodingTypeMap == null) doTranslation(resourceHelper); if (encodingTypeMap.containsKey(description)) { return encodingTypeMap.get(description); } return RileyLinkEncodingType.FourByteSixByteLocal; } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java index 370015ab95..bc9a4a3aa0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/ResetRileyLinkConfigurationTask.java @@ -4,15 +4,10 @@ import javax.inject.Inject; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState; -import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService; /** * Created by geoff on 7/16/16. @@ -34,7 +29,7 @@ public class ResetRileyLinkConfigurationTask extends PumpTask { @Override public void run() { - RileyLinkPumpDevice pumpAbstract = (RileyLinkPumpDevice)activePlugin.getActivePump(); + RileyLinkPumpDevice pumpAbstract = (RileyLinkPumpDevice) activePlugin.getActivePump(); rxBus.send(new EventRefreshButtonState(false)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java deleted file mode 100644 index 03b42b730f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java +++ /dev/null @@ -1,69 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.utils; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.location.LocationManager; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.utils.alertDialogs.OKDialog; - -/** - * Helper for checking if location services are enabled on the device. - */ -public class LocationHelper { - - /** - * Determine if GPS is currently enabled. - *

- * On Android 6 (Marshmallow), location needs to be enabled for Bluetooth discovery to work. - * - * @param context The current app context. - * @return true if location is enabled, false otherwise. - */ - public static boolean isLocationEnabled(Context context) { - LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); - - return (locationManager != null && // - (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || // - locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))); - - // return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - } - - - /** - * Prompt the user to enable GPS location if it isn't already on. - * - * @param parent The currently visible activity. - */ - public static void requestLocation(final Activity parent) { - if (LocationHelper.isLocationEnabled(parent)) { - return; - } - - // Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533 - OKDialog.showConfirmation(parent, parent.getString(R.string.location_not_found_title), parent.getString(R.string.location_not_found_message), () -> { - parent.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); - }); - } - - - /** - * Prompt the user to enable GPS location on devices that need it for Bluetooth discovery. - *

- * Android 6 (Marshmallow) needs GPS enabled for Bluetooth discovery to work. - * - * @param activity The currently visible activity. - */ - public static void requestLocationForBluetooth(Activity activity) { - // Location needs to be enabled for Bluetooth discovery on Marshmallow. - LocationHelper.requestLocation(activity); - } - - // public static Boolean locationPermission(ActivityWithMenu act) { - // return ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) == - // PackageManager.PERMISSION_GRANTED; - // } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt deleted file mode 100644 index dd4c59cee4..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt +++ /dev/null @@ -1,102 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class MessageHashTableR @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - constraintChecker: ConstraintChecker, - danaRPump: DanaRPump, - danaRPlugin: DanaRPlugin, - danaRKoreanPlugin: DanaRKoreanPlugin, - configBuilderPlugin: ConfigBuilderPlugin, - commandQueue: CommandQueueProvider, - activePlugin: ActivePluginProvider, - injector: HasAndroidInjector, - dateUtil: DateUtil -) : MessageHashTableBase { - - var messages: HashMap = HashMap() - - init { - put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED - put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS - put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING - put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)) // 0x0207 CMD_PUMP_EXPANS_INS_I - put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I - put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS - // 0x0301 CMD_PUMPINIT_TIME_INFO - put(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) - put(MsgInitConnStatusBolus(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO - put(MsgInitConnStatusBasic(aapsLogger, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO - put(MsgInitConnStatusOption(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0304 CMD_PUMPINIT_OPTION - put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S - put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S - put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP - put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S - put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS - put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT - put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT - put(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS - put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS - put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE - put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM - put(MsgHistoryError(aapsLogger, rxBus, dateUtil)) // 0x3106 CMD_HISTORY_ERROR - put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY - put(MsgHistoryRefill(aapsLogger, rxBus, dateUtil)) // 0x3108 CMD_HISTORY_REFILL - put(MsgHistorySuspend(aapsLogger, rxBus, dateUtil)) // 0x3109 CMD_HISTORY_SUSPEND - put(MsgHistoryBasalHour(aapsLogger, rxBus, dateUtil)) // 0x310A CMD_HISTORY_BASAL_HOUR - put(MsgHistoryDone(aapsLogger, danaRPump)) // 0x31F1 CMD_HISTORY_DONT_USED - // 0x3202 CMD_SETTING_V_BASAL_INS_I - put(MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin)) - // 0x3203 CMD_SETTING_V_MEAL_SETTING_I - put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) - put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I - put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I - put(MsgSettingBasalProfileAll(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL - put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I - put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY - put(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 0x320A CMD_SETTING_V_TIME_I - put(MsgSettingUserOptions(aapsLogger, danaRPump)) // 0x320B CMD_SETTING_V_USER_OPTIONS - put(MsgSettingActiveProfile(aapsLogger, danaRPump)) // 0x320C CMD_SETTING_V_PROFILE_NUMBER - put(MsgSettingProfileRatiosAll(aapsLogger, danaRPump)) // 0x320D CMD_SETTING_V_CIR_CF_VALUE - put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S - put(MsgSetBasalProfile(aapsLogger, rxBus, resourceHelper, 0.toByte(), Array(24) { 0.0 })) // 0x3306 CMD_SETTING_BASAL_PROFILE_S - put(MsgSetUserOptions(aapsLogger, danaRPump)) // 0x330B CMD_SETTING_USER_OPTIONS_S - put(MsgSetActivateBasalProfile(aapsLogger, 0.toByte())) // 0x330C CMD_SETTING_PROFILE_NUMBER_S - put(MsgHistoryAllDone(aapsLogger, danaRPump)) // 0x41F1 CMD_HISTORY_ALL_DONE - put(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL - put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW - // 0xF0F1 CMD_PUMP_CHECK_VALUE - put(MsgCheckValue(aapsLogger, danaRPump, danaRPlugin)) - } - - override fun put(message: MessageBase) { - messages[message.command] = message - } - - override fun findMessage(command: Int): MessageBase { - return messages[command] ?: MessageBase() - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetUserOptions.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetUserOptions.kt deleted file mode 100644 index f2a579fd72..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetUserOptions.kt +++ /dev/null @@ -1,43 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSetUserOptions( - private val aapsLogger: AAPSLogger, - danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x330B) - if (danaRPump.userOptionsFrompump == null) { - // No options set -> Exiting - aapsLogger.debug(LTag.PUMPCOMM, "NO USER OPTIONS LOADED EXITING!") - } else { - danaRPump.userOptionsFrompump!![0] = (if (danaRPump.timeDisplayType == 1) 0 else 1).toByte() - danaRPump.userOptionsFrompump!![1] = danaRPump.buttonScrollOnOff.toByte() - danaRPump.userOptionsFrompump!![2] = danaRPump.beepAndAlarm.toByte() - danaRPump.userOptionsFrompump!![3] = danaRPump.lcdOnTimeSec.toByte() - danaRPump.userOptionsFrompump!![4] = danaRPump.backlightOnTimeSec.toByte() - danaRPump.userOptionsFrompump!![5] = danaRPump.selectedLanguage.toByte() - danaRPump.userOptionsFrompump!![8] = danaRPump.units.toByte() - danaRPump.userOptionsFrompump!![9] = danaRPump.shutdownHour.toByte() - danaRPump.userOptionsFrompump!![27] = danaRPump.lowReservoirRate.toByte() - for (element in danaRPump.userOptionsFrompump!!) { - AddParamByte(element) - } - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - } - - override fun handleMessage(bytes: ByteArray) { - val result = intFromBuff(bytes, 0, 1) - if (result != 1) { - failed = true - aapsLogger.debug(LTag.PUMPCOMM, "Setting user options: $result FAILED!!!") - } else { - aapsLogger.debug(LTag.PUMPCOMM, "Setting user options: $result") - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMaxValues.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMaxValues.kt deleted file mode 100644 index 437af793f8..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMaxValues.kt +++ /dev/null @@ -1,25 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingMaxValues( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x3205) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.maxBolus = intFromBuff(bytes, 0, 2) / 100.0 - danaRPump.maxBasal = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.maxDailyTotalUnits = intFromBuff(bytes, 4, 2) / 100 - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus) - aapsLogger.debug(LTag.PUMPCOMM, "Max basal: " + danaRPump.maxBasal) - aapsLogger.debug(LTag.PUMPCOMM, "Total daily max units: " + danaRPump.maxDailyTotalUnits) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatios.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatios.kt deleted file mode 100644 index 6c29024677..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatios.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingProfileRatios( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x3204) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (danaRPump.units == DanaRPump.UNITS_MGDL) { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2).toDouble() - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2).toDouble() - danaRPump.currentAIDR = intFromBuff(bytes, 8, 1) - } else { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2) / 100.0 - danaRPump.currentAIDR = intFromBuff(bytes, 8, 1) - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump units (saved): " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CIR: " + danaRPump.currentCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CF: " + danaRPump.currentCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AI: " + danaRPump.currentAI) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump target: " + danaRPump.currentTarget) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AIDR: " + danaRPump.currentAIDR) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatiosAll.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatiosAll.kt deleted file mode 100644 index 4f626e89df..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatiosAll.kt +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingProfileRatiosAll( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x320D) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (danaRPump.units == DanaRPump.UNITS_MGDL) { - danaRPump.morningCIR = intFromBuff(bytes, 0, 2) - danaRPump.morningCF = intFromBuff(bytes, 2, 2).toDouble() - danaRPump.afternoonCIR = intFromBuff(bytes, 4, 2) - danaRPump.afternoonCF = intFromBuff(bytes, 6, 2).toDouble() - danaRPump.eveningCIR = intFromBuff(bytes, 8, 2) - danaRPump.eveningCF = intFromBuff(bytes, 10, 2).toDouble() - danaRPump.nightCIR = intFromBuff(bytes, 12, 2) - danaRPump.nightCF = intFromBuff(bytes, 14, 2).toDouble() - } else { - danaRPump.morningCIR = intFromBuff(bytes, 0, 2) - danaRPump.morningCF = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.afternoonCIR = intFromBuff(bytes, 4, 2) - danaRPump.afternoonCF = intFromBuff(bytes, 6, 2) / 100.0 - danaRPump.eveningCIR = intFromBuff(bytes, 8, 2) - danaRPump.eveningCF = intFromBuff(bytes, 10, 2) / 100.0 - danaRPump.nightCIR = intFromBuff(bytes, 12, 2) - danaRPump.nightCF = intFromBuff(bytes, 14, 2) / 100.0 - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CIR: " + danaRPump.morningCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CF: " + danaRPump.morningCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CIR: " + danaRPump.afternoonCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CF: " + danaRPump.afternoonCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CIR: " + danaRPump.eveningCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CF: " + danaRPump.eveningCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CIR: " + danaRPump.nightCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CF: " + danaRPump.nightCF) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingUserOptions.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingUserOptions.kt deleted file mode 100644 index 3678424499..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingUserOptions.kt +++ /dev/null @@ -1,59 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import java.util.* - -class MsgSettingUserOptions( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - - init { - SetCommand(0x320B) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(packet: ByteArray) { - val bytes = getDataBytes(packet, packet.size - 10) - danaRPump.userOptionsFrompump = Arrays.copyOf(bytes, bytes!!.size) // saving pumpDataBytes to use it in MsgSetUserOptions - for (pos in bytes.indices) { - aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos]) - } - danaRPump.timeDisplayType = if (bytes[0] == 1.toByte()) 0 else 1 // 1 -> 24h 0 -> 12h - danaRPump.buttonScrollOnOff = if (bytes[1] == 1.toByte()) 1 else 0 // 1 -> ON, 0-> OFF - danaRPump.beepAndAlarm = bytes[2].toInt() // 1 -> Sound on alarm 2-> Vibrate on alarm 3-> Both on alarm 5-> Sound + beep 6-> vibrate + beep 7-> both + beep Beep adds 4 - danaRPump.lcdOnTimeSec = bytes[3].toInt() and 255 - danaRPump.backlightOnTimeSec = bytes[4].toInt() and 255 - danaRPump.selectedLanguage = bytes[5].toInt() // on DanaRv2 is that needed ? - danaRPump.units = bytes[8].toInt() - danaRPump.shutdownHour = bytes[9].toInt() - danaRPump.lowReservoirRate = bytes[32].toInt() and 255 - /* int selectableLanguage1 = bytes[10]; - int selectableLanguage2 = bytes[11]; - int selectableLanguage3 = bytes[12]; - int selectableLanguage4 = bytes[13]; - int selectableLanguage5 = bytes[14]; - */ - aapsLogger.debug(LTag.PUMPCOMM, "timeDisplayType: " + danaRPump.timeDisplayType) - aapsLogger.debug(LTag.PUMPCOMM, "Button scroll: " + danaRPump.buttonScrollOnOff) - aapsLogger.debug(LTag.PUMPCOMM, "BeepAndAlarm: " + danaRPump.beepAndAlarm) - aapsLogger.debug(LTag.PUMPCOMM, "screen timeout: " + danaRPump.lcdOnTimeSec) - aapsLogger.debug(LTag.PUMPCOMM, "BackLight: " + danaRPump.backlightOnTimeSec) - aapsLogger.debug(LTag.PUMPCOMM, "Selected language: " + danaRPump.selectedLanguage) - aapsLogger.debug(LTag.PUMPCOMM, "Units: " + danaRPump.getUnits()) - aapsLogger.debug(LTag.PUMPCOMM, "Shutdown: " + danaRPump.shutdownHour) - aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaRPump.lowReservoirRate) - } - - private fun getDataBytes(bytes: ByteArray?, len: Int): ByteArray? { - if (bytes == null) { - return null - } - val ret = ByteArray(len) - System.arraycopy(bytes, 6, ret, 0, len) - return ret - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatus.kt deleted file mode 100644 index e37ad1ebb6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatus.kt +++ /dev/null @@ -1,37 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgStatus( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump - -) : MessageBase() { - - init { - SetCommand(0x020B) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.dailyTotalUnits = intFromBuff(bytes, 0, 3) / 750.0 - danaRPump.isExtendedInProgress = intFromBuff(bytes, 3, 1) == 1 - danaRPump.extendedBolusMinutes = intFromBuff(bytes, 4, 2) - danaRPump.extendedBolusAmount = intFromBuff(bytes, 6, 2) / 100.0 - val lastBolusAmount = intFromBuff(bytes, 13, 2) / 100.0 - if (lastBolusAmount != 0.0) { - danaRPump.lastBolusTime = dateTimeFromBuff(bytes, 8) - danaRPump.lastBolusAmount = lastBolusAmount - } - danaRPump.iob = intFromBuff(bytes, 15, 2) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus min: " + danaRPump.extendedBolusMinutes) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus amount: " + danaRPump.extendedBolusAmount) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + danaRPump.lastBolusTime) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) - aapsLogger.debug(LTag.PUMPCOMM, "IOB: " + danaRPump.iob) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusProfile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusProfile.kt deleted file mode 100644 index e8bd43012b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusProfile.kt +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgStatusProfile( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x0204) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (danaRPump.units == DanaRPump.UNITS_MGDL) { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2).toDouble() - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2).toDouble() - } else { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2) / 100.0 - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump units (saved): " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CIR: " + danaRPump.currentCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CF: " + danaRPump.currentCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AI: " + danaRPump.currentAI) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump target: " + danaRPump.currentTarget) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AIDR: " + danaRPump.currentAIDR) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractSerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractSerialIOThread.java deleted file mode 100644 index 6d2cba9741..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractSerialIOThread.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.services; - -import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase; - -/** - * Created by mike on 28.01.2018. - */ - -public abstract class AbstractSerialIOThread extends Thread { - - public abstract void sendMessage(MessageBase message); - public abstract void disconnect(String reason); -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt deleted file mode 100644 index 882ab11739..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt +++ /dev/null @@ -1,85 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRKorean.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.* -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class MessageHashTableRKorean @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - constraintChecker: ConstraintChecker, - danaRPump: DanaRPump, - danaRPlugin: DanaRPlugin, - danaRKoreanPlugin: DanaRKoreanPlugin, - configBuilderPlugin: ConfigBuilderPlugin, - commandQueue: CommandQueueProvider, - activePlugin: ActivePluginProvider, - dateUtil: DateUtil, - injector: HasAndroidInjector -) : MessageHashTableBase { - - var messages: HashMap = HashMap() - - init { - put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS - put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING - put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)) // 0x0207 CMD_PUMP_EXPANS_INS_I - put(MsgStatusBasic_k(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I - put(MsgStatus_k(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS - put(MsgInitConnStatusTime_k(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) // 0x0301 CMD_PUMPINIT_TIME_INFO - put(MsgInitConnStatusBolus_k(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO - put(MsgInitConnStatusBasic_k(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO - put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S - put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S - put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP - put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S - put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS - put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT - put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT - put(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS - put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS - put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE - put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM - put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY - put(MsgSettingBasal_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0x3202 CMD_SETTING_V_BASAL_INS_I - put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) // 0x3203 CMD_SETTING_V_MEAL_SETTING_I - put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I - put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I - put(MsgSettingBasalProfileAll_k(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL - put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I - put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY - put(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 0x320A CMD_SETTING_V_TIME_I - put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S - put(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL - put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW - put(MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0xF0F1 CMD_PUMP_CHECK_VALUE - } - - override fun put(message: MessageBase) { - messages[message.command] = message - } - - override fun findMessage(command: Int): MessageBase { - return messages[command] ?: MessageBase() - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java deleted file mode 100644 index 293faf8621..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ /dev/null @@ -1,836 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.IBinder; - -import androidx.annotation.NonNull; -import androidx.preference.Preference; - -import org.jetbrains.annotations.NotNull; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.events.EventAppExit; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.PumpDescription; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.interfaces.PumpPluginBase; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.interfaces.ProfileFunction; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; -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.pump.common.bolusInfo.DetailedBolusInfoStorage; -import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange; -import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService; -import info.nightscout.androidaps.db.Treatment; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.Round; -import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.TimeChangeType; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - -@Singleton -public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { - private CompositeDisposable disposable = new CompositeDisposable(); - - private final Context context; - private final ResourceHelper resourceHelper; - private final ConstraintChecker constraintChecker; - private final ProfileFunction profileFunction; - private final TreatmentsPlugin treatmentsPlugin; - private final SP sp; - private final RxBusWrapper rxBus; - private final CommandQueueProvider commandQueue; - private final DanaRPump danaRPump; - private final DetailedBolusInfoStorage detailedBolusInfoStorage; - private final DateUtil dateUtil; - - private static DanaRSService danaRSService; - - private static String mDeviceAddress = ""; - public static String mDeviceName = ""; - - public static PumpDescription pumpDescription = new PumpDescription(); - - // Bolus & history handling - public int bolusStartErrorCode; // from start message - public Treatment bolusingTreatment; // actually delivered treatment - public double bolusAmountToBeDelivered = 0.0; // amount to be delivered - public boolean bolusStopped = false; // bolus finished - public boolean bolusStopForced = false; // bolus forced to stop by user - public boolean bolusDone = false; // success end - public long bolusProgressLastTimeStamp = 0; // timestamp of last bolus progress message - public boolean apsHistoryDone = false; // true when last history message is received - public long lastEventTimeLoaded = 0; // timestamp of last received event - - @Inject - public DanaRSPlugin( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - RxBusWrapper rxBus, - Context context, - ResourceHelper resourceHelper, - ConstraintChecker constraintChecker, - ProfileFunction profileFunction, - TreatmentsPlugin treatmentsPlugin, - SP sp, - CommandQueueProvider commandQueue, - DanaRPump danaRPump, - DetailedBolusInfoStorage detailedBolusInfoStorage, - DateUtil dateUtil - ) { - super(new PluginDescription() - .mainType(PluginType.PUMP) - .fragmentClass(DanaRFragment.class.getName()) - .pluginName(R.string.danarspump) - .shortName(R.string.danarspump_shortname) - .preferencesId(R.xml.pref_danars) - .description(R.string.description_pump_dana_rs), - injector, aapsLogger, resourceHelper, commandQueue - ); - this.context = context; - this.rxBus = rxBus; - this.resourceHelper = resourceHelper; - this.constraintChecker = constraintChecker; - this.profileFunction = profileFunction; - this.treatmentsPlugin = treatmentsPlugin; - this.sp = sp; - this.commandQueue = commandQueue; - this.danaRPump = danaRPump; - this.detailedBolusInfoStorage = detailedBolusInfoStorage; - this.dateUtil = dateUtil; - - pumpDescription.setPumpDescription(PumpType.DanaRS); - } - - @Override - public void updatePreferenceSummary(@NotNull Preference pref) { - super.updatePreferenceSummary(pref); - - if (pref.getKey().equals(resourceHelper.gs(R.string.key_danars_name))) - pref.setSummary(sp.getString(R.string.key_danars_name, "")); - } - - @Override - protected void onStart() { - Intent intent = new Intent(context, DanaRSService.class); - context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - - disposable.add(rxBus - .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) - .subscribe(event -> context.unbindService(mConnection), exception -> FabricPrivacy.getInstance().logException(exception)) - ); - disposable.add(rxBus - .toObservable(EventDanaRSDeviceChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> loadAddress(), exception -> FabricPrivacy.getInstance().logException(exception)) - ); - loadAddress(); // load device name - super.onStart(); - } - - @Override - protected void onStop() { - context.unbindService(mConnection); - - disposable.clear(); - super.onStop(); - } - - private ServiceConnection mConnection = new ServiceConnection() { - - public void onServiceDisconnected(ComponentName name) { - getAapsLogger().debug(LTag.PUMP, "Service is disconnected"); - danaRSService = null; - } - - public void onServiceConnected(ComponentName name, IBinder service) { - getAapsLogger().debug(LTag.PUMP, "Service is connected"); - DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder) service; - danaRSService = mLocalBinder.getServiceInstance(); - } - }; - - private void loadAddress() { - mDeviceAddress = sp.getString(R.string.key_danars_address, ""); - mDeviceName = sp.getString(R.string.key_danars_name, ""); - } - - @Override - public void connect(String from) { - getAapsLogger().debug(LTag.PUMP, "RS connect from: " + from); - if (danaRSService != null && !mDeviceAddress.equals("") && !mDeviceName.equals("")) { - final Object o = new Object(); - - danaRSService.connect(from, mDeviceAddress, o); - } - } - - @Override - public boolean isConnected() { - return danaRSService != null && danaRSService.isConnected(); - } - - @Override - public boolean isConnecting() { - return danaRSService != null && danaRSService.isConnecting(); - } - - @Override - public boolean isHandshakeInProgress() { - return false; - } - - @Override - public void finishHandshaking() { - } - - @Override - public void disconnect(String from) { - getAapsLogger().debug(LTag.PUMP, "RS disconnect from: " + from); - if (danaRSService != null) danaRSService.disconnect(from); - } - - @Override - public void stopConnecting() { - if (danaRSService != null) danaRSService.stopConnecting(); - } - - @Override - public void getPumpStatus() { - if (danaRSService != null) { - danaRSService.getPumpStatus(); - pumpDescription.basalStep = danaRPump.getBasalStep(); - pumpDescription.bolusStep = danaRPump.getBolusStep(); - } - } - - // DanaR interface - - @Override - public PumpEnactResult loadHistory(byte type) { - return danaRSService.loadHistory(type); - } - - @Override - public PumpEnactResult loadEvents() { - return danaRSService.loadEvents(); - } - - @Override - public PumpEnactResult setUserOptions() { - return danaRSService.setUserSettings(); - } - - // Constraints interface - - @NonNull - @Override - public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), resourceHelper.gs(R.string.limitingbasalratio, danaRPump.getMaxBasal(), resourceHelper.gs(R.string.pumplimit)), this); - return absoluteRate; - } - - @NonNull - @Override - public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(getAapsLogger(), 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); - - return percentRate; - } - - - @NonNull - @Override - public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), resourceHelper.gs(R.string.limitingbolus, danaRPump.getMaxBolus(), resourceHelper.gs(R.string.pumplimit)), this); - return insulin; - } - - @NonNull - @Override - public Constraint applyExtendedBolusConstraints(@NonNull Constraint insulin) { - return applyBolusConstraints(insulin); - } - - // Pump interface - - @Override - public boolean isInitialized() { - return danaRPump.getLastConnection() > 0 && danaRPump.getMaxBasal() > 0; - } - - @Override - public boolean isSuspended() { - return danaRPump.getPumpSuspended(); - } - - @Override - public boolean isBusy() { - if (danaRSService == null) return false; - return danaRSService.isConnected() || danaRSService.isConnecting(); - } - - @NonNull @Override - public PumpEnactResult setNewBasalProfile(Profile profile) { - PumpEnactResult result = new PumpEnactResult(getInjector()); - - if (danaRSService == null) { - getAapsLogger().error("setNewBasalProfile sExecutionService is null"); - result.comment = "setNewBasalProfile sExecutionService is null"; - return result; - } - if (!isInitialized()) { - getAapsLogger().error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); - rxBus.send(new EventNewNotification(notification)); - result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet); - return result; - } else { - rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); - } - if (!danaRSService.updateBasalsInPump(profile)) { - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); - rxBus.send(new EventNewNotification(notification)); - result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile); - return result; - } else { - rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); - rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60); - rxBus.send(new EventNewNotification(notification)); - result.success = true; - result.enacted = true; - result.comment = "OK"; - return result; - } - } - - @Override - public boolean isThisProfileSet(Profile profile) { - if (!isInitialized()) - return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS - if (danaRPump.getPumpProfiles() == null) - return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS - int basalValues = danaRPump.getBasal48Enable() ? 48 : 24; - int basalIncrement = danaRPump.getBasal48Enable() ? 30 * 60 : 60 * 60; - for (int h = 0; h < basalValues; h++) { - Double pumpValue = danaRPump.getPumpProfiles()[danaRPump.getActiveProfile()][h]; - Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement); - if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { - getAapsLogger().debug(LTag.PUMP, "Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); - return false; - } - } - return true; - } - - @Override - public long lastDataTime() { - return danaRPump.getLastConnection(); - } - - @Override - public double getBaseBasalRate() { - return danaRPump.getCurrentBasal(); - } - - @Override - public double getReservoirLevel() { - return danaRPump.getReservoirRemainingUnits(); - } - - @Override - public int getBatteryLevel() { - return danaRPump.getBatteryRemaining(); - } - - @NonNull @Override - public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); - if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { - int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0); - int speed = 12; - switch (preferencesSpeed) { - case 0: - speed = 12; - break; - case 1: - speed = 30; - break; - case 2: - speed = 60; - break; - } - // RS stores end time for bolus, we need to adjust time - // default delivery speed is 12 sec/U - detailedBolusInfo.date = DateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000); - // clean carbs to prevent counting them as twice because they will picked up as another record - // I don't think it's necessary to copy DetailedBolusInfo right now for carbs records - double carbs = detailedBolusInfo.carbs; - detailedBolusInfo.carbs = 0; - int carbTime = detailedBolusInfo.carbTime; - if (carbTime == 0) carbTime--; // better set 1 min back to prevents clash with insulin - detailedBolusInfo.carbTime = 0; - - detailedBolusInfoStorage.add(detailedBolusInfo); // will be picked up on reading history - - Treatment t = new Treatment(); - t.isSMB = detailedBolusInfo.isSMB; - boolean connectionOK = false; - if (detailedBolusInfo.insulin > 0 || carbs > 0) - connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); - PumpEnactResult result = new PumpEnactResult(getInjector()); - result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; - result.bolusDelivered = t.insulin; - result.carbsDelivered = detailedBolusInfo.carbs; - if (!result.success) { - String error = "" + bolusStartErrorCode; - switch (bolusStartErrorCode) { - // 4 reported as max bolus violation. Check later - case 0x10: - error = resourceHelper.gs(R.string.maxbolusviolation); - break; - case 0x20: - error = resourceHelper.gs(R.string.commanderror); - break; - case 0x40: - error = resourceHelper.gs(R.string.speederror); - break; - case 0x80: - error = resourceHelper.gs(R.string.insulinlimitviolation); - break; - } - result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, error); - } else - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - getAapsLogger().debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); - return result; - } else { - PumpEnactResult result = new PumpEnactResult(getInjector()); - result.success = false; - result.bolusDelivered = 0d; - result.carbsDelivered = 0d; - result.comment = resourceHelper.gs(R.string.danar_invalidinput); - getAapsLogger().error("deliverTreatment: Invalid input"); - return result; - } - } - - @Override - public void stopBolusDelivering() { - if (danaRSService == null) { - getAapsLogger().error("stopBolusDelivering sExecutionService is null"); - return; - } - danaRSService.bolusStop(); - } - - // This is called from APS - @NonNull @Override - public synchronized PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { - // Recheck pump status if older than 30 min - - //This should not be needed while using queue because connection should be done before calling this - //if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) { - // connect("setTempBasalAbsolute old data"); - //} - - PumpEnactResult result = new PumpEnactResult(getInjector()); - - absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); - - final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; - final boolean doLowTemp = absoluteRate < getBaseBasalRate(); - final boolean doHighTemp = absoluteRate > getBaseBasalRate(); - - if (doTempOff) { - // If temp in progress - if (treatmentsPlugin.isTempBasalInProgress()) { - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doTempOff)"); - return cancelTempBasal(false); - } - result.success = true; - result.enacted = false; - result.percent = 100; - result.isPercent = true; - result.isTempCancel = true; - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: doTempOff OK"); - return result; - } - - if (doLowTemp || doHighTemp) { - Integer percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); - if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); - else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); - if (percentRate > 500) // Special high temp 500/15min - percentRate = 500; - // Check if some temp is already in progress - TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: currently running: " + activeTemp.toString()); - // Correct basal already set ? - if (activeTemp.percentRate == percentRate && activeTemp.getPlannedRemainingMinutes() > 4) { - if (!enforceNew) { - result.success = true; - result.percent = percentRate; - result.enacted = false; - result.duration = activeTemp.getPlannedRemainingMinutes(); - result.isPercent = true; - result.isTempCancel = false; - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); - return result; - } - } - } - // Convert duration from minutes to hours - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); - if (percentRate == 0 && durationInMinutes > 30) { - result = setTempBasalPercent(percentRate, durationInMinutes, profile, enforceNew); - } else { - // use special APS temp basal call ... 100+/15min .... 100-/30min - result = setHighTempBasalPercent(percentRate); - } - if (!result.success) { - getAapsLogger().error("setTempBasalAbsolute: Failed to set hightemp basal"); - return result; - } - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: hightemp basal set ok"); - return result; - } - // We should never end here - getAapsLogger().error("setTempBasalAbsolute: Internal error"); - result.success = false; - result.comment = "Internal error"; - return result; - } - - @NonNull @Override - public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { - DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(getInjector()); - percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); - if (percent < 0) { - result.isTempCancel = false; - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_invalidinput); - getAapsLogger().error("setTempBasalPercent: Invalid input"); - return result; - } - if (percent > getPumpDescription().maxTempPercent) - percent = getPumpDescription().maxTempPercent; - long now = System.currentTimeMillis(); - TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now); - if (activeTemp != null && activeTemp.percentRate == percent && activeTemp.getPlannedRemainingMinutes() > 4 && !enforceNew) { - result.enacted = false; - result.success = true; - result.isTempCancel = false; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.duration = pump.getTempBasalRemainingMin(); - result.percent = pump.getTempBasalPercent(); - result.isPercent = true; - getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: Correct value already set"); - return result; - } - boolean connectionOK; - if (durationInMinutes == 15 || durationInMinutes == 30) { - connectionOK = danaRSService.tempBasalShortDuration(percent, durationInMinutes); - } else { - int durationInHours = Math.max(durationInMinutes / 60, 1); - connectionOK = danaRSService.tempBasal(percent, durationInHours); - } - if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { - result.enacted = true; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.isTempCancel = false; - result.duration = pump.getTempBasalRemainingMin(); - result.percent = pump.getTempBasalPercent(); - result.isPercent = true; - getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: OK"); - return result; - } - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.tempbasaldeliveryerror); - getAapsLogger().error("setTempBasalPercent: Failed to set temp basal"); - return result; - } - - private synchronized PumpEnactResult setHighTempBasalPercent(Integer percent) { - DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(getInjector()); - boolean connectionOK = danaRSService.highTempBasal(percent); - if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { - result.enacted = true; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.isTempCancel = false; - result.duration = pump.getTempBasalRemainingMin(); - result.percent = pump.getTempBasalPercent(); - result.isPercent = true; - getAapsLogger().debug(LTag.PUMP, "setHighTempBasalPercent: OK"); - return result; - } - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - getAapsLogger().error("setHighTempBasalPercent: Failed to set temp basal"); - return result; - } - - @NonNull @Override - public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { - DanaRPump pump = danaRPump; - insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); - // needs to be rounded - int durationInHalfHours = Math.max(durationInMinutes / 30, 1); - insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); - PumpEnactResult result = new PumpEnactResult(getInjector()); - ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); - if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { - result.enacted = false; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.duration = pump.getExtendedBolusRemainingMinutes(); - result.absolute = pump.getExtendedBolusAbsoluteRate(); - result.isPercent = false; - result.isTempCancel = false; - getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: Correct extended bolus already set. Current: " + pump.getExtendedBolusAmount() + " Asked: " + insulin); - return result; - } - boolean connectionOK = danaRSService.extendedBolus(insulin, durationInHalfHours); - if (connectionOK && pump.isExtendedInProgress() && Math.abs(pump.getExtendedBolusAbsoluteRate() - insulin) < getPumpDescription().extendedBolusStep) { - result.enacted = true; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.isTempCancel = false; - result.duration = pump.getExtendedBolusRemainingMinutes(); - result.absolute = pump.getExtendedBolusAbsoluteRate(); - result.bolusDelivered = pump.getExtendedBolusAmount(); - result.isPercent = false; - getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: OK"); - return result; - } - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - getAapsLogger().error("setExtendedBolus: Failed to extended bolus"); - return result; - } - - @NonNull @Override - public synchronized PumpEnactResult cancelTempBasal(boolean force) { - PumpEnactResult result = new PumpEnactResult(getInjector()); - TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); - if (runningTB != null) { - danaRSService.tempBasalStop(); - result.enacted = true; - result.isTempCancel = true; - } - if (!danaRPump.isTempBasalInProgress()) { - result.success = true; - result.isTempCancel = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - getAapsLogger().debug(LTag.PUMP, "cancelRealTempBasal: OK"); - return result; - } else { - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - result.isTempCancel = true; - getAapsLogger().error("cancelRealTempBasal: Failed to cancel temp basal"); - return result; - } - } - - @NonNull @Override - public synchronized PumpEnactResult cancelExtendedBolus() { - PumpEnactResult result = new PumpEnactResult(getInjector()); - ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); - if (runningEB != null) { - danaRSService.extendedBolusStop(); - result.enacted = true; - result.isTempCancel = true; - } - if (!danaRPump.isExtendedInProgress()) { - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - getAapsLogger().debug(LTag.PUMP, "cancelExtendedBolus: OK"); - return result; - } else { - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - getAapsLogger().error("cancelExtendedBolus: Failed to cancel extended bolus"); - return result; - } - } - - @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { - DanaRPump pump = danaRPump; - long now = System.currentTimeMillis(); - if (pump.getLastConnection() + 5 * 60 * 1000L < System.currentTimeMillis()) { - return new JSONObject(); - } - JSONObject pumpjson = new JSONObject(); - JSONObject battery = new JSONObject(); - JSONObject status = new JSONObject(); - JSONObject extended = new JSONObject(); - try { - battery.put("percent", pump.getBatteryRemaining()); - status.put("status", pump.getPumpSuspended() ? "suspended" : "normal"); - status.put("timestamp", DateUtil.toISOString(pump.getLastConnection())); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); - if (pump.getLastBolusTime() != 0) { - extended.put("LastBolus", dateUtil.dateAndTimeString(pump.getLastBolusTime())); - extended.put("LastBolusAmount", pump.getLastBolusAmount()); - } - TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now); - if (tb != null) { - extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)); - extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date)); - extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); - } - ExtendedBolus eb = treatmentsPlugin.getExtendedBolusFromHistory(now); - if (eb != null) { - extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()); - extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date)); - extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes()); - } - extended.put("BaseBasalRate", getBaseBasalRate()); - try { - extended.put("ActiveProfile", profileFunction.getProfileName()); - } catch (Exception e) { - getAapsLogger().error("Unhandled exception", e); - } - - pumpjson.put("battery", battery); - pumpjson.put("status", status); - pumpjson.put("extended", extended); - pumpjson.put("reservoir", (int) pump.getReservoirRemainingUnits()); - pumpjson.put("clock", DateUtil.toISOString(now)); - } catch (JSONException e) { - getAapsLogger().error("Unhandled exception", e); - } - return pumpjson; - } - - @NonNull @Override - public ManufacturerType manufacturer() { - return ManufacturerType.Sooil; - } - - @NonNull @Override - public PumpType model() { - return PumpType.DanaRS; - } - - @NonNull @Override - public String serialNumber() { - return danaRPump.getSerialNumber(); - } - - @NonNull @Override - public PumpDescription getPumpDescription() { - return pumpDescription; - } - - @NonNull @Override - public String shortStatus(boolean veryShort) { - DanaRPump pump = danaRPump; - String ret = ""; - if (pump.getLastConnection() != 0) { - long agoMsec = System.currentTimeMillis() - pump.getLastConnection(); - int agoMin = (int) (agoMsec / 60d / 1000d); - ret += "LastConn: " + agoMin + " minago\n"; - } - if (pump.getLastBolusTime() != 0) { - ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.getLastBolusTime()) + "\n"; - } - TemporaryBasal activeTemp = treatmentsPlugin.getRealTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - ret += "Temp: " + activeTemp.toStringFull() + "\n"; - } - ExtendedBolus activeExtendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); - if (activeExtendedBolus != null) { - ret += "Extended: " + activeExtendedBolus.toString() + "\n"; - } - if (!veryShort) { - ret += "TDD: " + DecimalFormatter.to0Decimal(pump.getDailyTotalUnits()) + " / " + pump.getMaxDailyTotalUnits() + " U\n"; - } - ret += "Reserv: " + DecimalFormatter.to0Decimal(pump.getReservoirRemainingUnits()) + "U\n"; - ret += "Batt: " + pump.getBatteryRemaining() + "\n"; - return ret; - } - - @Override - public boolean isFakingTempsByExtendedBoluses() { - return false; - } - - @NonNull @Override - public PumpEnactResult loadTDDs() { - return loadHistory(RecordTypes.RECORD_TYPE_DAILY); - } - - @Override - public List getCustomActions() { - return null; - } - - @Override - public void executeCustomAction(CustomActionType customActionType) { - - } - - @Override - public boolean canHandleDST() { - return false; - } - - @Override - public void timezoneOrDSTChanged(TimeChangeType changeType) { - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java deleted file mode 100644 index 89f794259e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java +++ /dev/null @@ -1,217 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.activities; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.le.BluetoothLeScanner; -import android.bluetooth.le.ScanCallback; -import android.bluetooth.le.ScanResult; -import android.content.pm.ActivityInfo; -import android.os.Bundle; -import android.os.Handler; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.ListView; -import android.widget.TextView; - -import java.util.ArrayList; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange; -import info.nightscout.androidaps.utils.SP; - -public class BLEScanActivity extends NoSplashAppCompatActivity { - private ListAdapter mListAdapter = null; - private ArrayList mDevices = new ArrayList<>(); - - private BluetoothLeScanner mBluetoothLeScanner = null; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.danars_blescanner_activity); - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - - mListAdapter = new ListAdapter(); - - ListView listView = findViewById(R.id.danars_blescanner_listview); - listView.setEmptyView(findViewById(R.id.danars_blescanner_nodevice)); - listView.setAdapter(mListAdapter); - - mListAdapter.notifyDataSetChanged(); - } - - @Override - protected void onResume() { - super.onResume(); - - BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (mBluetoothAdapter != null) { - if (!mBluetoothAdapter.isEnabled()) mBluetoothAdapter.enable(); - mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); - - if (mBluetoothLeScanner == null) { - mBluetoothAdapter.enable(); - mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); - } - startScan(); - } - } - - @Override - protected void onPause() { - super.onPause(); - - stopScan(); - } - - private void startScan() { - if (mBluetoothLeScanner != null) - mBluetoothLeScanner.startScan(mBleScanCallback); - } - - private void stopScan() { - if (mBluetoothLeScanner != null) - mBluetoothLeScanner.stopScan(mBleScanCallback); - } - - private void addBleDevice(BluetoothDevice device) { - if (device == null || device.getName() == null || device.getName().equals("")) { - return; - } - BluetoothDeviceItem item = new BluetoothDeviceItem(device); - if (!isSNCheck(device.getName()) || mDevices.contains(item)) { - return; - } - - mDevices.add(item); - new Handler().post(() -> mListAdapter.notifyDataSetChanged()); - } - - private ScanCallback mBleScanCallback = new ScanCallback() { - @Override - public void onScanResult(int callbackType, ScanResult result) { - addBleDevice(result.getDevice()); - } - }; - - class ListAdapter extends BaseAdapter { - - @Override - public int getCount() { - return mDevices.size(); - } - - @Override - public BluetoothDeviceItem getItem(int i) { - return mDevices.get(i); - } - - @Override - public long getItemId(int i) { - return 0; - } - - @Override - public View getView(int i, View convertView, ViewGroup parent) { - View v = convertView; - ViewHolder holder; - - if (v == null) { - v = View.inflate(getApplicationContext(), R.layout.danars_blescanner_item, null); - holder = new ViewHolder(v); - v.setTag(holder); - } else { - holder = (ViewHolder) v.getTag(); - } - - BluetoothDeviceItem item = getItem(i); - holder.setData(item); - return v; - } - - private class ViewHolder implements View.OnClickListener { - private BluetoothDeviceItem item = null; - - private TextView mName; - private TextView mAddress; - - ViewHolder(View v) { - mName = v.findViewById(R.id.ble_name); - mAddress = v.findViewById(R.id.ble_address); - - v.setOnClickListener(ViewHolder.this); - } - - @Override - public void onClick(View v) { - SP.putString(R.string.key_danars_address, item.device.getAddress()); - SP.putString(R.string.key_danars_name, mName.getText().toString()); - item.device.createBond(); - RxBus.Companion.getINSTANCE().send(new EventDanaRSDeviceChange()); - finish(); - } - - public void setData(BluetoothDeviceItem data) { - if (data != null) { - try { - String tTitle = data.device.getName(); - if (tTitle == null || tTitle.equals("")) { - tTitle = "(unknown)"; - } else if (tTitle.length() > 10) { - tTitle = tTitle.substring(0, 10); - } - mName.setText(tTitle); - - mAddress.setText(data.device.getAddress()); - - item = data; - } catch (Exception ignored) { - } - } - } - } - } - - // - private class BluetoothDeviceItem { - private BluetoothDevice device; - - BluetoothDeviceItem(BluetoothDevice device) { - super(); - this.device = device; - } - - @Override - public boolean equals(Object o) { - if (device == null || !(o instanceof BluetoothDeviceItem)) { - return false; - } - BluetoothDeviceItem checkItem = (BluetoothDeviceItem) o; - if (checkItem.device == null) { - return false; - } - return stringEquals(device.getAddress(), checkItem.device.getAddress()); - } - - boolean stringEquals(String arg1, String arg2) { - try { - return arg1.equals(arg2); - } catch (Exception e) { - return false; - } - } - } - - public static boolean isSNCheck(String sn) { - String regex = "^([a-zA-Z]{3})([0-9]{5})([a-zA-Z]{2})$"; - Pattern p = Pattern.compile(regex); - Matcher m = p.matcher(sn); - - return m.matches(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingHelperActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingHelperActivity.kt deleted file mode 100644 index ba73e1b368..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingHelperActivity.kt +++ /dev/null @@ -1,16 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.activities - -import android.content.pm.ActivityInfo -import android.os.Bundle -import info.nightscout.androidaps.activities.NoSplashAppCompatActivity -import info.nightscout.androidaps.plugins.pump.danaRS.dialogs.PairingProgressDialog - -class PairingHelperActivity : NoSplashAppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - PairingProgressDialog() - .setHelperActivity(this) - .show(supportFragmentManager, "PairingProgress") - requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTable.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTable.kt deleted file mode 100644 index 0a4c81314d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTable.kt +++ /dev/null @@ -1,109 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class DanaRSMessageHashTable @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - danaRPump: DanaRPump, - danaRSPlugin: DanaRSPlugin, - activePlugin: ActivePluginProvider, - constraintChecker: ConstraintChecker, - detailedBolusInfoStorage: DetailedBolusInfoStorage, - injector: HasAndroidInjector, - dateUtil: DateUtil -) { - - var messages: HashMap = HashMap() - - fun put(message: DanaRS_Packet) { - messages[message.command] = message - } - - fun findMessage(command: Int): DanaRS_Packet { - return messages[command] ?: DanaRS_Packet() - } - - init { - put(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)) - put(DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)) - put(DanaRS_Packet_Basal_Get_Profile_Basal_Rate(aapsLogger, danaRPump)) - put(DanaRS_Packet_Basal_Get_Profile_Number(aapsLogger, danaRPump)) - put(DanaRS_Packet_Basal_Set_Basal_Rate(aapsLogger, arrayOf())) - put(DanaRS_Packet_Basal_Set_Profile_Basal_Rate(aapsLogger, 0, arrayOf())) - put(DanaRS_Packet_Basal_Set_Profile_Number(aapsLogger)) - put(DanaRS_Packet_Basal_Set_Suspend_Off(aapsLogger)) - put(DanaRS_Packet_Basal_Set_Suspend_On(aapsLogger)) - put(DanaRS_Packet_Basal_Set_Temporary_Basal(aapsLogger)) - put(DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)) - put(DanaRS_Packet_Bolus_Get_Bolus_Option(aapsLogger, rxBus, resourceHelper, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Initial_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Get_Calculation_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_CIR_CF_Array(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Dual_Bolus(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Extended_Bolus(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)) - put(DanaRS_Packet_Bolus_Set_Bolus_Option(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Initial_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_CIR_CF_Array(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Dual_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Extended_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Step_Bolus_Start(aapsLogger, danaRSPlugin, constraintChecker)) - put(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin)) - put(DanaRS_Packet_Etc_Keep_Connection(aapsLogger)) - put(DanaRS_Packet_Etc_Set_History_Save(aapsLogger)) - put(DanaRS_Packet_General_Delivery_Status(aapsLogger)) - put(DanaRS_Packet_General_Get_Password(aapsLogger, danaRPump)) - put(DanaRS_Packet_General_Initial_Screen_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Notify_Alarm(aapsLogger, resourceHelper)) - put(DanaRS_Packet_Notify_Delivery_Complete(aapsLogger, rxBus, resourceHelper, danaRSPlugin)) - put(DanaRS_Packet_Notify_Delivery_Rate_Display(aapsLogger, rxBus, resourceHelper, danaRSPlugin)) - put(DanaRS_Packet_Notify_Missed_Bolus_Alarm(aapsLogger)) - put(DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil)) - put(DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)) - put(DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil)) - put(DanaRS_Packet_Option_Set_User_Option(aapsLogger, danaRPump)) - //put(new DanaRS_Packet_History_()); - put(DanaRS_Packet_History_Alarm(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_All_History(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_Basal(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_Bolus(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_Review_Bolus_Avg(aapsLogger)) - put(DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_Daily(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_General_Get_More_Information(aapsLogger, danaRPump, dateUtil)) - put(DanaRS_Packet_General_Get_Pump_Check(aapsLogger, danaRPump, rxBus, resourceHelper)) - put(DanaRS_Packet_General_Get_Shipping_Information(aapsLogger, danaRPump, dateUtil)) - put(DanaRS_Packet_General_Get_Today_Delivery_Total(aapsLogger, danaRPump)) - put(DanaRS_Packet_General_Get_User_Time_Change_Flag(aapsLogger)) - put(DanaRS_Packet_History_Prime(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_Refill(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger)) - put(DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(aapsLogger)) - put(DanaRS_Packet_History_Suspend(aapsLogger, rxBus, dateUtil)) - put(DanaRS_Packet_History_Temporary(aapsLogger, rxBus, dateUtil)) - // APS - put(DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 0)) - put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, 0)) - put(DanaRS_Packet_APS_Set_Event_History(aapsLogger, dateUtil, 0, 0, 0, 0)) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt deleted file mode 100644 index c37242b740..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt +++ /dev/null @@ -1,27 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Basal_Get_Profile_Number( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER - aapsLogger.debug(LTag.PUMPCOMM, "Requesting active profile") - } - - override fun handleMessage(data: ByteArray) { - danaRPump.activeProfile = byteArrayToInt(getBytes(data, DATA_START, 1)) - aapsLogger.debug(LTag.PUMPCOMM, "Active profile: " + danaRPump.activeProfile) - } - - override fun getFriendlyName(): String { - return "BASAL__GET_PROFILE_NUMBER" - } - -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt deleted file mode 100644 index 2fbe624322..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Bolus_Get_Dual_Bolus( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - val error = byteArrayToInt(getBytes(data, DATA_START, 1)) - danaRPump.bolusStep = byteArrayToInt(getBytes(data, DATA_START + 1, 2)) / 100.0 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, DATA_START + 3, 2)) / 100.0 - danaRPump.maxBolus = byteArrayToInt(getBytes(data, DATA_START + 5, 2)) / 100.0 - val bolusIncrement = byteArrayToInt(getBytes(data, DATA_START + 7, 1)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: ${danaRPump.bolusStep} U") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: ${danaRPump.extendedBolusAbsoluteRate} U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "bolusIncrement: $bolusIncrement U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_DUAL_BOLUS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt deleted file mode 100644 index 3cd50febdb..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Bolus_Get_Extended_Bolus( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + danaRPump.extendedBolusAbsoluteRate + " U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaRPump.bolusStep + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_BOLUS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt deleted file mode 100644 index c48b08150b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt +++ /dev/null @@ -1,49 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Bolus_Get_Extended_Bolus_State( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - danaRPump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01 - dataIndex += dataSize - dataSize = 1 - danaRPump.extendedBolusMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) * 30 - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusSoFarInMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusDeliveredSoFar = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + danaRPump.extendedBolusAbsoluteRate + " U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus duration: " + danaRPump.extendedBolusMinutes + " min") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far: " + danaRPump.extendedBolusSoFarInMinutes + " min") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus delivered so far: " + danaRPump.extendedBolusDeliveredSoFar + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_BOLUS_STATE" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt deleted file mode 100644 index a78bf0c525..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt +++ /dev/null @@ -1,61 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_Bolus_Get_Step_Bolus_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val dateUtil: DateUtil -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val bolusType = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.initialBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - val lbt = Date() // it doesn't provide day only hour+min, workaround: expecting today - dataIndex += dataSize - dataSize = 1 - lbt.hours = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - lbt.minutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - danaRPump.lastBolusTime = lbt.time - dataIndex += dataSize - dataSize = 2 - danaRPump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "BolusType: $bolusType") - aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount: " + danaRPump.initialBolusAmount + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + dateUtil.dateAndTimeString(danaRPump.lastBolusTime)) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaRPump.bolusStep + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_STEP_BOLUS_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_More_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_More_Information.kt deleted file mode 100644 index a9b1b2df62..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_More_Information.kt +++ /dev/null @@ -1,63 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_General_Get_More_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val dateUtil: DateUtil -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 15) { - failed = true - return - } - var dataIndex = DATA_START - var dataSize = 2 - danaRPump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01 - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusRemainingMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - //val remainRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - val lastBolusTime = Date() // it doesn't provide day only hour+min, workaround: expecting today - dataIndex += dataSize - dataSize = 1 - lastBolusTime.hours = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - lastBolusTime.minutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() - // On DanaRS DailyUnits can't be more than 160 - if (danaRPump.dailyTotalUnits > 160) failed = true - aapsLogger.debug(LTag.PUMPCOMM, "Daily total units: " + danaRPump.dailyTotalUnits.toString() + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Is extended in progress: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus remaining minutes: " + danaRPump.extendedBolusRemainingMinutes) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + dateUtil.dateAndTimeAndSecondsString(lastBolusTime.time)) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_MORE_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.kt deleted file mode 100644 index 6a60ea523a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.kt +++ /dev/null @@ -1,42 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_General_Get_Shipping_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val dateUtil: DateUtil -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 18) { - failed = true - return - } else failed = false - var dataIndex = DATA_START - var dataSize = 10 - danaRPump.serialNumber = stringFromBuff(data, dataIndex, dataSize) - dataIndex += dataSize - dataSize = 3 - danaRPump.shippingDate = dateFromBuff(data, dataIndex) - dataIndex += dataSize - dataSize = 3 - danaRPump.shippingCountry = asciiStringFromBuff(data, dataIndex, dataSize) - aapsLogger.debug(LTag.PUMPCOMM, "Serial number: " + danaRPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "Shipping date: " + dateUtil.dateAndTimeString(danaRPump.shippingDate)) - aapsLogger.debug(LTag.PUMPCOMM, "Shipping country: " + danaRPump.shippingCountry) - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_SHIPPING_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt deleted file mode 100644 index 31310e3d08..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_General_Get_Today_Delivery_Total( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 8) { - failed = true - return - } else failed = false - var dataIndex = DATA_START - var dataSize = 2 - danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Daily total bolus: " + danaRPump.dailyTotalBolusUnits + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Daily total basal: " + danaRPump.dailyTotalBasalUnits + " U") - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_TODAY_DELIVERY_TOTAL" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.kt deleted file mode 100644 index fab00aca3d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.kt +++ /dev/null @@ -1,71 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_General_Initial_Screen_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - type = BleCommandUtil.DANAR_PACKET__TYPE_RESPONSE - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 17) { - failed = true - return - } else failed = false - var dataIndex = DATA_START - var dataSize = 1 - val status = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - danaRPump.pumpSuspended = status and 0x01 == 0x01 - danaRPump.isTempBasalInProgress = status and 0x10 == 0x10 - danaRPump.isExtendedInProgress = status and 0x04 == 0x04 - danaRPump.isDualBolusInProgress = status and 0x08 == 0x08 - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.maxDailyTotalUnits = (byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0).toInt() - dataIndex += dataSize - dataSize = 2 - danaRPump.reservoirRemainingUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.currentBasal = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.tempBasalPercent = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - danaRPump.batteryRemaining = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Pump suspended: " + danaRPump.pumpSuspended) - aapsLogger.debug(LTag.PUMPCOMM, "Temp basal in progress: " + danaRPump.isTempBasalInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended in progress: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Dual in progress: " + danaRPump.isDualBolusInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Daily units: " + danaRPump.dailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Max daily units: " + danaRPump.maxDailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Reservoir remaining units: " + danaRPump.reservoirRemainingUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Battery: " + danaRPump.batteryRemaining) - aapsLogger.debug(LTag.PUMPCOMM, "Current basal: " + danaRPump.currentBasal) - aapsLogger.debug(LTag.PUMPCOMM, "Temp basal percent: " + danaRPump.tempBasalPercent) - aapsLogger.debug(LTag.PUMPCOMM, "Extended absolute rate: " + danaRPump.extendedBolusAbsoluteRate) - } - - override fun getFriendlyName(): String { - return "REVIEW__INITIAL_SCREEN_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Alarm.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Alarm.kt deleted file mode 100644 index 360499cc21..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Alarm.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Alarm @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__ALARM" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_All_History.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_All_History.kt deleted file mode 100644 index 8f6343604b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_All_History.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_All_History( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__ALL_HISTORY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Basal.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Basal.kt deleted file mode 100644 index e3268bcf1d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Basal.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Basal @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__BASAL" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Blood_Glucose.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Blood_Glucose.kt deleted file mode 100644 index 7235137871..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Blood_Glucose.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Blood_Glucose @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__BLOOD_GLUCOSE" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Bolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Bolus.kt deleted file mode 100644 index 1d7950e8b3..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Bolus.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Bolus @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__BOLUS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Carbohydrate.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Carbohydrate.kt deleted file mode 100644 index 03b84489cb..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Carbohydrate.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Carbohydrate @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__CARBOHYDRATE" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Daily.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Daily.kt deleted file mode 100644 index 74f3894e79..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Daily.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Daily @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__DAILY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Prime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Prime.kt deleted file mode 100644 index 9d283e905c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Prime.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Prime @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__PRIME" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Refill.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Refill.kt deleted file mode 100644 index 637fb1be0d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Refill.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Refill @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__REFILL" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Suspend.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Suspend.kt deleted file mode 100644 index 3d35ec35dc..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Suspend.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Suspend @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__SUSPEND" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Temporary.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Temporary.kt deleted file mode 100644 index 31258ea1b0..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Temporary.kt +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_History_Temporary( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - dateUtil: DateUtil, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__TEMPORARY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_User_Option.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_User_Option.kt deleted file mode 100644 index 2ca965fc60..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_User_Option.kt +++ /dev/null @@ -1,60 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Option_Set_User_Option( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION - aapsLogger.debug(LTag.PUMPCOMM, "Setting user settings") - } - - override fun getRequestParams(): ByteArray { - aapsLogger.debug(LTag.PUMPCOMM, - "UserOptions:" + (System.currentTimeMillis() - danaRPump.lastConnection) / 1000 + " s ago" - + "\ntimeDisplayType:" + danaRPump.timeDisplayType - + "\nbuttonScroll:" + danaRPump.buttonScrollOnOff - + "\ntimeDisplayType:" + danaRPump.timeDisplayType - + "\nlcdOnTimeSec:" + danaRPump.lcdOnTimeSec - + "\nbacklight:" + danaRPump.backlightOnTimeSec - + "\ndanaRPumpUnits:" + danaRPump.units - + "\nlowReservoir:" + danaRPump.lowReservoirRate) - val request = ByteArray(13) - request[0] = (danaRPump.timeDisplayType and 0xff).toByte() - request[1] = (danaRPump.buttonScrollOnOff and 0xff).toByte() - request[2] = (danaRPump.beepAndAlarm and 0xff).toByte() - request[3] = (danaRPump.lcdOnTimeSec and 0xff).toByte() - request[4] = (danaRPump.backlightOnTimeSec and 0xff).toByte() - request[5] = (danaRPump.selectedLanguage and 0xff).toByte() - request[6] = (danaRPump.units and 0xff).toByte() - request[7] = (danaRPump.shutdownHour and 0xff).toByte() - request[8] = (danaRPump.lowReservoirRate and 0xff).toByte() - request[9] = (danaRPump.cannulaVolume and 0xff).toByte() - request[10] = (danaRPump.cannulaVolume ushr 8 and 0xff).toByte() - request[11] = (danaRPump.refillAmount and 0xff).toByte() - request[12] = (danaRPump.refillAmount ushr 8 and 0xff).toByte() - return request - } - - override fun handleMessage(data: ByteArray) { - val result = intFromBuff(data, 0, 1) - if (result == 0) { - aapsLogger.debug(LTag.PUMPCOMM, "Result OK") - failed = false - } else { - aapsLogger.error("Result Error: $result") - failed = true - } - } - - override fun getFriendlyName(): String { - return "OPTION__SET_USER_OPTION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java deleted file mode 100644 index 35097dcef5..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java +++ /dev/null @@ -1,682 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.services; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCallback; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattService; -import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; -import android.content.Context; -import android.content.Intent; -import android.os.SystemClock; - -import com.cozmo.danar.util.BleCommandUtil; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ScheduledFuture; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventPumpStatusChanged; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; -import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by mike on 23.09.2017. - */ - -public class BLEComm { - private Logger log = StacktraceLoggerWrapper.getLogger(LTag.PUMPBTCOMM); - - private final long WRITE_DELAY_MILLIS = 50; - - private String UART_READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb"; - private String UART_WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb"; - - private final byte PACKET_START_BYTE = (byte) 0xA5; - private final byte PACKET_END_BYTE = (byte) 0x5A; - private Context context; - private DanaRPump danaRPump; - private DanaRSMessageHashTable danaRSMessageHashTable; - - public BLEComm(Context context, DanaRSMessageHashTable danaRSMessageHashTable, DanaRPump danaRPump) { - this.context = context; - this.danaRPump = danaRPump; - this.danaRSMessageHashTable = danaRSMessageHashTable; - initialize(); - } - - private ScheduledFuture scheduledDisconnection = null; - - private DanaRS_Packet processsedMessage = null; - private final ArrayList mSendQueue = new ArrayList<>(); - - private BluetoothManager mBluetoothManager = null; - private BluetoothAdapter mBluetoothAdapter = null; - private String mBluetoothDeviceName = null; - private BluetoothGatt mBluetoothGatt = null; - - protected boolean isConnected = false; - protected boolean isConnecting = false; - - private BluetoothGattCharacteristic UART_Read; - private BluetoothGattCharacteristic UART_Write; - - private boolean initialize() { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Initializing BLEComm."); - - if (mBluetoothManager == null) { - mBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)); - if (mBluetoothManager == null) { - log.error("Unable to initialize BluetoothManager."); - return false; - } - } - - mBluetoothAdapter = mBluetoothManager.getAdapter(); - if (mBluetoothAdapter == null) { - log.error("Unable to obtain a BluetoothAdapter."); - return false; - } - - return true; - } - - public boolean isConnected() { - return isConnected; - } - - public boolean isConnecting() { - return isConnecting; - } - - public boolean connect(String from, String address, Object confirmConnect) { - BluetoothManager tBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)); - if (tBluetoothManager == null) { - return false; - } - - BluetoothAdapter tBluetoothAdapter = tBluetoothManager.getAdapter(); - if (tBluetoothAdapter == null) { - return false; - } - - if (mBluetoothAdapter == null) { - if (!initialize()) { - return false; - } - } - - if (address == null) { - log.error("unspecified address."); - return false; - } - - isConnecting = true; - - BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); - if (device == null) { - log.error("Device not found. Unable to connect from: " + from); - return false; - } - - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Trying to create a new connection from: " + from); - mBluetoothDeviceName = device.getName(); - mBluetoothGatt = device.connectGatt(context, false, mGattCallback); - setCharacteristicNotification(getUARTReadBTGattChar(), true); - return true; - } - - public void stopConnecting() { - isConnecting = false; - } - - public synchronized void disconnect(String from) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("disconnect from: " + from); - - // cancel previous scheduled disconnection to prevent closing upcomming connection - if (scheduledDisconnection != null) - scheduledDisconnection.cancel(false); - scheduledDisconnection = null; - - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("disconnect not possible: (mBluetoothAdapter == null) " + (mBluetoothAdapter == null)); - log.error("disconnect not possible: (mBluetoothGatt == null) " + (mBluetoothGatt == null)); - return; - } - setCharacteristicNotification(getUARTReadBTGattChar(), false); - mBluetoothGatt.disconnect(); - isConnected = false; - SystemClock.sleep(2000); - } - - public synchronized void close() { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("BluetoothAdapter close"); - if (mBluetoothGatt == null) { - return; - } - - mBluetoothGatt.close(); - mBluetoothGatt = null; - } - - - private String getConnectDeviceName() { - return mBluetoothDeviceName; - } - - private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { - public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - onConnectionStateChangeSynchronized(gatt, status, newState); // call it synchronized - } - - public void onServicesDiscovered(BluetoothGatt gatt, int status) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onServicesDiscovered"); - if (status == BluetoothGatt.GATT_SUCCESS) { - findCharacteristic(); - } - SendPumpCheck(); - // 1st message sent to pump after connect - } - - public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onCharacteristicRead" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); - addToReadBuffer(characteristic.getValue()); - readDataParsing(); - } - - public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onCharacteristicChanged" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); - addToReadBuffer(characteristic.getValue()); - new Thread(() -> readDataParsing()).start(); - } - - public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); - new Thread(() -> { - synchronized (mSendQueue) { - // after message sent, check if there is the rest of the message waiting and send it - if (mSendQueue.size() > 0) { - byte[] bytes = mSendQueue.get(0); - mSendQueue.remove(0); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - } - }).start(); - } - }; - - private synchronized void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("setCharacteristicNotification"); - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return; - } - mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); - } - - public synchronized void readCharacteristic(BluetoothGattCharacteristic characteristic) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("readCharacteristic"); - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return; - } - mBluetoothGatt.readCharacteristic(characteristic); - } - - private synchronized void writeCharacteristic_NO_RESPONSE(final BluetoothGattCharacteristic characteristic, final byte[] data) { - new Thread(() -> { - SystemClock.sleep(WRITE_DELAY_MILLIS); - - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return; - } - - characteristic.setValue(data); - characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data)); - mBluetoothGatt.writeCharacteristic(characteristic); - }).start(); - } - - private BluetoothGattCharacteristic getUARTReadBTGattChar() { - if (UART_Read == null) { - UART_Read = new BluetoothGattCharacteristic(UUID.fromString(UART_READ_UUID), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0); - } - return UART_Read; - } - - private BluetoothGattCharacteristic getUARTWriteBTGattChar() { - if (UART_Write == null) { - UART_Write = new BluetoothGattCharacteristic(UUID.fromString(UART_WRITE_UUID), BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, 0); - } - return UART_Write; - } - - private List getSupportedGattServices() { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("getSupportedGattServices"); - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return null; - } - - return mBluetoothGatt.getServices(); - } - - private void findCharacteristic() { - List gattServices = getSupportedGattServices(); - - if (gattServices == null) { - return; - } - String uuid; - - for (BluetoothGattService gattService : gattServices) { - List gattCharacteristics = gattService.getCharacteristics(); - for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { - uuid = gattCharacteristic.getUuid().toString(); - if (UART_READ_UUID.equals(uuid)) { - UART_Read = gattCharacteristic; - setCharacteristicNotification(UART_Read, true); - } - if (UART_WRITE_UUID.equals(uuid)) { - UART_Write = gattCharacteristic; - } - } - } - } - - private synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onConnectionStateChange"); - - if (newState == BluetoothProfile.STATE_CONNECTED) { - mBluetoothGatt.discoverServices(); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - close(); - isConnected = false; - isConnecting = false; - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected - } - } - - private final byte[] readBuffer = new byte[1024]; - private int bufferLength = 0; - - private void addToReadBuffer(byte[] buffer) { - //log.debug("addToReadBuffer " + DanaRS_Packet.toHexString(buffer)); - if (buffer == null || buffer.length == 0) { - return; - } - synchronized (readBuffer) { - // Append incomming data to input buffer - System.arraycopy(buffer, 0, readBuffer, bufferLength, buffer.length); - bufferLength += buffer.length; - } - } - - private void readDataParsing() { - boolean startSignatureFound = false, packetIsValid = false; - boolean isProcessing; - - isProcessing = true; - - while (isProcessing) { - int length = 0; - byte[] inputBuffer = null; - synchronized (readBuffer) { - // Find packet start [A5 A5] - if (bufferLength >= 6) { - for (int idxStartByte = 0; idxStartByte < bufferLength - 2; idxStartByte++) { - if ((readBuffer[idxStartByte] == PACKET_START_BYTE) && (readBuffer[idxStartByte + 1] == PACKET_START_BYTE)) { - if (idxStartByte > 0) { - // if buffer doesn't start with signature remove the leading trash - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Shifting the input buffer by " + idxStartByte + " bytes"); - System.arraycopy(readBuffer, idxStartByte, readBuffer, 0, bufferLength - idxStartByte); - bufferLength -= idxStartByte; - } - startSignatureFound = true; - break; - } - } - } - // A5 A5 LEN TYPE CODE PARAMS CHECKSUM1 CHECKSUM2 5A 5A - // ^---- LEN -----^ - // total packet length 2 + 1 + readBuffer[2] + 2 + 2 - if (startSignatureFound) { - length = readBuffer[2]; - // test if there is enough data loaded - if (length + 7 > bufferLength) - return; - // Verify packed end [5A 5A] - if ((readBuffer[length + 5] == PACKET_END_BYTE) && (readBuffer[length + 6] == PACKET_END_BYTE)) { - packetIsValid = true; - } - } - if (packetIsValid) { - inputBuffer = new byte[length + 7]; - // copy packet to input buffer - System.arraycopy(readBuffer, 0, inputBuffer, 0, length + 7); - // Cut off the message from readBuffer - try { - System.arraycopy(readBuffer, length + 7, readBuffer, 0, bufferLength - (length + 7)); - } catch (Exception e) { - log.error("length: " + length + "bufferLength: " + bufferLength); - throw e; - } - bufferLength -= (length + 7); - // now we have encrypted packet in inputBuffer - } - } - if (packetIsValid) { - try { - // decrypt the packet - inputBuffer = BleCommandUtil.getInstance().getDecryptedPacket(inputBuffer); - - if (inputBuffer == null) { - log.error("Null decryptedInputBuffer"); - return; - } - - switch (inputBuffer[0]) { - // initial handshake packet - case (byte) BleCommandUtil.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE: - switch (inputBuffer[1]) { - // 1st packet - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK: - if (inputBuffer.length == 4 && inputBuffer[2] == 'O' && inputBuffer[3] == 'K') { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - // Grab pairing key from preferences if exists - String pairingKey = SP.getString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Using stored pairing key: " + pairingKey); - if (pairingKey != null) { - byte[] encodedPairingKey = DanaRS_Packet.hexToBytes(pairingKey); - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY, encodedPairingKey, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } else { - // Stored pairing key does not exists, request pairing - SendPairingRequest(); - } - - } else if (inputBuffer.length == 6 && inputBuffer[2] == 'P' && inputBuffer[3] == 'U' && inputBuffer[4] == 'M' && inputBuffer[5] == 'P') { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - mSendQueue.clear(); - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumperror))); - NSUpload.uploadError(MainApp.gs(R.string.pumperror)); - Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - } else if (inputBuffer.length == 6 && inputBuffer[2] == 'B' && inputBuffer[3] == 'U' && inputBuffer[4] == 'S' && inputBuffer[5] == 'Y') { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - mSendQueue.clear(); - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumpbusy))); - } else { - // ERROR in response, wrong serial number - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - mSendQueue.clear(); - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.connectionerror))); - SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName); - Notification n = new Notification(Notification.WRONGSERIALNUMBER, MainApp.gs(R.string.wrongpassword), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - } - break; - // 2nd packet, pairing key - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(inputBuffer)); - if (inputBuffer[2] == (byte) 0x00) { - // Paring is not requested, sending time info - SendTimeInfo(); - } else { - // Pairing on pump is requested - SendPairingRequest(); - } - break; - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer)); - if (inputBuffer[2] != (byte) 0x00) { - disconnect("passkey request failed"); - } - break; - // Paring response, OK button on pump pressed - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer)); - // Paring is successfull, sending time info - RxBus.Companion.getINSTANCE().send(new EventDanaRSPairingSuccess()); - SendTimeInfo(); - byte[] pairingKey = {inputBuffer[2], inputBuffer[3]}; - // store pairing key to preferences - SP.putString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, DanaRS_Packet.bytesToHex(pairingKey)); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey)); - break; - // time and user password information. last packet in handshake - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__TIME_INFORMATION " + /*message.getMessageName() + " " + */ DanaRS_Packet.toHexString(inputBuffer)); - int size = inputBuffer.length; - int pass = ((inputBuffer[size - 1] & 0x000000FF) << 8) + ((inputBuffer[size - 2] & 0x000000FF)); - pass = pass ^ 3463; - danaRPump.setRsPassword(Integer.toHexString(pass)); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Pump user password: " + Integer.toHexString(pass)); - - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED)); - isConnected = true; - isConnecting = false; - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("RS connected and status read"); - break; - } - break; - // common data packet - default: - DanaRS_Packet message; - // Retrieve message code from received buffer and last message sent - int originalCommand = processsedMessage != null ? processsedMessage.getCommand() : 0xFFFF; - int receivedCommand = DanaRS_Packet.getCommand(inputBuffer); - if (originalCommand == receivedCommand) { - // it's response to last message - message = processsedMessage; - } else { - // it's not response to last message, create new instance - message = danaRSMessageHashTable.findMessage(receivedCommand); - } - if (message != null) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer)); - // process received data - message.handleMessage(inputBuffer); - message.setReceived(); - synchronized (message) { - // notify to sendMessage - message.notify(); - } - } else { - log.error("Unknown message received " + DanaRS_Packet.toHexString(inputBuffer)); - } - break; - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - startSignatureFound = false; - packetIsValid = false; - if (bufferLength < 6) { - // stop the loop - isProcessing = false; - } - } else { - // stop the loop - isProcessing = false; - } - } - } - - public void sendMessage(DanaRS_Packet message) { - processsedMessage = message; - if (message == null) - return; - - byte[] command = {(byte) message.getType(), (byte) message.getOpCode()}; - byte[] params = message.getRequestParams(); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)); - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(message.getOpCode(), params, null); - // If there is another message not completely sent, add to queue only - if (mSendQueue.size() > 0) { - // Split to parts per 20 bytes max - for (; ; ) { - if (bytes.length > 20) { - byte[] addBytes = new byte[20]; - System.arraycopy(bytes, 0, addBytes, 0, addBytes.length); - byte[] reBytes = new byte[bytes.length - addBytes.length]; - System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length); - bytes = reBytes; - synchronized (mSendQueue) { - mSendQueue.add(addBytes); - } - } else { - synchronized (mSendQueue) { - mSendQueue.add(bytes); - } - break; - } - } - - } else { - if (bytes.length > 20) { - // Cut first 20 bytes - byte[] sendBytes = new byte[20]; - System.arraycopy(bytes, 0, sendBytes, 0, sendBytes.length); - byte[] reBytes = new byte[bytes.length - sendBytes.length]; - System.arraycopy(bytes, sendBytes.length, reBytes, 0, reBytes.length); - bytes = reBytes; - // and send - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), sendBytes); - // The rest split to parts per 20 bytes max - for (; ; ) { - if (bytes.length > 20) { - byte[] addBytes = new byte[20]; - System.arraycopy(bytes, 0, addBytes, 0, addBytes.length); - reBytes = new byte[bytes.length - addBytes.length]; - System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length); - bytes = reBytes; - synchronized (mSendQueue) { - mSendQueue.add(addBytes); - } - } else { - synchronized (mSendQueue) { - mSendQueue.add(bytes); - } - break; - } - } - } else { - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - } - // The rest from queue is send from onCharasteristicWrite (after sending 1st part) - synchronized (message) { - try { - message.wait(5000); - } catch (InterruptedException e) { - log.error("sendMessage InterruptedException", e); - log.error("Unhandled exception", e); - } - } - - //SystemClock.sleep(200); - if (!message.isReceived()) { - log.warn("Reply not received " + message.getFriendlyName()); - message.handleMessageNotReceived(); - } - } - - private void SendPairingRequest() { - // Start activity which is waiting 20sec - // On pump pairing request is displayed and is waiting for conformation - Intent i = new Intent(); - i.setClass(MainApp.instance(), PairingHelperActivity.class); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); - - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - - private void SendPumpCheck() { - // 1st message sent to pump after connect - String devicename = getConnectDeviceName(); - if (devicename == null || devicename.equals("")) { - Notification n = new Notification(Notification.DEVICENOTPAIRED, MainApp.gs(R.string.pairfirst), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - return; - } - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, devicename); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - - private void SendTimeInfo() { - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, null, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java deleted file mode 100644 index 359294ca00..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ /dev/null @@ -1,566 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.services; - -import android.content.Context; -import android.content.Intent; -import android.os.Binder; -import android.os.IBinder; -import android.os.SystemClock; - -import javax.inject.Inject; - -import dagger.android.DaggerService; -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.activities.ErrorHelperActivity; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; -import info.nightscout.androidaps.events.EventAppExit; -import info.nightscout.androidaps.events.EventInitializationChanged; -import info.nightscout.androidaps.events.EventProfileNeedsUpdate; -import info.nightscout.androidaps.events.EventPumpStatusChanged; -import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.interfaces.ProfileFunction; -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.EventOverviewBolusProgress; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRNewStatus; -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_Basal_Set_Temporary_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_History_Events; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_Set_Event_History; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Basal_Rate; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Profile_Number; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Temporary_Basal_State; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Profile_Basal_Rate; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Profile_Number; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Temporary_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Bolus_Option; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_CIR_CF_Array; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Calculation_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Extended_Bolus_State; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Step_Bolus_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Start; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Stop; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Get_Pump_Check; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Get_Shipping_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Initial_Screen_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Set_History_Upload_Mode; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Alarm; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Blood_Glucose; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Bolus; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Carbohydrate; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Daily; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Prime; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Refill; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Suspend; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Get_Pump_Time; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Get_User_Option; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Set_Pump_Time; -import info.nightscout.androidaps.db.Treatment; -import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - -public class DanaRSService extends DaggerService { - @Inject HasAndroidInjector injector; - @Inject AAPSLogger aapsLogger; - @Inject RxBusWrapper rxBus; - @Inject SP sp; - @Inject ResourceHelper resourceHelper; - @Inject ProfileFunction profileFunction; - @Inject CommandQueueProvider commandQueue; - @Inject Context context; - @Inject DanaRSPlugin danaRSPlugin; - @Inject DanaRPump danaRPump; - @Inject DanaRSMessageHashTable danaRSMessageHashTable; - @Inject ActivePluginProvider activePlugin; - @Inject ConstraintChecker constraintChecker; - @Inject DetailedBolusInfoStorage detailedBolusInfoStorage; - @Inject DateUtil dateUtil; - - private CompositeDisposable disposable = new CompositeDisposable(); - - private BLEComm bleComm; - - private IBinder mBinder = new LocalBinder(); - - private Treatment bolusingTreatment = null; - - private long lastHistoryFetched = 0; - private long lastApproachingDailyLimit = 0; - - @Override - public void onCreate() { - super.onCreate(); - bleComm = new BLEComm(this, danaRSMessageHashTable, danaRPump); - disposable.add(rxBus - .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) - .subscribe(event -> { - aapsLogger.debug(LTag.PUMPCOMM, "EventAppExit received"); - stopSelf(); - }, exception -> FabricPrivacy.getInstance().logException(exception)) - ); - } - - @Override - public void onDestroy() { - disposable.clear(); - super.onDestroy(); - } - - public boolean isConnected() { - return bleComm.isConnected; - } - - public boolean isConnecting() { - return bleComm.isConnecting; - } - - public boolean connect(String from, String address, Object confirmConnect) { - return bleComm.connect(from, address, confirmConnect); - } - - public void stopConnecting() { - bleComm.stopConnecting(); - } - - public void disconnect(String from) { - bleComm.disconnect(from); - } - - @SuppressWarnings("unused") - public void sendMessage(DanaRS_Packet message) { - bleComm.sendMessage(message); - } - - public void getPumpStatus() { - try { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))); - - bleComm.sendMessage(new DanaRS_Packet_General_Initial_Screen_Information(aapsLogger, danaRPump)); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)); // last bolus, bolusStep, maxBolus - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); - - danaRPump.setLastConnection(System.currentTimeMillis()); - - Profile profile = profileFunction.getProfile(); - PumpInterface pump = activePlugin.getActivePump(); - if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal - if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { - rxBus.send(new EventProfileNeedsUpdate()); - } - } - - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); - bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil)); - - long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (danaRPump.getPumpTime() == 0) { - // initial handshake was not successfull - // deinitialize pump - danaRPump.setLastConnection(0); - rxBus.send(new EventDanaRNewStatus()); - rxBus.send(new EventInitializationChanged()); - return; - } - long now = System.currentTimeMillis(); - if (danaRPump.getLastSettingsRead() + 60 * 60 * 1000L < now || !pump.isInitialized()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); - bleComm.sendMessage(new DanaRS_Packet_General_Get_Shipping_Information(aapsLogger, danaRPump, dateUtil)); // serial no - bleComm.sendMessage(new DanaRS_Packet_General_Get_Pump_Check(aapsLogger, danaRPump, rxBus, resourceHelper)); // firmware - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Profile_Number(aapsLogger, danaRPump)); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Bolus_Option(aapsLogger, rxBus, resourceHelper, danaRPump)); // isExtendedEnabled - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Calculation_Information(aapsLogger, danaRPump)); // target - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_CIR_CF_Array(aapsLogger, danaRPump)); - bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)); // Getting user options - danaRPump.setLastSettingsRead(now); - } - - aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds"); - if (Math.abs(timeDiff) > 3) { - if (Math.abs(timeDiff) > 60 * 60 * 1.5) { - aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds - large difference"); - //If time-diff is very large, warn user until we can synchronize history readings properly - Intent i = new Intent(context, ErrorHelperActivity.class); - i.putExtra("soundid", R.raw.error); - i.putExtra("status", resourceHelper.gs(R.string.largetimediff)); - i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle)); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(i); - - //deinitialize pump - danaRPump.setLastConnection(0); - rxBus.send(new EventDanaRNewStatus()); - rxBus.send(new EventInitializationChanged()); - return; - } else { - if (danaRPump.getProtocol() >= 6) { - bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil, DateUtil.now())); - } else { - waitForWholeMinute(); // Dana can set only whole minute - // add 10sec to be sure we are over minute (will be cutted off anyway) - bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil, DateUtil.now() + T.secs(10).msecs())); - } - bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil)); - timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds"); - } - } - - loadEvents(); - - rxBus.send(new EventDanaRNewStatus()); - rxBus.send(new EventInitializationChanged()); - //NSUpload.uploadDeviceStatus(); - if (danaRPump.getDailyTotalUnits() > danaRPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { - aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); - if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); - rxBus.send(new EventNewNotification(reportFail)); - NSUpload.uploadError(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits() + "U"); - lastApproachingDailyLimit = System.currentTimeMillis(); - } - } - } catch (Exception e) { - aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e); - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded"); - } - - public PumpEnactResult loadEvents() { - - if (!danaRSPlugin.isInitialized()) { - PumpEnactResult result = new PumpEnactResult(injector).success(false); - result.comment = "pump not initialized"; - return result; - } - - SystemClock.sleep(1000); - - DanaRS_Packet_APS_History_Events msg; - if (lastHistoryFetched == 0) { - msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, 0); - aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history"); - } else { - msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, lastHistoryFetched); - aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(lastHistoryFetched)); - } - bleComm.sendMessage(msg); - while (!danaRSPlugin.apsHistoryDone && bleComm.isConnected()) { - SystemClock.sleep(100); - } - if (danaRSPlugin.lastEventTimeLoaded != 0) - lastHistoryFetched = danaRSPlugin.lastEventTimeLoaded - T.mins(1).msecs(); - else - lastHistoryFetched = 0; - aapsLogger.debug(LTag.PUMPCOMM, "Events loaded"); - danaRPump.setLastConnection(System.currentTimeMillis()); - return new PumpEnactResult(injector).success(true); - } - - - public PumpEnactResult setUserSettings() { - bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)); - return new PumpEnactResult(injector).success(true); - } - - - public boolean bolus(final double insulin, int carbs, long carbtime, Treatment t) { - if (!isConnected()) return false; - if (BolusProgressDialog.stopPressed) return false; - - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))); - bolusingTreatment = t; - final int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0); - danaRSPlugin.bolusingTreatment = t; - danaRSPlugin.bolusAmountToBeDelivered = insulin; - danaRSPlugin.bolusStopped = false; - danaRSPlugin.bolusStopForced = false; - danaRSPlugin.bolusProgressLastTimeStamp = DateUtil.now(); - - DanaRS_Packet_Bolus_Set_Step_Bolus_Start start = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(aapsLogger, danaRSPlugin, constraintChecker, insulin, preferencesSpeed); - if (carbs > 0) { -// MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbtime, carbs); #### -// bleComm.sendMessage(msg); - DanaRS_Packet_APS_Set_Event_History msgSetHistoryEntry_v2 = new DanaRS_Packet_APS_Set_Event_History(aapsLogger, dateUtil, DanaRPump.CARBS, carbtime, carbs, 0); - bleComm.sendMessage(msgSetHistoryEntry_v2); - lastHistoryFetched = Math.min(lastHistoryFetched, carbtime - T.mins(1).msecs()); - } - - final long bolusStart = System.currentTimeMillis(); - if (insulin > 0) { - if (!danaRSPlugin.bolusStopped) { - bleComm.sendMessage(start); - } else { - t.insulin = 0d; - return false; - } - - while (!danaRSPlugin.bolusStopped && !start.failed && !danaRSPlugin.bolusDone) { - SystemClock.sleep(100); - if ((System.currentTimeMillis() - danaRSPlugin.bolusProgressLastTimeStamp) > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm - danaRSPlugin.bolusStopped = true; - danaRSPlugin.bolusStopForced = true; - aapsLogger.debug(LTag.PUMPCOMM, "Communication stopped"); - } - } - } - - final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; - bolusingEvent.setT(t); - bolusingEvent.setPercent(99); - - bolusingTreatment = null; - int speed = 12; - switch (preferencesSpeed) { - case 0: - speed = 12; - break; - case 1: - speed = 30; - break; - case 2: - speed = 60; - break; - } - long bolusDurationInMSec = (long) (insulin * speed * 1000); - long expectedEnd = bolusStart + bolusDurationInMSec + 2000; - while (System.currentTimeMillis() < expectedEnd) { - long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.setStatus(String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); - rxBus.send(bolusingEvent); - SystemClock.sleep(1000); - } - // do not call loadEvents() directly, reconnection may be needed - commandQueue.loadEvents(new Callback() { - @Override - public void run() { - // reread bolus status - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)); // last bolus - bolusingEvent.setPercent(100); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))); - } - }); - return !start.failed; - } - - public void bolusStop() { - aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin)); - DanaRS_Packet_Bolus_Set_Step_Bolus_Stop stop = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin); - danaRSPlugin.bolusStopForced = true; - if (isConnected()) { - bleComm.sendMessage(stop); - while (!danaRSPlugin.bolusStopped) { - bleComm.sendMessage(stop); - SystemClock.sleep(200); - } - } else { - danaRSPlugin.bolusStopped = true; - } - } - - public boolean tempBasal(Integer percent, int durationInHours) { - if (!isConnected()) return false; - if (danaRPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - SystemClock.sleep(500); - } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Temporary_Basal(aapsLogger, percent, durationInHours)); - SystemClock.sleep(200); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean highTempBasal(Integer percent) { - if (danaRPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - SystemClock.sleep(500); - } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, percent)); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean tempBasalShortDuration(Integer percent, int durationInMinutes) { - if (durationInMinutes != 15 && durationInMinutes != 30) { - aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param"); - return false; - } - - if (danaRPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - SystemClock.sleep(500); - } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, percent)); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean tempBasalStop() { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean extendedBolus(Double insulin, int durationInHalfHours) { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus(aapsLogger, insulin, durationInHalfHours)); - SystemClock.sleep(200); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean extendedBolusStop() { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(aapsLogger)); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean updateBasalsInPump(Profile profile) { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))); - Double[] basal = danaRPump.buildDanaRProfileRecord(profile); - DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(aapsLogger, 0, basal); - bleComm.sendMessage(msgSet); - DanaRS_Packet_Basal_Set_Profile_Number msgActivate = new DanaRS_Packet_Basal_Set_Profile_Number(aapsLogger, 0); - bleComm.sendMessage(msgActivate); - danaRPump.setLastSettingsRead(0); // force read full settings - getPumpStatus(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public PumpEnactResult loadHistory(byte type) { - PumpEnactResult result = new PumpEnactResult(injector); - if (!isConnected()) return result; - DanaRS_Packet_History_ msg = null; - switch (type) { - case RecordTypes.RECORD_TYPE_ALARM: - msg = new DanaRS_Packet_History_Alarm(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_PRIME: - msg = new DanaRS_Packet_History_Prime(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_BASALHOUR: - msg = new DanaRS_Packet_History_Basal(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_BOLUS: - msg = new DanaRS_Packet_History_Bolus(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_CARBO: - msg = new DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_DAILY: - msg = new DanaRS_Packet_History_Daily(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_GLUCOSE: - msg = new DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_REFILL: - msg = new DanaRS_Packet_History_Refill(aapsLogger, rxBus, dateUtil); - break; - case RecordTypes.RECORD_TYPE_SUSPEND: - msg = new DanaRS_Packet_History_Suspend(aapsLogger, rxBus, dateUtil); - break; - } - if (msg != null) { - bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger, 1)); - SystemClock.sleep(200); - bleComm.sendMessage(msg); - while (!msg.getDone() && isConnected()) { - SystemClock.sleep(100); - } - SystemClock.sleep(200); - bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger, 0)); - } - result.success = true; - result.comment = "OK"; - return result; - } - - - public class LocalBinder extends Binder { - public DanaRSService getServiceInstance() { - return DanaRSService.this; - } - - } - - @Override - public IBinder onBind(Intent intent) { - return mBinder; - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - return START_STICKY; - } - - void waitForWholeMinute() { - while (true) { - long time = DateUtil.now(); - long timeToWholeMinute = (60000 - time % 60000); - if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) - break; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); - SystemClock.sleep(Math.min(timeToWholeMinute, 100)); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt deleted file mode 100644 index 8833ea6b3f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt +++ /dev/null @@ -1,109 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRv2.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.* -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class MessageHashTableRv2 @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - constraintChecker: ConstraintChecker, - danaRPump: DanaRPump, - danaRPlugin: DanaRPlugin, - danaRKoreanPlugin: DanaRKoreanPlugin, - danaRv2Plugin: DanaRv2Plugin, - configBuilderPlugin: ConfigBuilderPlugin, - commandQueue: CommandQueueProvider, - activePlugin: ActivePluginProvider, - detailedBolusInfoStorage: DetailedBolusInfoStorage, - treatmentsPlugin: TreatmentsPlugin, - injector: HasAndroidInjector, - dateUtil: DateUtil -) : MessageHashTableBase { - - var messages: HashMap = HashMap() - - init { - put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED - put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS - put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING - put(MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended_v2(aapsLogger, danaRPump)) // 0x0207 CMD_PUMP_EXPANS_INS_I - put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I - put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS - put(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) // 0x0301 CMD_PUMPINIT_TIME_INFO - put(MsgInitConnStatusBolus(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO - put(MsgInitConnStatusBasic(aapsLogger, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO - put(MsgInitConnStatusOption(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0304 CMD_PUMPINIT_OPTION - put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S - put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S - put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP - put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S - put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS - put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT - put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT - put(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS - put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS - put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE - put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM - put(MsgHistoryError(aapsLogger, rxBus, dateUtil)) // 0x3106 CMD_HISTORY_ERROR - put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY - put(MsgHistoryRefill(aapsLogger, rxBus, dateUtil)) // 0x3108 CMD_HISTORY_REFILL - put(MsgHistorySuspend(aapsLogger, rxBus, dateUtil)) // 0x3109 CMD_HISTORY_SUSPEND - put(MsgHistoryBasalHour(aapsLogger, rxBus, dateUtil)) // 0x310A CMD_HISTORY_BASAL_HOUR - put(MsgHistoryDone(aapsLogger, danaRPump)) // 0x31F1 CMD_HISTORY_DONT_USED - put(MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin)) // 0x3202 CMD_SETTING_V_BASAL_INS_I - put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) // 0x3203 CMD_SETTING_V_MEAL_SETTING_I - put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I - put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I - put(MsgSettingBasalProfileAll(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL - put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I - put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY - put(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 0x320A CMD_SETTING_V_TIME_I - put(MsgSettingUserOptions(aapsLogger, danaRPump)) // 0x320B CMD_SETTING_V_USER_OPTIONS - put(MsgSettingActiveProfile(aapsLogger, danaRPump)) // 0x320C CMD_SETTING_V_PROFILE_NUMBER - put(MsgSettingProfileRatiosAll(aapsLogger, danaRPump)) // 0x320D CMD_SETTING_V_CIR_CF_VALUE - put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S - put(MsgSetBasalProfile(aapsLogger, rxBus, resourceHelper, 0.toByte(), Array(24) { 0.0 })) // 0x3306 CMD_SETTING_BASAL_PROFILE_S - put(MsgSetUserOptions(aapsLogger, danaRPump)) // 0x330B CMD_SETTING_USER_OPTIONS_S - put(MsgSetActivateBasalProfile(aapsLogger, 0.toByte())) // 0x330C CMD_SETTING_PROFILE_NUMBER_S - put(MsgHistoryAllDone(aapsLogger, danaRPump)) // 0x41F1 CMD_HISTORY_ALL_DONE - put(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL - put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW - put(MsgCheckValue_v2(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue)) // 0xF0F1 CMD_PUMP_CHECK_VALUE - put(MsgStatusAPS_v2(aapsLogger, danaRPump)) // 0xE001 CMD_PUMPSTATUS_APS - put(MsgSetAPSTempBasalStart_v2(aapsLogger, 0, false, false)) // 0xE002 CMD_PUMPSET_APSTEMP - put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, dateUtil)) // 0xE003 CMD_GET_HISTORY - put(MsgSetHistoryEntry_v2(aapsLogger, 0, 0, 0, 0)) // 0xE004 CMD_SET_HISTORY_ENTRY - } - - override fun put(message: MessageBase) { - messages[message.command] = message - } - - override fun findMessage(command: Int): MessageBase { - return messages[command] ?: MessageBase() - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java index 0812bb7614..50722c627c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java @@ -8,7 +8,6 @@ import android.content.ServiceConnection; import android.os.Binder; import android.os.IBinder; import android.os.Vibrator; -import android.text.Html; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; @@ -34,6 +33,7 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.InsightExcepti import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.AppLayerErrorException; import info.nightscout.androidaps.plugins.pump.insight.utils.AlertUtils; import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper; public class InsightAlertService extends DaggerService implements InsightConnectionService.StateCallback { @@ -299,7 +299,7 @@ public class InsightAlertService extends DaggerService implements InsightConnect notificationBuilder.setContentTitle(alertUtils.getAlertCode(alert.getAlertType()) + " – " + alertUtils.getAlertTitle(alert.getAlertType())); String description = alertUtils.getAlertDescription(alert); if (description != null) - notificationBuilder.setContentText(Html.fromHtml(description).toString()); + notificationBuilder.setContentText(HtmlHelper.INSTANCE.fromHtml(description).toString()); Intent fullScreenIntent = new Intent(this, InsightAlertActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 2c1c9b6e91..cc4cdd9516 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -269,7 +269,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick private void getBatteryStatusItem(List statusItems) { if (localInsightPlugin.getBatteryStatus() == null) return; - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_battery_label), + statusItems.add(getStatusItem(resourceHelper.gs(R.string.battery_label), localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%")); } @@ -280,7 +280,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick if (cartridgeStatus.isInserted()) status = DecimalFormatter.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U"; else status = resourceHelper.gs(R.string.not_inserted); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_reservoir_label), status)); + statusItems.add(getStatusItem(resourceHelper.gs(R.string.reservoir_label), status)); } private void getTDDItems(List statusItems) { @@ -294,14 +294,14 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick private void getBaseBasalRateItem(List statusItems) { if (localInsightPlugin.getActiveBasalRate() == null) return; ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_basebasalrate_label), + statusItems.add(getStatusItem(resourceHelper.gs(R.string.basebasalrate_label), DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); } private void getTBRItem(List statusItems) { if (localInsightPlugin.getActiveTBR() == null) return; ActiveTBR activeTBR = localInsightPlugin.getActiveTBR(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_tempbasal_label), + statusItems.add(getStatusItem(resourceHelper.gs(R.string.tempbasal_label), resourceHelper.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()))); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index d44470bad1..f8d1cf1ce5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -39,6 +38,7 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.CommandQueueProvider; @@ -46,6 +46,7 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpPluginBase; @@ -53,7 +54,6 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -132,7 +132,6 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException; import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; -import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.TimeChangeType; @@ -149,7 +148,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, private final SP sp; private final CommandQueueProvider commandQueue; private final ProfileFunction profileFunction; + private final NSUpload nsUpload; private final Context context; + private final UploadQueue uploadQueue; private final DateUtil dateUtil; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; @@ -209,7 +210,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, SP sp, CommandQueueProvider commandQueue, ProfileFunction profileFunction, + NSUpload nsUpload, Context context, + UploadQueue uploadQueue, Config config, DateUtil dateUtil ) { @@ -230,7 +233,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, this.sp = sp; this.commandQueue = commandQueue; this.profileFunction = profileFunction; + this.nsUpload = nsUpload; this.context = context; + this.uploadQueue = uploadQueue; this.dateUtil = dateUtil; pumpDescription = new PumpDescription(); @@ -929,8 +934,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, if (extendedBolus.durationInMinutes <= 0) { final String _id = extendedBolus._id; if (NSUpload.isIdValid(_id)) - NSUpload.removeCareportalEntryFromNS(_id); - else UploadQueue.removeID("dbAdd", _id); + nsUpload.removeCareportalEntryFromNS(_id); + else uploadQueue.removeID("dbAdd", _id); MainApp.getDbHelper().delete(extendedBolus); } else treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); @@ -978,7 +983,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { long now = System.currentTimeMillis(); if (connectionService == null) return null; if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) { @@ -991,7 +996,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, final JSONObject extended = new JSONObject(); try { status.put("timestamp", DateUtil.toISOString(connectionService.getLastConnected())); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extended.put("Version", version); try { extended.put("ActiveProfile", profileFunction.getProfileName()); } catch (Exception e) { @@ -1451,8 +1456,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, ExtendedBolus extendedBolus = MainApp.getDbHelper().getExtendedBolusByPumpId(bolusID.id); if (extendedBolus != null) { final String _id = extendedBolus._id; - if (NSUpload.isIdValid(_id)) NSUpload.removeCareportalEntryFromNS(_id); - else UploadQueue.removeID("dbAdd", _id); + if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id); + else uploadQueue.removeID("dbAdd", _id); MainApp.getDbHelper().delete(extendedBolus); } } else { @@ -1583,7 +1588,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, careportalEvent.eventType = CareportalEvent.NOTE; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } @@ -1617,7 +1622,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, careportalEvent.eventType = event; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java index 65034d321a..c5121184ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService; import info.nightscout.androidaps.plugins.pump.insight.descriptors.Alert; import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertStatus; import info.nightscout.androidaps.plugins.pump.insight.utils.AlertUtils; +import info.nightscout.androidaps.utils.HtmlHelper; public class InsightAlertActivity extends DaggerAppCompatActivity { @@ -91,7 +92,7 @@ public class InsightAlertActivity extends DaggerAppCompatActivity { if (description == null) this.errorDescription.setVisibility(View.GONE); else { this.errorDescription.setVisibility(View.VISIBLE); - this.errorDescription.setText(Html.fromHtml(description)); + this.errorDescription.setText(HtmlHelper.INSTANCE.fromHtml(description)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java index f1b4c3f6de..e0d0f2461a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java @@ -22,7 +22,7 @@ public class DeliverBolusMessage extends AppLayerMessage { @Override protected ByteBuf getData() { ByteBuf byteBuf = new ByteBuf(22); - byteBuf.putUInt16LE(805); + byteBuf.putUInt16LE(252); byteBuf.putUInt16LE(BolusTypeIDs.IDS.getID(bolusType)); byteBuf.putUInt16LE(31); byteBuf.putUInt16LE(0); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java index b5d7fafb4e..44550ebea6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java @@ -227,14 +227,14 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { } @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { long now = System.currentTimeMillis(); JSONObject pump = new JSONObject(); JSONObject status = new JSONObject(); JSONObject extended = new JSONObject(); try { status.put("status", "normal"); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extended.put("Version", version); try { extended.put("ActiveProfile", profileName); } catch (Exception e) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index 95a3f68c12..77df3be676 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -201,7 +201,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter if (pref.getKey().equals(getResourceHelper().gs(R.string.key_rileylink_mac_address))) { String value = sp.getStringOrNull(R.string.key_rileylink_mac_address, null); - pref.setSummary(value == null ? getResourceHelper().gs(R.string.rileylink_error_address_not_set_short) : value); + pref.setSummary(value == null ? getResourceHelper().gs(R.string.not_set_short) : value); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java index 086dc92cd7..83ed08ddd0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java @@ -87,9 +87,9 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager } @Override - public E createResponseMessage(byte[] payload, Class clazz) { + public RLMessage createResponseMessage(byte[] payload) { PumpMessage pumpMessage = new PumpMessage(aapsLogger, payload); - return (E) pumpMessage; + return pumpMessage; } @Override @@ -170,7 +170,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager if (radioResponse.isValid()) { - PumpMessage pumpResponse = createResponseMessage(radioResponse.getPayload(), PumpMessage.class); + PumpMessage pumpResponse = (PumpMessage) createResponseMessage(radioResponse.getPayload()); if (!pumpResponse.isValid()) { aapsLogger.warn(LTag.PUMPCOMM, "Response is invalid ! [interrupted={}, timeout={}]", rfSpyResponse.wasInterrupted(), @@ -551,8 +551,8 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager // All pump communications go through this function. - private PumpMessage sendAndListen(RLMessage msg, int timeout_ms) throws RileyLinkCommunicationException { - return sendAndListen(msg, timeout_ms, PumpMessage.class); + protected PumpMessage sendAndListen(RLMessage msg, int timeout_ms) throws RileyLinkCommunicationException { + return sendAndListen(msg, timeout_ms); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index d8f5c47b4f..76f011da16 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java @@ -78,6 +78,7 @@ public class MedtronicHistoryData { private final AAPSLogger aapsLogger; private final SP sp; private final ActivePluginProvider activePlugin; + private final NSUpload nsUpload; private final MedtronicUtil medtronicUtil; private final MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder; @@ -106,6 +107,7 @@ public class MedtronicHistoryData { AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin, + NSUpload nsUpload, MedtronicUtil medtronicUtil, MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder ) { @@ -115,6 +117,7 @@ public class MedtronicHistoryData { this.aapsLogger = aapsLogger; this.sp = sp; this.activePlugin = activePlugin; + this.nsUpload = nsUpload; this.medtronicUtil = medtronicUtil; this.medtronicPumpHistoryDecoder = medtronicPumpHistoryDecoder; } @@ -543,7 +546,7 @@ public class MedtronicHistoryData { careportalEvent.eventType = event; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java index 61b235f1d2..f5ff77cf72 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java @@ -363,10 +363,6 @@ public class BasalProfile { } - private boolean isLogEnabled() { - return L.isEnabled(LTag.PUMPCOMM); - } - public boolean verify(PumpType pumpType) { try { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java index caac54e122..bf3e771b1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java @@ -42,8 +42,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo public TempBasalPair(AAPSLogger aapsLogger, byte[] response) { super(); - if (L.isEnabled(LTag.PUMPCOMM)) - aapsLogger.debug(LTag.PUMPBTCOMM, "Received TempBasal response: " + ByteUtil.getHex(response)); + aapsLogger.debug(LTag.PUMPBTCOMM, "Received TempBasal response: " + ByteUtil.getHex(response)); isPercent = response[0] == 1; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java index cb3aad5f94..1d5d300b49 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java @@ -23,11 +23,13 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; +import info.nightscout.androidaps.utils.resources.ResourceHelper; public class MedtronicHistoryActivity extends NoSplashAppCompatActivity { @Inject MedtronicHistoryData medtronicHistoryData; + @Inject ResourceHelper resourceHelper; Spinner historyTypeSpinner; TextView statusView; @@ -119,7 +121,7 @@ public class MedtronicHistoryActivity extends NoSplashAppCompatActivity { statusView.setVisibility(View.GONE); - typeListFull = getTypeList(PumpHistoryEntryGroup.getList()); + typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(resourceHelper)); ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, R.layout.spinner_centered, typeListFull); historyTypeSpinner.setAdapter(spinnerAdapter); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java index 7c6a55d092..7ae299036d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/service/RileyLinkMedtronicService.java @@ -61,6 +61,11 @@ public class RileyLinkMedtronicService extends RileyLinkService { } + @Override public void onCreate() { + super.onCreate(); + aapsLogger.debug(LTag.PUMPCOMM, "RileyLinkMedtronicService newly created"); + } + @Override public void onConfigurationChanged(Configuration newConfig) { aapsLogger.warn(LTag.PUMPCOMM, "onConfigurationChanged"); @@ -314,7 +319,7 @@ public class RileyLinkMedtronicService extends RileyLinkService { return false; } - RileyLinkEncodingType newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr); + RileyLinkEncodingType newEncodingType = RileyLinkEncodingType.getByDescription(encodingTypeStr, resourceHelper); if (encodingType == null) { encodingType = newEncodingType; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt index 6dba697009..843beed61f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt @@ -100,7 +100,7 @@ class OmnipodFragment : DaggerFragment() { omnipod_refresh.setOnClickListener { if (omnipodPumpPlugin.rileyLinkService?.verifyConfiguration() != true) { - OmnipodUtil.displayNotConfiguredDialog(context) + displayNotConfiguredDialog() } else { omnipod_refresh.isEnabled = false omnipodPumpPlugin.addPodStatusRequest(OmnipodStatusRequest.GetPodState); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java index 0c51b5901c..76d39f7318 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java @@ -24,7 +24,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -91,8 +90,6 @@ import io.reactivex.schedulers.Schedulers; public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPumpPluginInterface, RileyLinkPumpDevice { // TODO Dagger (maybe done) - private static OmnipodPumpPlugin plugin = null; - private RileyLinkServiceData rileyLinkServiceData; private ServiceTaskExecutor serviceTaskExecutor; private RileyLinkOmnipodService rileyLinkOmnipodService; private OmnipodUtil omnipodUtil; @@ -151,11 +148,9 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump PumpType.Insulet_Omnipod, injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil ); - this.rileyLinkServiceData = rileyLinkServiceData; this.serviceTaskExecutor = serviceTaskExecutor; displayConnectionMessages = false; - OmnipodPumpPlugin.plugin = this; this.omnipodUtil = omnipodUtil; this.omnipodPumpStatus = omnipodPumpStatus; @@ -250,14 +245,6 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump } - @Deprecated - public static OmnipodPumpPlugin getPlugin() { - if (plugin == null) - throw new IllegalStateException("Plugin not injected jet"); - return plugin; - } - - @Override protected void onStart() { super.onStart(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java index e77befd258..89b6a43559 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java @@ -16,11 +16,8 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLink import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.ServiceTaskExecutor; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; -import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.OmnipodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; @@ -94,8 +91,8 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { } @Override - public E createResponseMessage(byte[] payload, Class clazz) { - return (E) new OmnipodPacket(payload); + public RLMessage createResponseMessage(byte[] payload) { + return new OmnipodPacket(payload); } @Override @@ -301,7 +298,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { OmnipodPacket ack = createAckPacket(podState, packetAddress, messageAddress); boolean quiet = false; while (!quiet) try { - sendAndListen(ack, 300, 1, 0, 40, OmnipodPacket.class); + sendAndListen(ack, 300, 1, 0, 40); } catch (RileyLinkCommunicationException ex) { if (RileyLinkBLEError.Timeout.equals(ex.getErrorCode())) { quiet = true; @@ -333,7 +330,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { while (System.currentTimeMillis() < timeoutTime) { OmnipodPacket response = null; try { - response = sendAndListen(packet, responseTimeoutMilliseconds, repeatCount, 9, preambleExtensionMilliseconds, OmnipodPacket.class); + response = (OmnipodPacket) sendAndListen(packet, responseTimeoutMilliseconds, repeatCount, 9, preambleExtensionMilliseconds); } catch (RileyLinkCommunicationException | OmnipodException ex) { aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in exchangePackets: " + ex.getClass().getSimpleName() + ": " + ex.getMessage()); continue; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java index f2066ebb2b..0026d41f97 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java @@ -10,6 +10,7 @@ public interface OmnipodPumpPluginInterface extends PumpInterface { void setDriverState(OmnipodDriverState state); + @Deprecated RxBusWrapper getRxBus(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java index d98721ff15..bfbdbfc9d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java @@ -148,7 +148,7 @@ public class PodHistoryActivity extends NoSplashAppCompatActivity { statusView.setVisibility(View.GONE); - typeListFull = getTypeList(PumpHistoryEntryGroup.getList()); + typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(resourceHelper)); ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, R.layout.spinner_centered, typeListFull); historyTypeSpinner.setAdapter(spinnerAdapter); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java index 37c6d420f7..70dac25789 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java @@ -35,6 +35,7 @@ public class InitPodRefreshAction extends AbstractCancelAction implements Finish @Inject OmnipodUtil omnipodUtil; @Inject AAPSLogger aapsLogger; @Inject SP sp; + @Inject NSUpload nsUpload; public InitPodRefreshAction(HasAndroidInjector injector, PodManagementActivity podManagementActivity, PodActionType actionType) { injector.androidInjector().inject(this); @@ -86,7 +87,7 @@ public class InitPodRefreshAction extends AbstractCancelAction implements Finish careportalEvent.eventType = event; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception when uploading SiteChange event.", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java index 6632cd0213..5a47672e8c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java @@ -425,7 +425,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface pumpStatus.tempBasalEnd = DateTimeUtil.getTimeInFutureFromMinutes(time, tempBasalPair.getDurationMinutes()); pumpStatus.tempBasalPumpId = pumpId; - TemporaryBasal tempStart = new TemporaryBasal() // + TemporaryBasal tempStart = new TemporaryBasal(injector) // .date(time) // .duration(tempBasalPair.getDurationMinutes()) // .absolute(tempBasalPair.getInsulinRate()) // @@ -561,7 +561,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface addSuccessToHistory(time, PodHistoryEntryType.CancelTemporaryBasal, null); - TemporaryBasal temporaryBasal = new TemporaryBasal() // + TemporaryBasal temporaryBasal = new TemporaryBasal(injector) // .date(time) // .duration(0) // .pumpId(pumpStatus.tempBasalPumpId) @@ -709,7 +709,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface Intent intent = new Intent(context, ErrorHelperActivity.class); intent.putExtra("soundid", sound == null ? 0 : sound); intent.putExtra("status", message); - intent.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)); + intent.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java index f002989e3c..dfaa18bcaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java @@ -35,6 +35,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodDriverState import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange; import info.nightscout.androidaps.utils.alertDialogs.OKDialog; +import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; /** @@ -49,6 +50,7 @@ public class OmnipodUtil { private final OmnipodPumpStatus omnipodPumpStatus; private final ActivePluginProvider activePlugins; private final SP sp; + private final ResourceHelper resourceHelper; private final HasAndroidInjector injector; private boolean lowLevelDebug = true; @@ -67,6 +69,7 @@ public class OmnipodUtil { RileyLinkUtil rileyLinkUtil, OmnipodPumpStatus omnipodPumpStatus, SP sp, + ResourceHelper resourceHelper, ActivePluginProvider activePlugins, HasAndroidInjector injector ) { @@ -75,6 +78,7 @@ public class OmnipodUtil { this.rileyLinkUtil = rileyLinkUtil; this.omnipodPumpStatus = omnipodPumpStatus; this.sp = sp; + this.resourceHelper = resourceHelper; this.activePlugins = activePlugins; this.injector = injector; } @@ -102,11 +106,6 @@ public class OmnipodUtil { rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(currentCommand)); } - public static void displayNotConfiguredDialog(Context context) { - OKDialog.showConfirmation(context, MainApp.gs(R.string.combo_warning), - MainApp.gs(R.string.omnipod_error_operation_not_possible_no_configuration), (Runnable) null); - } - public OmnipodDriverState getDriverState() { return driverState; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java index d4f8e8dc85..29e21e41ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java @@ -50,7 +50,6 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP // TODO Dagger //private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); - protected static OmnipodDashPumpPlugin plugin = null; //private RileyLinkOmnipodService omnipodService; //private OmnipodPumpStatus pumpStatusLocal = null; @@ -136,14 +135,6 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP // }; } - @Deprecated - public static OmnipodDashPumpPlugin getPlugin() { - if (plugin == null) - throw new IllegalStateException("Plugin not injected jet"); - return plugin; - } - - private String getLogPrefix() { return "OmnipodPlugin::"; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 3db377a230..2ef49e95b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.virtual import android.os.SystemClock import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo @@ -67,16 +66,6 @@ class VirtualPumpPlugin @Inject constructor( ), PumpInterface { - companion object { - private lateinit var virtualPumpPlugin: VirtualPumpPlugin - - @Deprecated("Use dagger to get an instance") - fun getPlugin(): VirtualPumpPlugin { - checkNotNull(virtualPumpPlugin) { "Accessing VirtualPumpPlugin before first instantiation" } - return virtualPumpPlugin - } - } - private val disposable = CompositeDisposable() var batteryPercent = 50 var reservoirInUnits = 50 @@ -87,7 +76,6 @@ class VirtualPumpPlugin @Inject constructor( private val pumpDescription = PumpDescription() init { - virtualPumpPlugin = this pumpDescription.isBolusCapable = true pumpDescription.bolusStep = 0.1 pumpDescription.isExtendedBolusCapable = true @@ -337,7 +325,7 @@ class VirtualPumpPlugin @Inject constructor( return result } - override fun getJSONStatus(profile: Profile, profileName: String): JSONObject { + override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject { val now = System.currentTimeMillis() if (!sp.getBoolean("virtualpump_uploadstatus", false)) { return JSONObject() @@ -349,7 +337,7 @@ class VirtualPumpPlugin @Inject constructor( try { battery.put("percent", batteryPercent) status.put("status", "normal") - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION) + extended.put("Version", version) try { extended.put("ActiveProfile", profileName) } catch (ignored: Exception) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java index 5740c7a5d1..fec1b6d960 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java @@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.sensitivity; import androidx.collection.LongSparseArray; +import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -61,7 +63,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { this.dateUtil = dateUtil; } - @Override + @NotNull @Override public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular // dependency, this should be avoided @@ -92,7 +94,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { //[0] = 8 hour //[1] = 24 hour //Deviationshour has DeviationsArray - List deviationsHour = Arrays.asList(new ArrayList(), new ArrayList()); + List> deviationsHour = Arrays.asList(new ArrayList<>(), new ArrayList<>()); List pastSensitivityArray = Arrays.asList("", ""); List sensResultArray = Arrays.asList("", ""); List ratioArray = Arrays.asList(0d, 0d); @@ -118,7 +120,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { //hoursegment = 0 = 8 hour //hoursegment = 1 = 24 hour while (hoursegment < deviationsHour.size()) { - ArrayList deviationsArray = deviationsHour.get(hoursegment); + ArrayList deviationsArray = deviationsHour.get(hoursegment); String pastSensitivity = pastSensitivityArray.get(hoursegment); // reset deviations after site change @@ -144,8 +146,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { deviationsArray.add(deviation); - for (int i = 0; i < autosensData.extraDeviation.size(); i++) - deviationsArray.add(autosensData.extraDeviation.get(i)); + deviationsArray.addAll(autosensData.extraDeviation); if (deviationsArray.size() > deviationCategory.get(hoursegment)) { deviationsArray.remove(0); @@ -170,13 +171,12 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely for (int i = 0; i < deviationsHour.size(); i++) { - ArrayList deviations = deviationsHour.get(i); + ArrayList deviations = deviationsHour.get(i); getAapsLogger().debug(LTag.AUTOSENS, "Using most recent " + deviations.size() + " deviations"); if (deviations.size() < deviationCategory.get(i)) { int pad = (int) Math.round((1 - (double) deviations.size() / deviationCategory.get(i)) * 18); getAapsLogger().debug(LTag.AUTOSENS, "Adding " + pad + " more zero deviations"); for (int d = 0; d < pad; d++) { - ; deviations.add(0d); } } @@ -190,11 +190,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { ArrayList deviationsArray = deviationsHour.get(hourused); String pastSensitivity = pastSensitivityArray.get(hourused); String sensResult = "(8 hours) "; - String senstime = sensResult; - if (hourused == 1) { - senstime = "(24 hours) "; - sensResult = senstime; - } + if (hourused == 1) sensResult = "(24 hours) "; String ratioLimit = ""; Double[] deviations = new Double[deviationsArray.size()]; @@ -212,10 +208,10 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { double basalOff = 0; if (pSensitive < 0) { // sensitive - basalOff = pSensitive * (60 / 5) / Profile.toMgdl(sens, profile.getUnits()); + basalOff = pSensitive * (60.0 / 5) / Profile.toMgdl(sens, profile.getUnits()); sensResult += "Excess insulin sensitivity detected"; } else if (pResistant > 0) { // resistant - basalOff = pResistant * (60 / 5) / Profile.toMgdl(sens, profile.getUnits()); + basalOff = pResistant * (60.0 / 5) / Profile.toMgdl(sens, profile.getUnits()); sensResult += "Excess insulin resistance detected"; } else { sensResult += "Sensitivity normal"; @@ -239,7 +235,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { if (ratioArray.get(0) < ratioArray.get(1)) { key = 0; } - String message = hoursDetection.get(key) + " of sensitivity used"; + //String message = hoursDetection.get(key) + " of sensitivity used"; AutosensResult output = fillResult(ratioArray.get(key), current.cob, pastSensitivityArray.get(key), ratioLimitArray.get(key), sensResultArray.get(key) + comparison, deviationsHour.get(key).size()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index 7e854f7e96..41d1c07ddc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -31,7 +31,8 @@ class DexcomPlugin @Inject constructor( private val sp: SP, private val mainApp: MainApp, resourceHelper: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -78,10 +79,10 @@ class DexcomPlugin @Inject constructor( bgReading.raw = 0.0 if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom$sensorType")) { if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType") + nsUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType") } if (sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } @@ -108,7 +109,7 @@ class DexcomPlugin @Inject constructor( careportalEvent.eventType = CareportalEvent.BGCHECK careportalEvent.json = jsonObject.toString() MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadCareportalEntryToNS(jsonObject) + nsUpload.uploadCareportalEntryToNS(jsonObject) } } } @@ -128,7 +129,7 @@ class DexcomPlugin @Inject constructor( careportalEvent.eventType = CareportalEvent.SENSORCHANGE careportalEvent.json = jsonObject.toString() MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadCareportalEntryToNS(jsonObject) + nsUpload.uploadCareportalEntryToNS(jsonObject) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index 6b0021fbcf..9141d57214 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -29,7 +29,8 @@ class EversensePlugin @Inject constructor( private val sp: SP, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val dateUtil: DateUtil + private val dateUtil: DateUtil, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -77,10 +78,10 @@ class EversensePlugin @Inject constructor( bgReading.raw = 0.0 val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Eversense") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Eversense") + nsUpload.uploadBg(bgReading, "AndroidAPS-Eversense") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } @@ -103,7 +104,7 @@ class EversensePlugin @Inject constructor( data.put("glucoseType", "Finger") data.put("glucose", calibrationGlucoseLevels[i]) data.put("units", Constants.MGDL) - NSUpload.uploadCareportalEntryToNS(data) + nsUpload.uploadCareportalEntryToNS(data) } } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index c33cfaee0f..2032dd4479 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -26,7 +26,8 @@ class PoctechPlugin @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP + private val sp: SP, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -58,10 +59,10 @@ class PoctechPlugin @Inject constructor( if (safeGetString(json, "units", Constants.MGDL) == "mmol/L") bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Poctech") + nsUpload.uploadBg(bgReading, "AndroidAPS-Poctech") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } catch (e: JSONException) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index db4c658614..1ba7958b61 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -22,7 +22,8 @@ class TomatoPlugin @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP + private val sp: SP, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -46,10 +47,10 @@ class TomatoPlugin @Inject constructor( bgReading.date = bundle.getLong("com.fanqies.tomatofn.Extras.Time") val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Tomato") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Tomato") + nsUpload.uploadBg(bgReading, "AndroidAPS-Tomato") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index f43ece03d8..60bd9b9b8c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -38,6 +38,7 @@ import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; @@ -60,6 +61,7 @@ public class TreatmentService extends OrmLiteBaseService { @Inject FabricPrivacy fabricPrivacy; @Inject RxBusWrapper rxBus; @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject DatabaseHelperInterface databaseHelper; private CompositeDisposable disposable = new CompositeDisposable(); @@ -289,7 +291,7 @@ public class TreatmentService extends OrmLiteBaseService { } try { Treatment old; - treatment.date = DatabaseHelper.roundDateToSec(treatment.date); + treatment.date = databaseHelper.roundDateToSec(treatment.date); if (treatment.source == Source.PUMP) { // check for changed from pump change in NS @@ -412,7 +414,7 @@ public class TreatmentService extends OrmLiteBaseService { aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); try { - treatment.date = DatabaseHelper.roundDateToSec(treatment.date); + treatment.date = databaseHelper.roundDateToSec(treatment.date); Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date); @@ -539,37 +541,6 @@ public class TreatmentService extends OrmLiteBaseService { return (Math.abs(diff) <= 0.00001); } - @Deprecated - private void treatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { - - aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); - - - if (fromNightScout) { - long pumpId_old = oldTreatment.pumpId; - boolean isSMB = (oldTreatment.isSMB || newTreatment.isSMB); - - oldTreatment.copyFrom(newTreatment); - - if (pumpId_old != 0) { - oldTreatment.pumpId = pumpId_old; - } - - if (oldTreatment.pumpId != 0 && oldTreatment.source != Source.PUMP) { - oldTreatment.source = Source.PUMP; - } - - oldTreatment.isSMB = isSMB; - - } else { - oldTreatment.copyFrom(newTreatment); - } - - aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [newAfterChange={}]", oldTreatment.toString()); - - } - - public Treatment getRecord(long pumpId, long date) { Treatment record = null; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index f83e522b30..f273015441 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -75,6 +75,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final ActivePluginProvider activePlugin; + private final NSUpload nsUpload; private final FabricPrivacy fabricPrivacy; private final DateUtil dateUtil; @@ -101,6 +102,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface SP sp, ProfileFunction profileFunction, ActivePluginProvider activePlugin, + NSUpload nsUpload, FabricPrivacy fabricPrivacy, DateUtil dateUtil ) { @@ -122,6 +124,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface this.activePlugin = activePlugin; this.fabricPrivacy = fabricPrivacy; this.dateUtil = dateUtil; + this.nsUpload = nsUpload; } @Override @@ -293,7 +296,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface /** * Returns all Treatments after specified timestamp. Also returns invalid entries (required to - * map "Fill Canulla" entries to history (and not to add double bolus for it) + * map "Fill Canula" entries to history (and not to add double bolus for it) * * @param fromTimestamp * @return @@ -304,13 +307,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface long time = System.currentTimeMillis(); synchronized (treatments) { - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); +// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); for (Treatment t : treatments) { if (t.date <= time && t.date >= fromTimestamp) in5minback.add(t); } - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); +// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); return in5minback; } } @@ -553,13 +556,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (newRecordCreated) { if (extendedBolus.durationInMinutes == 0) { if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) - NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); + nsUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); else - NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); + nsUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); } else if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) - NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); + nsUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); else - NSUpload.uploadExtendedBolus(extendedBolus); + nsUpload.uploadExtendedBolus(extendedBolus); } return newRecordCreated; } @@ -586,11 +589,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(tempBasal); if (newRecordCreated) { if (tempBasal.durationInMinutes == 0) - NSUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId); + nsUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId); else if (tempBasal.isAbsolute) - NSUpload.uploadTempBasalStartAbsolute(tempBasal, null); + nsUpload.uploadTempBasalStartAbsolute(tempBasal, null); else - NSUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date)); + nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date)); } return newRecordCreated; } @@ -641,7 +644,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface //log.debug("Adding new Treatment record" + carbsTreatment); } if (newRecordCreated && detailedBolusInfo.isValid) - NSUpload.uploadTreatmentRecord(detailedBolusInfo); + nsUpload.uploadTreatmentRecord(detailedBolusInfo); if (!allowUpdate && !creatOrUpdateResult.success) { getAapsLogger().error("Treatment could not be added to DB", new Exception()); @@ -710,7 +713,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public void addToHistoryTempTarget(TempTarget tempTarget) { //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); MainApp.getDbHelper().createOrUpdate(tempTarget); - NSUpload.uploadTempTarget(tempTarget, profileFunction); + nsUpload.uploadTempTarget(tempTarget, profileFunction); } @Override @@ -733,7 +736,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING)); MainApp.getDbHelper().createOrUpdate(profileSwitch); - NSUpload.uploadProfileSwitch(profileSwitch); + nsUpload.uploadProfileSwitch(profileSwitch); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt index 63574ea8d2..e6d2f02883 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt @@ -42,6 +42,8 @@ class TreatmentsBolusFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -68,9 +70,9 @@ class TreatmentsBolusFragment : DaggerFragment() { val futureTreatments = treatmentsPlugin.service.getTreatmentDataFromTime(DateUtil.now() + 1000, true) for (treatment in futureTreatments) { if (NSUpload.isIdValid(treatment._id)) - NSUpload.removeCareportalEntryFromNS(treatment._id) + nsUpload.removeCareportalEntryFromNS(treatment._id) else - UploadQueue.removeID("dbAdd", treatment._id) + uploadQueue.removeID("dbAdd", treatment._id) treatmentsPlugin.service.delete(treatment) } updateGui() @@ -166,9 +168,9 @@ class TreatmentsBolusFragment : DaggerFragment() { treatmentsPlugin.service.update(treatment) } else { if (NSUpload.isIdValid(treatment._id)) - NSUpload.removeCareportalEntryFromNS(treatment._id) + nsUpload.removeCareportalEntryFromNS(treatment._id) else - UploadQueue.removeID("dbAdd", treatment._id) + uploadQueue.removeID("dbAdd", treatment._id) treatmentsPlugin.service.delete(treatment) } updateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt index 9307238211..26165ec661 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt @@ -38,6 +38,8 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var translator: Translator + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -66,9 +68,9 @@ class TreatmentsCareportalFragment : DaggerFragment() { val careportalEvent = events[i] if (careportalEvent.json.contains(resourceHelper.gs(R.string.androidaps_start))) { if (NSUpload.isIdValid(careportalEvent._id)) - NSUpload.removeCareportalEntryFromNS(careportalEvent._id) + nsUpload.removeCareportalEntryFromNS(careportalEvent._id) else - UploadQueue.removeID("dbAdd", careportalEvent._id) + uploadQueue.removeID("dbAdd", careportalEvent._id) MainApp.getDbHelper().delete(careportalEvent) } } @@ -131,14 +133,14 @@ class TreatmentsCareportalFragment : DaggerFragment() { remove.setOnClickListener { v: View -> val careportalEvent = v.tag as CareportalEvent activity?.let { activity -> - val text = resourceHelper.gs(R.string.careportal_newnstreatment_eventtype) + ": " + translator.translate(careportalEvent.eventType) + "\n" + + val text = resourceHelper.gs(R.string.eventtype) + ": " + translator.translate(careportalEvent.eventType) + "\n" + resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + careportalEvent.notes + "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(careportalEvent.date) OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { if (NSUpload.isIdValid(careportalEvent._id)) - NSUpload.removeCareportalEntryFromNS(careportalEvent._id) + nsUpload.removeCareportalEntryFromNS(careportalEvent._id) else - UploadQueue.removeID("dbAdd", careportalEvent._id) + uploadQueue.removeID("dbAdd", careportalEvent._id) MainApp.getDbHelper().delete(careportalEvent) }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt index d2dcd632ea..91e3b098fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt @@ -40,6 +40,8 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -116,8 +118,8 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.date)} """.trimIndent(), DialogInterface.OnClickListener { _: DialogInterface, _: Int -> val id = extendedBolus._id - if (NSUpload.isIdValid(id)) NSUpload.removeCareportalEntryFromNS(id) - else UploadQueue.removeID("dbAdd", id) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(extendedBolus) }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt index 77934e304c..886c0ec34e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt @@ -43,6 +43,8 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -135,8 +137,8 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { resourceHelper.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { val id = profileSwitch._id - if (NSUpload.isIdValid(id)) NSUpload.removeCareportalEntryFromNS(id) - else UploadQueue.removeID("dbAdd", id) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(profileSwitch) }) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java index 7df7db72be..980e9efe7d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java @@ -47,6 +47,8 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { @Inject RxBusWrapper rxBus; @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; + @Inject NSUpload nsUpload; + @Inject UploadQueue uploadQueue; @Inject FabricPrivacy fabricPrivacy; @Inject DateUtil dateUtil; @@ -146,9 +148,9 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { (dialog, id) -> { final String _id = tempTarget._id; if (NSUpload.isIdValid(_id)) { - NSUpload.removeCareportalEntryFromNS(_id); + nsUpload.removeCareportalEntryFromNS(_id); } else { - UploadQueue.removeID("dbAdd", _id); + uploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(tempTarget); }, null); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt index 4ff6b15950..fed0ba1137 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -44,6 +44,8 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -160,13 +162,13 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { context?.let { showConfirmation(it, resourceHelper.gs(R.string.removerecord), """ - ${resourceHelper.gs(R.string.pump_tempbasal_label)}: ${tempBasal.toStringFull()} + ${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull()} ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.date)} """.trimIndent(), DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> val id = tempBasal._id - if (NSUpload.isIdValid(id)) NSUpload.removeCareportalEntryFromNS(id) - else UploadQueue.removeID("dbAdd", id) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(tempBasal) }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index 15f1eaa9f8..bbc541c7b9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -375,12 +375,14 @@ class CommandQueue @Inject constructor( callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() return false } + /* this is breaking setting of profile at all if not engineering mode if (!buildHelper.isEngineeringModeOrRelease()) { val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT) rxBus.send(EventNewNotification(notification)) callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run() return false } + */ // Compare with pump limits val basalValues = profile.basalValues for (basalValue in basalValues) { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt index a3dda44325..b6705ac733 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -8,15 +8,16 @@ import android.content.Intent import android.os.PowerManager import android.os.SystemClock import dagger.android.DaggerBroadcastReceiver +import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.commands.Command @@ -39,6 +40,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var receiverStatusStore: ReceiverStatusStore @Inject lateinit var config: Config + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var dateUtil: DateUtil companion object { @@ -108,7 +110,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { else if (DateUtil.isOlderThan(activePlugin.activeAPS.lastAPSRun, 5)) shouldUploadStatus = true if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY) && shouldUploadStatus) { lastIobUpload = DateUtil.now() - NSUpload.uploadDeviceStatus(loopPlugin, iobCobCalculatorPlugin, profileFunction, activePlugin.activePump, receiverStatusStore) + nsUpload.uploadDeviceStatus(loopPlugin, iobCobCalculatorPlugin, profileFunction, activePlugin.activePump, receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION) } } diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java index 83891275a2..cf1833e892 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.BundleLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; @@ -42,6 +43,7 @@ public class DataService extends DaggerIntentService { @Inject AAPSLogger aapsLogger; @Inject SP sp; @Inject RxBusWrapper rxBus; + @Inject NSUpload nsUpload; @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; @Inject DexcomPlugin dexcomPlugin; @Inject EversensePlugin eversensePlugin; @@ -210,7 +212,7 @@ public class DataService extends DaggerIntentService { } else if (eventType.equals(CareportalEvent.COMBOBOLUS)) { MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); } else if (eventType.equals(CareportalEvent.PROFILESWITCH)) { - MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePlugin, json); + MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePlugin, nsUpload, json); } else if (eventType.equals(CareportalEvent.SITECHANGE) || eventType.equals(CareportalEvent.INSULINCHANGE) || eventType.equals(CareportalEvent.SENSORCHANGE) || diff --git a/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt b/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt index 01cc925942..e78b112615 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.utils import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.utils.extensions.toHex import org.spongycastle.util.encoders.Base64 import java.nio.ByteBuffer import java.security.MessageDigest @@ -16,42 +17,10 @@ import javax.crypto.spec.SecretKeySpec import javax.inject.Inject import javax.inject.Singleton -private val HEX_CHARS = "0123456789abcdef" -private val HEX_CHARS_ARRAY = "0123456789abcdef".toCharArray() - -fun String.hexStringToByteArray() : ByteArray { - - val upperCased = this.toLowerCase() - val result = ByteArray(length / 2) - for (i in 0 until length step 2) { - val firstIndex = HEX_CHARS.indexOf(upperCased[i]); - val secondIndex = HEX_CHARS.indexOf(upperCased[i + 1]); - - val octet = firstIndex.shl(4).or(secondIndex) - result.set(i.shr(1), octet.toByte()) - } - - return result -} - -fun ByteArray.toHex() : String{ - val result = StringBuffer() - - forEach { - val octet = it.toInt() - val firstIndex = (octet and 0xF0).ushr(4) - val secondIndex = octet and 0x0F - result.append(HEX_CHARS_ARRAY[firstIndex]) - result.append(HEX_CHARS_ARRAY[secondIndex]) - } - - return result.toString() -} - @Singleton class CryptoUtil @Inject constructor( val aapsLogger: AAPSLogger -) { +) { companion object { private const val IV_LENGTH_BYTE = 12 @@ -71,26 +40,26 @@ class CryptoUtil @Inject constructor( } fun hmac256(str: String, secret: String): String? { - val sha256_HMAC = Mac.getInstance("HmacSHA256") + val sha256HMAC = Mac.getInstance("HmacSHA256") val secretKey = SecretKeySpec(secret.toByteArray(), "HmacSHA256") - sha256_HMAC.init(secretKey) - return sha256_HMAC.doFinal(str.toByteArray()).toHex() + sha256HMAC.init(secretKey) + return sha256HMAC.doFinal(str.toByteArray()).toHex() } - private fun prepCipherKey(passPhrase: String, salt:ByteArray, iterationCount:Int = PBKDF2_ITERATIONS, keyStrength:Int = AES_KEY_SIZE_BIT): SecretKeySpec { + private fun prepCipherKey(passPhrase: String, salt: ByteArray, iterationCount: Int = PBKDF2_ITERATIONS, keyStrength: Int = AES_KEY_SIZE_BIT): SecretKeySpec { val factory: SecretKeyFactory = SecretKeyFactory.getInstance("PBKDF2withHmacSHA1") val spec: KeySpec = PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength) val tmp: SecretKey = factory.generateSecret(spec) - return SecretKeySpec(tmp.getEncoded(), "AES") + return SecretKeySpec(tmp.encoded, "AES") } - fun mineSalt(len :Int = SALT_SIZE_BYTE): ByteArray { + fun mineSalt(len: Int = SALT_SIZE_BYTE): ByteArray { val salt = ByteArray(len) secureRandom.nextBytes(salt) return salt } - fun encrypt(passPhrase: String, salt:ByteArray, rawData: String ): String? { + fun encrypt(passPhrase: String, salt: ByteArray, rawData: String): String? { val iv: ByteArray? val encrypted: ByteArray? return try { @@ -107,12 +76,12 @@ class CryptoUtil @Inject constructor( String(Base64.encode(byteBuffer.array())) } catch (e: Exception) { lastException = e - aapsLogger.error("Encryption failed due to technical exception: ${e}") + aapsLogger.error("Encryption failed due to technical exception: $e") null } } - fun decrypt(passPhrase: String, salt:ByteArray, encryptedData: String): String? { + fun decrypt(passPhrase: String, salt: ByteArray, encryptedData: String): String? { val iv: ByteArray? val encrypted: ByteArray? return try { @@ -129,7 +98,7 @@ class CryptoUtil @Inject constructor( String(dec) } catch (e: Exception) { lastException = e - aapsLogger.error("Decryption failed due to technical exception: ${e}") + aapsLogger.error("Decryption failed due to technical exception: $e") null } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt index c9e2835ceb..bec9c0fa16 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt @@ -12,11 +12,12 @@ import javax.inject.Singleton @Singleton class HardLimits @Inject constructor( - val aapsLogger: AAPSLogger, - val rxBus: RxBusWrapper, - val sp: SP, - val resourceHelper: ResourceHelper, - val context: Context + private val aapsLogger: AAPSLogger, + private val rxBus: RxBusWrapper, + private val sp: SP, + private val resourceHelper: ResourceHelper, + private val context: Context, + private val nsUpload: NSUpload ) { val CHILD = 0 @@ -90,7 +91,7 @@ class HardLimits @Inject constructor( msg += ".\n" msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newvalue) aapsLogger.error(msg) - NSUpload.uploadError(msg) + nsUpload.uploadError(msg) ToastUtils.showToastInUiThread(context, rxBus, msg, R.raw.error) } return newvalue diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt index eff444aa6e..f5ac9d64ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt @@ -31,6 +31,7 @@ class LocalAlertUtils @Inject constructor( private val profileFunction: ProfileFunction, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val config: Config, + private val nsUpload: NSUpload, private val dateUtil: DateUtil ) { @@ -53,7 +54,7 @@ class LocalAlertUtils @Inject constructor( sp.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()) rxBus.send(EventNewNotification(n)) if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { - NSUpload.uploadError(n.text) + nsUpload.uploadError(n.text) } } if (!isStatusOutdated && !alarmTimeoutExpired) rxBus.send(EventDismissNotification(Notification.PUMP_UNREACHABLE)) @@ -101,7 +102,7 @@ class LocalAlertUtils @Inject constructor( sp.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()) rxBus.send(EventNewNotification(n)) if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { - NSUpload.uploadError(n.text) + nsUpload.uploadError(n.text) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java b/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java index cae1a3cde3..f09f562d25 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java @@ -30,8 +30,6 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; * Created by mike on 28.06.2016. */ public class NumberPickerVertical extends NumberPicker { - private static Logger log = StacktraceLoggerWrapper.getLogger(NumberPickerVertical.class); - public NumberPickerVertical(Context context) { super(context); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SP.java b/app/src/main/java/info/nightscout/androidaps/utils/SP.java deleted file mode 100644 index a6124acf10..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/SP.java +++ /dev/null @@ -1,50 +0,0 @@ -package info.nightscout.androidaps.utils; - -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import java.util.Map; - -import info.nightscout.androidaps.MainApp; - -/** - * Created by mike on 17.02.2017. - */ - -public class SP { - private static SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - - @Deprecated - static public Map getAll() { - return sharedPreferences.getAll(); - } - - @Deprecated - static public String getString(String key, String defaultValue) { - return sharedPreferences.getString(key, defaultValue); - } - - @Deprecated - static public boolean getBoolean(int resourceID, Boolean defaultValue) { - try { - return sharedPreferences.getBoolean(MainApp.gs(resourceID), defaultValue); - } catch (Exception e) { - return defaultValue; - } - } - - @Deprecated - static public void putString(int resourceID, String value) { - sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply(); - } - - @Deprecated - static public void putString(String key, String value) { - sharedPreferences.edit().putString(key, value).apply(); - } - - @Deprecated - static public void remove(String key) { - sharedPreferences.edit().remove(key).apply(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java b/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java index fa79caaf2b..098b90c5d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java @@ -2,21 +2,14 @@ package info.nightscout.androidaps.utils; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import info.nightscout.androidaps.MainApp; public class SPBackupAgent extends BackupAgentHelper { - // API 24 - //static final String PREFS = PreferenceManager.getDefaultSharedPreferencesName(MainApp.instance().getApplicationContext()); - static final String PREFS = MainApp.instance().getApplicationContext().getPackageName() + "_preferences"; - - static final String PREFS_BACKUP_KEY = "SP"; - @Override public void onCreate() { + // API 24 + final String PREFS = getApplicationContext().getPackageName() + "_preferences"; + final String PREFS_BACKUP_KEY = "SP"; SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS); addHelper(PREFS_BACKUP_KEY, helper); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt index 6ee23a85f5..028c63086e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt @@ -10,6 +10,7 @@ import androidx.core.app.TaskStackBuilder import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.NotificationHolderInterface import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject @@ -20,11 +21,11 @@ class NotificationHolder @Inject constructor( private val resourceHelper: ResourceHelper, private val context: Context, private val iconsProvider: IconsProvider -) { +) : NotificationHolderInterface { - val channelID = "AndroidAPS-Ongoing" - val notificationID = 4711 - var notification: Notification + override val channelID = "AndroidAPS-Ongoing" + override val notificationID = 4711 + override lateinit var notification: Notification init { val stackBuilder = TaskStackBuilder.create(context) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 6ee3024fc6..1e567dd94a 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.interfaces.ProfileFunction +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 @@ -32,8 +33,9 @@ class TddCalculator @Inject constructor( val activePlugin: ActivePluginProvider, val profileFunction: ProfileFunction, fabricPrivacy: FabricPrivacy, + nsUpload: NSUpload, private val dateUtil: DateUtil -) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy, dateUtil) { +) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil) { init { service = TreatmentService(injector) // plugin is not started diff --git a/app/src/main/res/drawable-hdpi/icon_local_savehdpi.png b/app/src/main/res/drawable-hdpi/icon_local_savehdpi.png deleted file mode 100644 index e5c1d5cedc..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_savehdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_activatexhdpi.png b/app/src/main/res/drawable-xhdpi/icon_local_activatexhdpi.png deleted file mode 100644 index 75e9af38ed..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_activatexhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_resetxhdpi.png b/app/src/main/res/drawable-xhdpi/icon_local_resetxhdpi.png deleted file mode 100644 index 2813cb448d..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_resetxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_savexhdpi.png b/app/src/main/res/drawable-xhdpi/icon_local_savexhdpi.png deleted file mode 100644 index 0cf81430cc..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_savexhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_activatexxhdpi.png b/app/src/main/res/drawable-xxhdpi/icon_local_activatexxhdpi.png deleted file mode 100644 index 600e6ee61c..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_activatexxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_savexxhdpi.png b/app/src/main/res/drawable-xxhdpi/icon_local_savexxhdpi.png deleted file mode 100644 index 20448e4bf9..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_savexxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_resetxxxhdpi.png b/app/src/main/res/drawable-xxxhdpi/icon_local_resetxxxhdpi.png deleted file mode 100644 index ec54479149..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_resetxxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_activatexxxhdpi.png b/app/src/main/res/drawable/icon_local_activate.png similarity index 100% rename from app/src/main/res/drawable-xxxhdpi/icon_local_activatexxxhdpi.png rename to app/src/main/res/drawable/icon_local_activate.png diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_resetxxhdpi.png b/app/src/main/res/drawable/icon_local_reset.png similarity index 100% rename from app/src/main/res/drawable-xxhdpi/icon_local_resetxxhdpi.png rename to app/src/main/res/drawable/icon_local_reset.png diff --git a/app/src/main/res/layout/actions_fragment.xml b/app/src/main/res/layout/actions_fragment.xml index 77a5ab00dd..0290c1cf8a 100644 --- a/app/src/main/res/layout/actions_fragment.xml +++ b/app/src/main/res/layout/actions_fragment.xml @@ -126,6 +126,13 @@ android:paddingEnd="15dp" android:text="@string/careportal" /> + + - + - + + + + app:layout_row="6" /> + app:layout_row="6" /> diff --git a/app/src/main/res/layout/careportal_newnstreatment_dialog.xml b/app/src/main/res/layout/careportal_newnstreatment_dialog.xml index 4251efd3a2..a501e70a77 100644 --- a/app/src/main/res/layout/careportal_newnstreatment_dialog.xml +++ b/app/src/main/res/layout/careportal_newnstreatment_dialog.xml @@ -233,7 +233,7 @@ - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout/dialog_tempbasal.xml b/app/src/main/res/layout/dialog_tempbasal.xml index c748960c33..e13d7fc872 100644 --- a/app/src/main/res/layout/dialog_tempbasal.xml +++ b/app/src/main/res/layout/dialog_tempbasal.xml @@ -24,7 +24,7 @@ diff --git a/app/src/main/res/layout/dialog_temptarget.xml b/app/src/main/res/layout/dialog_temptarget.xml index be4258ec5c..d03413a237 100644 --- a/app/src/main/res/layout/dialog_temptarget.xml +++ b/app/src/main/res/layout/dialog_temptarget.xml @@ -81,7 +81,7 @@ android:layout_gravity="center_vertical" android:width="120dp" android:padding="10dp" - android:text="@string/nsprofileview_target_label" + android:text="@string/target_label" android:textAppearance="@android:style/TextAppearance.Material.Small" android:textStyle="bold" /> diff --git a/app/src/main/res/layout/medtronic_fragment.xml b/app/src/main/res/layout/medtronic_fragment.xml index a67872fa5d..af16dd26cb 100644 --- a/app/src/main/res/layout/medtronic_fragment.xml +++ b/app/src/main/res/layout/medtronic_fragment.xml @@ -164,7 +164,7 @@ android:layout_weight="1.5" android:gravity="end" android:paddingRight="5dp" - android:text="@string/pump_battery_label" + android:text="@string/battery_label" android:textSize="14sp" /> + android:text="@string/pumphistory" />