From eef50c8290650ae844c095bdc7199ee90dd78286 Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 28 May 2021 00:17:37 +0200 Subject: [PATCH 01/91] Fix Cancel Extended Bolus if TBR emulation is disabled in insight preferences --- .../androidaps/plugins/pump/insight/LocalInsightPlugin.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 141f60a52a..ea06395622 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -1450,6 +1450,12 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); + if (!isFakingTempsByExtendedBoluses()) + pumpSync.syncStopExtendedBolusWithPumpId( + timestamp, + event.getEventPosition(), + PumpType.ACCU_CHEK_INSIGHT, + serialNumber()); } } From 330728299d2549f612e86e38735cdd2f68e6f913 Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 28 May 2021 08:56:58 +0200 Subject: [PATCH 02/91] Fix Extended Bolus in Overview --- .../androidaps/plugins/general/overview/OverviewData.kt | 2 +- .../androidaps/plugins/general/overview/OverviewFragment.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt index 11a1ff2203..4c4491e5b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt @@ -191,7 +191,7 @@ class OverviewData @Inject constructor( if (!extendedBolus.isInProgress(dateUtil)) { this@OverviewData.extendedBolus = null "" - } else if (activePlugin.activePump.isFakingTempsByExtendedBoluses) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate) + } else if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.rate) else "" } ?: "" 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 4ab51bfe5c..b387a74495 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 @@ -653,7 +653,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList OverviewData.Property.EXTENDED_BOLUS -> { binding.infoLayout.extendedBolus.text = overviewData.extendedBolusText - binding.infoLayout.extendedBolus.setOnClickListener { + binding.infoLayout.extendedLayout.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), overviewData.extendedBolusDialogText) } } binding.infoLayout.extendedLayout.visibility = (overviewData.extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility() From a06b799cd0b7871780b1b392ab25fa313ee68bb6 Mon Sep 17 00:00:00 2001 From: Philoul Date: Fri, 28 May 2021 22:07:01 +0200 Subject: [PATCH 03/91] Revert "Fix Cancel Extended Bolus if TBR emulation is disabled in insight preferences" This reverts commit eef50c82 --- .../androidaps/plugins/pump/insight/LocalInsightPlugin.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index ea06395622..141f60a52a 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -1450,12 +1450,6 @@ public class LocalInsightPlugin extends PumpPluginBase implements Pump, Constrai bolusID.getId(), PumpType.ACCU_CHEK_INSIGHT, serial); - if (!isFakingTempsByExtendedBoluses()) - pumpSync.syncStopExtendedBolusWithPumpId( - timestamp, - event.getEventPosition(), - PumpType.ACCU_CHEK_INSIGHT, - serialNumber()); } } From 9d29cafbe65b950f7f484af26fbfdfc98cf929c7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 29 May 2021 23:38:19 +0200 Subject: [PATCH 04/91] remove old db code --- .../info/nightscout/androidaps/MainApp.kt | 12 +- .../activities/MyPreferenceFragment.kt | 2 +- .../fragments/TreatmentsBolusCarbsFragment.kt | 2 +- .../fragments/TreatmentsCareportalFragment.kt | 2 +- .../TreatmentsProfileSwitchFragment.kt | 2 +- .../fragments/TreatmentsTempTargetFragment.kt | 2 +- .../fragments/TreatmentsUserEntryFragment.kt | 2 +- .../androidaps/db/DatabaseHelper.java | 296 ---------- .../androidaps/db/DatabaseHelperProvider.java | 84 --- .../nightscout/androidaps/db/OHQueueItem.kt | 2 - .../dependencyInjection/AppModule.kt | 18 +- .../dependencyInjection/DataClassesModule.kt | 5 - .../dependencyInjection/PluginsModule.kt | 10 - .../events/EventTreatmentUpdateGui.kt | 3 + .../plugins/aps/logger/LoggerCallback.kt | 2 +- .../configBuilder/ConfigBuilderFragment.kt | 22 +- .../configBuilder/ConfigBuilderPlugin.kt | 2 - .../plugins/configBuilder/PluginStore.kt | 16 - .../objectives/ObjectivesPlugin.kt | 24 +- .../general/maintenance/MaintenancePlugin.kt | 2 +- .../nsclient/services/NSClientService.kt | 4 +- .../general/openhumans/OHUploadWorker.kt | 6 +- .../general/openhumans/OpenHumansFragment.kt | 30 +- .../general/openhumans/OpenHumansUploader.kt | 89 ++- .../graphExtensions/TherapyEventDataPoint.kt | 26 +- .../profile/local/LocalProfileFragment.kt | 2 + .../plugins/treatments/TreatmentService.java | 540 ------------------ .../plugins/treatments/TreatmentsPlugin.java | 306 ---------- .../events/EventTreatmentUpdateGui.kt | 5 - .../utils/{ => ui}/NumberPickerVertical.kt | 3 +- .../utils/{ => ui}/SpinnerHelper.java | 2 +- .../utils/{ => ui}/TimeListEdit.java | 5 +- .../layout/timelistedit_element_vertical.xml | 4 +- app/src/main/res/values/strings.xml | 2 - .../androidaps/TestBaseWithProfile.kt | 1 - .../treatments/TreatmentsPluginTest.kt | 14 +- .../actions/ActionStartTempTargetTest.kt | 1 - .../plugins/pump/combo/ComboPluginTest.kt | 1 - .../nightscout/androidaps/data/Intervals.kt | 72 --- .../data/NonOverlappingIntervals.kt | 26 - .../androidaps/data/OverlappingIntervals.kt | 38 -- .../androidaps/data/ProfileIntervals.kt | 115 ---- .../androidaps/db/ExtendedBolus.java | 306 ---------- .../androidaps/db/InsightBolusID.java | 27 - .../androidaps/db/InsightHistoryOffset.java | 14 - .../androidaps/db/InsightPumpID.java | 24 - .../nightscout/androidaps/db/OHQueueItem.kt | 14 - .../info/nightscout/androidaps/db/Source.java | 24 - .../androidaps/db/TemporaryBasal.java | 370 ------------ .../nightscout/androidaps/db/Treatment.java | 280 --------- .../androidaps/{db => di}/StaticInjector.kt | 2 +- .../androidaps/interfaces/ActivePlugin.kt | 5 - .../interfaces/DatabaseHelperInterface.kt | 29 - .../androidaps/interfaces/Interval.kt | 20 - .../androidaps/interfaces/PluginType.kt | 2 +- .../interfaces/TreatmentServiceInterface.kt | 9 - .../interfaces/TreatmentsInterface.java | 29 - .../androidaps/interfaces/UpdateReturn.kt | 11 - .../androidaps/TestBaseWithProfile.kt | 7 +- .../data/NonOverlappingIntervalsTest.kt | 55 -- .../data/OverlappingIntervalsTest.kt | 58 -- .../androidaps/data/ProfileIntervalsTest.kt | 82 --- .../androidaps/data/TempTargetTest.kt | 86 --- .../androidaps/TestBaseWithProfile.kt | 1 - .../androidaps/danar/comm/MessageBase.java | 1 - .../androidaps/TestBaseWithProfile.kt | 1 - .../androidaps/TestBaseWithProfile.kt | 1 - .../pump/medtronic/MedtronicPumpPlugin.kt | 2 +- .../medtronic/data/MedtronicHistoryData.kt | 9 +- .../androidaps/db/OmnipodHistoryRecord.java | 0 .../omnipod/eros/OmnipodErosPumpPlugin.java | 8 +- .../eros/manager/AapsOmnipodErosManager.java | 25 +- .../service/RileyLinkOmnipodService.java | 2 - .../eros/ui/ErosPodHistoryActivity.java | 15 +- 74 files changed, 137 insertions(+), 3184 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTreatmentUpdateGui.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/treatments/events/EventTreatmentUpdateGui.kt rename app/src/main/java/info/nightscout/androidaps/utils/{ => ui}/NumberPickerVertical.kt (82%) rename app/src/main/java/info/nightscout/androidaps/utils/{ => ui}/SpinnerHelper.java (99%) rename app/src/main/java/info/nightscout/androidaps/utils/{ => ui}/TimeListEdit.java (98%) delete mode 100644 core/src/main/java/info/nightscout/androidaps/data/Intervals.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/InsightBolusID.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/InsightHistoryOffset.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/InsightPumpID.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/Source.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/db/Treatment.java rename core/src/main/java/info/nightscout/androidaps/{db => di}/StaticInjector.kt (95%) delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/Interval.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java delete mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/UpdateReturn.kt delete mode 100644 core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt delete mode 100644 core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt delete mode 100644 core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt delete mode 100644 core/src/test/java/info/nightscout/androidaps/data/TempTargetTest.kt rename {core => omnipod-common}/src/main/java/info/nightscout/androidaps/db/OmnipodHistoryRecord.java (100%) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.kt b/app/src/main/java/info/nightscout/androidaps/MainApp.kt index 9731bf37d6..8fb88a9963 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.kt @@ -6,7 +6,6 @@ import android.content.IntentFilter import android.net.ConnectivityManager import android.net.wifi.WifiManager import android.os.Build -import com.j256.ormlite.android.apptools.OpenHelperManager import dagger.android.AndroidInjector import dagger.android.DaggerApplication import info.nightscout.androidaps.database.AppRepository @@ -15,11 +14,10 @@ import info.nightscout.androidaps.database.entities.UserEntry import info.nightscout.androidaps.database.transactions.InsertIfNewByTimestampTherapyEventTransaction import info.nightscout.androidaps.database.transactions.VersionChangeTransaction import info.nightscout.androidaps.db.CompatDBHelper -import info.nightscout.androidaps.db.DatabaseHelper -import info.nightscout.androidaps.db.StaticInjector +import info.nightscout.androidaps.di.StaticInjector import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent -import info.nightscout.androidaps.interfaces.ConfigBuilder import info.nightscout.androidaps.interfaces.Config +import info.nightscout.androidaps.interfaces.ConfigBuilder import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -63,7 +61,6 @@ class MainApp : DaggerApplication() { super.onCreate() aapsLogger.debug("onCreate") update(this) - dbHelper = OpenHelperManager.getHelper(this, DatabaseHelper::class.java) var gitRemote: String? = BuildConfig.REMOTE var commitHash: String? = BuildConfig.HEAD @@ -134,9 +131,4 @@ class MainApp : DaggerApplication() { keepAliveManager.cancelAlarm(this) super.onTerminate() } - - companion object { - - lateinit var dbHelper: DatabaseHelper - } } \ No newline at end of file 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 048b9c0d73..e7ea847509 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -182,7 +182,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreferencesFromResourceIfEnabled(automationPlugin, rootKey) addPreferencesFromResourceIfEnabled(wearPlugin, rootKey) addPreferencesFromResourceIfEnabled(statusLinePlugin, rootKey) - addPreferencesFromResource(R.xml.pref_alerts, rootKey) // TODO not organized well + addPreferencesFromResource(R.xml.pref_alerts, rootKey) addPreferencesFromResource(R.xml.pref_datachoices, rootKey) addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey) addPreferencesFromResourceIfEnabled(openHumansUploader, rootKey) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt index 4b5dc48e2a..051c6ba212 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart -import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui +import info.nightscout.androidaps.events.EventTreatmentUpdateGui import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt index f3eb9e551f..e7c9fc480c 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart -import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui +import info.nightscout.androidaps.events.EventTreatmentUpdateGui import info.nightscout.androidaps.activities.fragments.TreatmentsCareportalFragment.RecyclerViewAdapter.TherapyEventsViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt index 151b37234f..846fa50ec6 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt @@ -29,7 +29,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged -import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui +import info.nightscout.androidaps.events.EventTreatmentUpdateGui import info.nightscout.androidaps.activities.fragments.TreatmentsProfileSwitchFragment.RecyclerProfileViewAdapter.ProfileSwitchViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt index 16e8a5ae32..ea87274914 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt @@ -28,7 +28,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart -import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui +import info.nightscout.androidaps.events.EventTreatmentUpdateGui import info.nightscout.androidaps.activities.fragments.TreatmentsTempTargetFragment.RecyclerViewAdapter.TempTargetsViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt index b0936580ae..a0b5d1b169 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.treatments.events.EventTreatmentUpdateGui +import info.nightscout.androidaps.events.EventTreatmentUpdateGui import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java deleted file mode 100644 index c323a475be..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ /dev/null @@ -1,296 +0,0 @@ -package info.nightscout.androidaps.db; - -import android.content.Context; -import android.database.DatabaseUtils; -import android.database.sqlite.SQLiteDatabase; - -import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; -import com.j256.ormlite.dao.CloseableIterator; -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.stmt.DeleteBuilder; -import com.j256.ormlite.stmt.PreparedQuery; -import com.j256.ormlite.stmt.QueryBuilder; -import com.j256.ormlite.stmt.Where; -import com.j256.ormlite.support.ConnectionSource; -import com.j256.ormlite.table.TableUtils; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import javax.inject.Inject; - -import info.nightscout.androidaps.events.EventRefreshOverview; -import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader; -import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; -import info.nightscout.androidaps.utils.DateUtil; - -/** - * This Helper contains all resource to provide a central DB management functionality. Only methods handling - * data-structure (and not the DB content) should be contained in here (meaning DDL and not SQL). - *

- * This class can safely be called from Services, but should not call Services to avoid circular dependencies. - * One major issue with this (right now) are the scheduled events, which are put into the service. Therefor all - * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service. - */ -public class DatabaseHelper extends OrmLiteSqliteOpenHelper { - @Inject AAPSLogger aapsLogger; - @Inject RxBusWrapper rxBus; - @Inject VirtualPumpPlugin virtualPumpPlugin; - @Inject OpenHumansUploader openHumansUploader; - @Inject ActivePlugin activePlugin; - @Inject DateUtil dateUtil; - - public static final String DATABASE_NAME = "AndroidAPSDb"; - - private static final int DATABASE_VERSION = 13; - - public static Long earliestDataChange = null; - - private int oldVersion = 0; - private int newVersion = 0; - - 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); - } - - @Override - public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { - try { - aapsLogger.info(LTag.DATABASE, "onCreate"); - TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); - TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); - } catch (SQLException e) { - aapsLogger.error("Can't create database", e); - throw new RuntimeException(e); - } - } - - @Override - public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { - try { - this.oldVersion = oldVersion; - this.newVersion = newVersion; - - if (oldVersion < 7) { - aapsLogger.info(LTag.DATABASE, "onUpgrade"); - onCreate(database, connectionSource); - } - TableUtils.createTableIfNotExists(connectionSource, OHQueueItem.class); - } catch (SQLException e) { - aapsLogger.error("Can't drop databases", e); - throw new RuntimeException(e); - } - } - - @Override - public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { - aapsLogger.info(LTag.DATABASE, "Do nothing for downgrading..."); - aapsLogger.info(LTag.DATABASE, "oldVersion: {}, newVersion: {}", oldVersion, newVersion); - } - - public int getOldVersion() { - return oldVersion; - } - - public int getNewVersion() { - return newVersion; - } - - public long size(String database) { - return DatabaseUtils.queryNumEntries(getReadableDatabase(), database); - } - - // --------------------- DB resets --------------------- - - public void resetDatabases() { - try { - TableUtils.dropTable(connectionSource, OmnipodHistoryRecord.class, true); - TableUtils.createTableIfNotExists(connectionSource, OmnipodHistoryRecord.class); - updateEarliestDataChange(0); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - virtualPumpPlugin.setFakingStatus(true); - new java.util.Timer().schedule( - new java.util.TimerTask() { - @Override - public void run() { - rxBus.send(new EventRefreshOverview("resetDatabases", false)); - } - }, - 3000 - ); - } - - // ------------------ getDao ------------------------------------------- - - private Dao getDaoPodHistory() throws SQLException { - return getDao(OmnipodHistoryRecord.class); - } - - private Dao getDaoOpenHumansQueue() throws SQLException { - return getDao(OHQueueItem.class); - } - - public static void updateEarliestDataChange(long newDate) { - if (earliestDataChange == null) { - earliestDataChange = newDate; - return; - } - if (newDate < earliestDataChange) { - earliestDataChange = newDate; - } - } - - // ---------------- Food handling --------------- - - // ---------------- PodHistory handling --------------- - - public void createOrUpdate(OmnipodHistoryRecord omnipodHistoryRecord) { - try { - getDaoPodHistory().createOrUpdate(omnipodHistoryRecord); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public List getAllOmnipodHistoryRecordsFromTimeStamp(long from, boolean ascending) { - try { - Dao daoPodHistory = getDaoPodHistory(); - List podHistories; - QueryBuilder queryBuilder = daoPodHistory.queryBuilder(); - queryBuilder.orderBy("date", ascending); - //queryBuilder.limit(100L); - Where where = queryBuilder.where(); - where.ge("date", from); - PreparedQuery preparedQuery = queryBuilder.prepare(); - podHistories = daoPodHistory.query(preparedQuery); - return podHistories; - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return new ArrayList<>(); - } - - public OmnipodHistoryRecord findOmnipodHistoryRecordByPumpId(long pumpId) { - try { - Dao daoPodHistory = getDaoPodHistory(); - QueryBuilder queryBuilder = daoPodHistory.queryBuilder(); - queryBuilder.orderBy("date", false); - Where where = queryBuilder.where(); - where.eq("pumpId", pumpId); - PreparedQuery preparedQuery = queryBuilder.prepare(); - return daoPodHistory.queryForFirst(preparedQuery); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - -/* - TODO implement again for database branch // Copied from xDrip+ - String calculateDirection(BgReading bgReading) { - // Rework to get bgreaings from internal DB and calculate on that base - - List bgReadingsList = MainApp.getDbHelper().getAllBgreadingsDataFromTime(bgReading.date - T.mins(10).msecs(), false); - if (bgReadingsList == null || bgReadingsList.size() < 2) - return "NONE"; - BgReading current = bgReadingsList.get(1); - BgReading previous = bgReadingsList.get(0); - - if (bgReadingsList.get(1).date < bgReadingsList.get(0).date) { - current = bgReadingsList.get(0); - previous = bgReadingsList.get(1); - } - - double slope; - - // Avoid division by 0 - if (current.date == previous.date) - slope = 0; - else - slope = (previous.value - current.value) / (previous.date - current.date); - -// aapsLogger.error(LTag.GLUCOSE, "Slope is :" + slope + " delta " + (previous.value - current.value) + " date difference " + (current.date - previous.date)); - - double slope_by_minute = slope * 60000; - String arrow = "NONE"; - - if (slope_by_minute <= (-3.5)) { - arrow = "DoubleDown"; - } else if (slope_by_minute <= (-2)) { - arrow = "SingleDown"; - } else if (slope_by_minute <= (-1)) { - arrow = "FortyFiveDown"; - } else if (slope_by_minute <= (1)) { - arrow = "Flat"; - } else if (slope_by_minute <= (2)) { - arrow = "FortyFiveUp"; - } else if (slope_by_minute <= (3.5)) { - arrow = "SingleUp"; - } else if (slope_by_minute <= (40)) { - arrow = "DoubleUp"; - } -// aapsLogger.error(LTag.GLUCOSE, "Direction set to: " + arrow); - return arrow; - } -*/ - // ---------------- Open Humans Queue handling --------------- - - public void clearOpenHumansQueue() { - try { - TableUtils.clearTable(connectionSource, OHQueueItem.class); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public void createOrUpdate(OHQueueItem item) { - try { - getDaoOpenHumansQueue().createOrUpdate(item); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public void removeAllOHQueueItemsWithIdSmallerThan(long id) { - try { - DeleteBuilder deleteBuilder = getDaoOpenHumansQueue().deleteBuilder(); - deleteBuilder.where().le("id", id); - deleteBuilder.delete(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - - public List getAllOHQueueItems(Long maxEntries) { - try { - return getDaoOpenHumansQueue() - .queryBuilder() - .orderBy("id", true) - .limit(maxEntries) - .query(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return Collections.emptyList(); - } - - public long getOHQueueSize() { - try { - return getDaoOpenHumansQueue().countOf(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return 0L; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java deleted file mode 100644 index da0b2479cf..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java +++ /dev/null @@ -1,84 +0,0 @@ -package info.nightscout.androidaps.db; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.j256.ormlite.dao.CloseableIterator; - -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; - -@Deprecated -@Singleton -public class DatabaseHelperProvider implements DatabaseHelperInterface { - - @Inject DatabaseHelperProvider() { - } - - @Override public void createOrUpdate(@NonNull OmnipodHistoryRecord record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - - @Override public boolean createOrUpdate(@NonNull TemporaryBasal tempBasal) { -// return MainApp.Companion.getDbHelper().createOrUpdate(tempBasal); - return false; - } - - @Nullable @Override public TemporaryBasal findTempBasalByPumpId(long id) { -// return MainApp.Companion.getDbHelper().findTempBasalByPumpId(id); - return null; - } - - @Deprecated - @NonNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { -// return MainApp.Companion.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); - return null; - } - - @NonNull @Override public List getAllOmnipodHistoryRecordsFromTimestamp(long timestamp, boolean ascending) { - return MainApp.Companion.getDbHelper().getAllOmnipodHistoryRecordsFromTimeStamp(timestamp, ascending); - } - - @Nullable @Override public OmnipodHistoryRecord findOmnipodHistoryRecordByPumpId(long pumpId) { - return MainApp.Companion.getDbHelper().findOmnipodHistoryRecordByPumpId(pumpId); - } - - @Override public void delete(@NonNull ExtendedBolus extendedBolus) { -// MainApp.Companion.getDbHelper().delete(extendedBolus); - } - - @Nullable @Override public ExtendedBolus getExtendedBolusByPumpId(long pumpId) { -// return MainApp.Companion.getDbHelper().getExtendedBolusByPumpId(pumpId); - return null; - } - - @Override public void resetDatabases() { - MainApp.Companion.getDbHelper().resetDatabases(); - } - - @Override public void createOrUpdate(@NonNull OHQueueItem record) { - MainApp.Companion.getDbHelper().createOrUpdate(record); - } - - @NonNull @Override public List getAllOHQueueItems(long maxEntries) { - return MainApp.Companion.getDbHelper().getAllOHQueueItems(maxEntries); - } - - @Override public long getOHQueueSize() { - return MainApp.Companion.getDbHelper().getOHQueueSize(); - } - - @Override public void clearOpenHumansQueue() { - MainApp.Companion.getDbHelper().clearOpenHumansQueue(); - } - - @Override public void removeAllOHQueueItemsWithIdSmallerThan(long id) { - MainApp.Companion.getDbHelper().removeAllOHQueueItemsWithIdSmallerThan(id); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt b/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt deleted file mode 100644 index 600a9f0823..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt +++ /dev/null @@ -1,2 +0,0 @@ -package info.nightscout.androidaps.db - 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 639472c4ff..da8551af0b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -8,7 +8,6 @@ import dagger.Provides import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.database.AppRepository -import info.nightscout.androidaps.db.DatabaseHelperProvider import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin @@ -20,7 +19,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.DataSyncSelectorImple import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.pump.PumpSyncImplementation -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.androidNotification.NotificationHolderImpl @@ -56,9 +54,7 @@ open class AppModule { @Provides @Singleton - fun provideStorage(): Storage { - return FileStorage() - } + fun provideStorage(): Storage = FileStorage() @Provides @Singleton @@ -66,9 +62,8 @@ open class AppModule { @Provides @Singleton - fun provideProfileFunction(aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePlugin, repository: AppRepository, dateUtil: DateUtil): ProfileFunction { - return ProfileFunctionImplementation(aapsLogger, sp, resourceHelper, activePlugin, repository, dateUtil) - } + fun provideProfileFunction(aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePlugin, repository: AppRepository, dateUtil: DateUtil): ProfileFunction = + ProfileFunctionImplementation(aapsLogger, sp, resourceHelper, activePlugin, repository, dateUtil) @Module interface AppBindings { @@ -79,11 +74,7 @@ open class AppModule { @Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider @Binds fun bindConfigInterface(config: ConfigImpl): Config - @Binds - fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder - @Binds fun bindTreatmentsInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface - - @Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface + @Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilder @Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolderImpl): NotificationHolder @Binds fun bindImportExportPrefsInterface(importExportPrefs: ImportExportPrefsImpl): ImportExportPrefs @Binds fun bindIconsProviderInterface(iconsProvider: IconsProviderImplementation): IconsProvider @@ -93,7 +84,6 @@ open class AppModule { @Binds fun bindDataSyncSelector(dataSyncSelectorImplementation: DataSyncSelectorImplementation): DataSyncSelector @Binds fun bindPumpSync(pumpSyncImplementation: PumpSyncImplementation): PumpSync - } } 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 c222f2de55..b9ce13a5de 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt @@ -2,9 +2,7 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus -import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @@ -14,9 +12,6 @@ abstract class DataClassesModule { @ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus - @ContributesAndroidInjector abstract fun databaseHelperInjector(): DatabaseHelper - @ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService - @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry } \ No newline at end of file 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 184e0cdbc1..d0335c03ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -25,7 +25,6 @@ import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastP import info.nightscout.androidaps.plugins.general.food.FoodPlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin -import info.nightscout.androidaps.plugins.general.openhumans.OpenHumansUploader import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin @@ -40,14 +39,11 @@ import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin 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.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin import info.nightscout.androidaps.plugins.source.* -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import javax.inject.Qualifier @Module @@ -203,12 +199,6 @@ abstract class PluginsModule { @IntKey(250) abstract fun bindAutomationPlugin(plugin: AutomationPlugin): PluginBase - @Binds - @AllConfigs - @IntoMap - @IntKey(260) - abstract fun bindTreatmentsPlugin(plugin: TreatmentsPlugin): PluginBase - @Binds @AllConfigs @IntoMap diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentUpdateGui.kt new file mode 100644 index 0000000000..4a32b3c659 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentUpdateGui.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventTreatmentUpdateGui : EventUpdateGui() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.kt index c1b4f076d4..eb21e33535 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.aps.logger -import info.nightscout.androidaps.db.StaticInjector +import info.nightscout.androidaps.di.StaticInjector import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import org.mozilla.javascript.ScriptableObject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 36c00a74e6..74bbac3d1d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -114,7 +114,6 @@ class ConfigBuilderFragment : DaggerFragment() { createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP)) createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInList(PluginType.CONSTRAINTS)) } - createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, activePlugin.getSpecificPluginsVisibleInList(PluginType.TREATMENT)) createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, activePlugin.getSpecificPluginsVisibleInList(PluginType.GENERAL)) } @@ -139,22 +138,15 @@ class ConfigBuilderFragment : DaggerFragment() { @Suppress("InflateParams") val baseView: LinearLayout = fragment.layoutInflater.inflate(R.layout.configbuilder_single_plugin, null) as LinearLayout - private val enabledExclusive: RadioButton - private val enabledInclusive: CheckBox - private val pluginIcon: ImageView - private val pluginName: TextView - private val pluginDescription: TextView - private val pluginPreferences: ImageButton - private val pluginVisibility: CheckBox + private val enabledExclusive: RadioButton = baseView.findViewById(R.id.plugin_enabled_exclusive) + private val enabledInclusive: CheckBox = baseView.findViewById(R.id.plugin_enabled_inclusive) + private val pluginIcon: ImageView = baseView.findViewById(R.id.plugin_icon) + private val pluginName: TextView = baseView.findViewById(R.id.plugin_name) + private val pluginDescription: TextView = baseView.findViewById(R.id.plugin_description) + private val pluginPreferences: ImageButton = baseView.findViewById(R.id.plugin_preferences) + private val pluginVisibility: CheckBox = baseView.findViewById(R.id.plugin_visibility) init { - enabledExclusive = baseView.findViewById(R.id.plugin_enabled_exclusive) - enabledInclusive = baseView.findViewById(R.id.plugin_enabled_inclusive) - pluginIcon = baseView.findViewById(R.id.plugin_icon) - pluginName = baseView.findViewById(R.id.plugin_name) - pluginDescription = baseView.findViewById(R.id.plugin_description) - pluginPreferences = baseView.findViewById(R.id.plugin_preferences) - pluginVisibility = baseView.findViewById(R.id.plugin_visibility) pluginVisibility.setOnClickListener { plugin.setFragmentVisible(pluginType, pluginVisibility.isChecked) 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 3b0ab58075..8d57e4f789 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 @@ -120,7 +120,6 @@ class ConfigBuilderPlugin @Inject constructor( for (p in activePlugin.getPluginsList()) { aapsLogger.debug(LTag.CONFIGBUILDER, p.name + ":" + (if (p.isEnabled(PluginType.GENERAL)) " GENERAL" else "") + - (if (p.isEnabled(PluginType.TREATMENT)) " TREATMENT" else "") + (if (p.isEnabled(PluginType.SENSITIVITY)) " SENSITIVITY" else "") + (if (p.isEnabled(PluginType.PROFILE)) " PROFILE" else "") + (if (p.isEnabled(PluginType.APS)) " APS" else "") + @@ -185,7 +184,6 @@ class ConfigBuilderPlugin @Inject constructor( PluginType.APS -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(APS::class.java) PluginType.PROFILE -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(ProfileSource::class.java) PluginType.BGSOURCE -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(BgSource::class.java) - PluginType.TREATMENT -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(TreatmentsInterface::class.java) PluginType.PUMP -> pluginsInCategory = activePlugin.getSpecificPluginsListByInterface(Pump::class.java) else -> { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt index 0f6029064b..42281c32c3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.configBuilder -import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -21,7 +20,6 @@ class PluginStore @Inject constructor( private var activeAPSStore: APS? = null private var activeInsulinStore: Insulin? = null private var activeSensitivityStore: Sensitivity? = null - private var activeTreatmentsStore: TreatmentsInterface? = null fun loadDefaults() { verifySelectionInCategories() @@ -121,16 +119,6 @@ class PluginStore @Inject constructor( aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting PumpInterface") } setFragmentVisibilities((activePumpStore as PluginBase).name, pluginsInCategory, PluginType.PUMP) - - // PluginType.TREATMENT - pluginsInCategory = getSpecificPluginsList(PluginType.TREATMENT) - activeTreatmentsStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.TREATMENT) as TreatmentsInterface? - if (activeTreatmentsStore == null) { - activeTreatmentsStore = getDefaultPlugin(PluginType.TREATMENT) as TreatmentsInterface - (activeTreatmentsStore as PluginBase).setPluginEnabled(PluginType.TREATMENT, true) - aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting PumpInterface") - } - setFragmentVisibilities((activeTreatmentsStore as PluginBase).name, pluginsInCategory, PluginType.TREATMENT) } private fun setFragmentVisibilities(activePluginName: String, pluginsInCategory: ArrayList, @@ -175,10 +163,6 @@ class PluginStore @Inject constructor( get() = activeSensitivityStore ?: checkNotNull(activeSensitivityStore) { "No sensitivity selected" } - override val activeTreatments: TreatmentsInterface - get() = activeTreatmentsStore - ?: checkNotNull(activeTreatmentsStore) { "No treatments selected" } - override val activeOverview: Overview get() = getSpecificPluginsListByInterface(Overview::class.java).first() as Overview diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index 2e1061ff7b..3368f86919 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -45,6 +45,7 @@ class ObjectivesPlugin @Inject constructor( var objectives: MutableList = ArrayList() companion object { + const val FIRST_OBJECTIVE = 0 @Suppress("unused") const val USAGE_OBJECTIVE = 1 @Suppress("unused") const val EXAM_OBJECTIVE = 2 @@ -60,7 +61,6 @@ class ObjectivesPlugin @Inject constructor( public override fun onStart() { super.onStart() - convertSP() setupObjectives() } @@ -68,26 +68,6 @@ class ObjectivesPlugin @Inject constructor( return activePlugin.activePump.pumpDescription.isTempBasalCapable } - // convert 2.3 SP version - private fun convertSP() { - doConvertSP(0, "config") - doConvertSP(1, "openloop") - doConvertSP(2, "maxbasal") - doConvertSP(3, "maxiobzero") - doConvertSP(4, "maxiob") - doConvertSP(5, "autosens") - doConvertSP(6, "ama") - doConvertSP(7, "smb") - } - - private fun doConvertSP(number: Int, name: String) { - if (!sp.contains("Objectives_" + name + "_started")) { - sp.putLong("Objectives_" + name + "_started", sp.getLong("Objectives" + number + "started", 0L)) - sp.putLong("Objectives_" + name + "_accomplished", sp.getLong("Objectives" + number + "accomplished", 0L)) - } - // TODO: we can remove Objectives1accomplished sometimes later - } - private fun setupObjectives() { objectives.clear() objectives.add(Objective0(injector)) @@ -125,7 +105,7 @@ class ObjectivesPlugin @Inject constructor( val requestCode = sp.getString(R.string.key_objectives_request_code, "") var url = sp.getString(R.string.key_nsclientinternal_url, "").lowercase(Locale.getDefault()) if (!url.endsWith("/")) url = "$url/" - @Suppress("DEPRECATION") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString() + @Suppress("DEPRECATION", "UnstableApiUsage") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString() if (request.equals(hashNS.substring(0, 10), ignoreCase = true)) { sp.putLong("Objectives_" + "openloop" + "_started", dateUtil.now()) sp.putLong("Objectives_" + "openloop" + "_accomplished", dateUtil.now()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index 20bdfa269a..571cd19656 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -72,7 +72,7 @@ class MaintenancePlugin @Inject constructor( } Arrays.sort(files) { f1: File, f2: File -> f1.name.compareTo(f2.name) } var delFiles = listOf(*files) - val amount = sp.getInt(R.string.key_logshipper_amount, 2) + val amount = sp.getInt(R.string.key_logshipper_amount, 5) val keepIndex = amount - 1 if (keepIndex < delFiles.size) { delFiles = delFiles.subList(keepIndex, delFiles.size) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt index 6510abb76a..339d2ed0a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt @@ -16,7 +16,6 @@ import info.nightscout.androidaps.events.EventConfigBuilderChange import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.DataSyncSelector -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -71,7 +70,6 @@ class NSClientService : DaggerService() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var nsSettingsStatus: NSSettingsStatus @Inject lateinit var nsDeviceStatus: NSDeviceStatus - @Inject lateinit var databaseHelper: DatabaseHelperInterface @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var sp: SP @@ -199,7 +197,7 @@ class NSClientService : DaggerService() { .build()) } - fun processAuthAck(ack: NSAuthAck) { + private fun processAuthAck(ack: NSAuthAck) { var connectionStatus = "Authenticated (" if (ack.read) connectionStatus += "R" if (ack.write) connectionStatus += "W" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OHUploadWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OHUploadWorker.kt index f6d5dca118..16c9dddec6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OHUploadWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OHUploadWorker.kt @@ -29,7 +29,9 @@ class OHUploadWorker(context: Context, workerParameters: WorkerParameters) lateinit var resourceHelper: ResourceHelper @kotlin.ExperimentalStdlibApi - override fun createWork(): Single = Single.defer { + override fun createWork(): Single =Single.just(Result.success()) +/* + = Single.defer { // Here we inject every time we create work // We could build our own WorkerFactory with dagger but this will create conflicts with other Workers @@ -50,7 +52,7 @@ class OHUploadWorker(context: Context, workerParameters: WorkerParameters) Single.just(Result.retry()) } } - +*/ private fun createForegroundInfo(): ForegroundInfo { val title = resourceHelper.gs(info.nightscout.androidaps.R.string.open_humans) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt index e6d26b1bb9..9178e8aca8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansFragment.kt @@ -11,7 +11,6 @@ import androidx.work.WorkManager import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.events.Event -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -38,24 +37,23 @@ class OpenHumansFragment : DaggerFragment() { @Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var aapsSchedulers: AapsSchedulers - @Inject lateinit var databaseHelper: DatabaseHelperInterface override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - compositeDisposable += Single.fromCallable { databaseHelper.getOHQueueSize() } - .subscribeOn(aapsSchedulers.io) - .repeatWhen { - rxBus.toObservable(UpdateViewEvent::class.java) - .cast(Any::class.java) - .mergeWith(rxBus.toObservable(UpdateQueueEvent::class.java) - .throttleLatest(5, TimeUnit.SECONDS)) - .toFlowable(BackpressureStrategy.LATEST) - } - .observeOn(aapsSchedulers.main) - .subscribe({ - queueSizeValue = it - updateGUI() - }, {}) + // compositeDisposable += Single.fromCallable { databaseHelper.getOHQueueSize() } + // .subscribeOn(aapsSchedulers.io) + // .repeatWhen { + // rxBus.toObservable(UpdateViewEvent::class.java) + // .cast(Any::class.java) + // .mergeWith(rxBus.toObservable(UpdateQueueEvent::class.java) + // .throttleLatest(5, TimeUnit.SECONDS)) + // .toFlowable(BackpressureStrategy.LATEST) + // } + // .observeOn(aapsSchedulers.main) + // .subscribe({ + // queueSizeValue = it + // updateGUI() + // }, {}) context?.applicationContext?.let { appContext -> WorkManager.getInstance(appContext).getWorkInfosForUniqueWorkLiveData(OpenHumansUploader.WORK_NAME).observe(this, { val workInfo = it.lastOrNull() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt index 1af58b5089..9d7bb1e7bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/openhumans/OpenHumansUploader.kt @@ -21,14 +21,13 @@ import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.db.* import info.nightscout.androidaps.events.EventPreferenceChange -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface +import info.nightscout.androidaps.extensions.toConstant 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.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.extensions.toConstant import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -60,7 +59,6 @@ class OpenHumansUploader @Inject constructor( private val sp: SP, private val rxBus: RxBusWrapper, private val context: Context, - private val databaseHelper: DatabaseHelperInterface, val repository: AppRepository ) : PluginBase( PluginDescription() @@ -306,11 +304,11 @@ class OpenHumansUploader @Inject constructor( jsonObject.put("structureVersion", structureVersion) jsonObject.put("queuedOn", System.currentTimeMillis()) generator(jsonObject) - val queueItem = OHQueueItem( - file = file, - content = jsonObject.toString() - ) - databaseHelper.createOrUpdate(queueItem) +// val queueItem = OHQueueItem( +// file = file, +// content = jsonObject.toString() +// ) +// databaseHelper.createOrUpdate(queueItem) rxBus.send(OpenHumansFragment.UpdateQueueEvent) } catch (e: JSONException) { e.printStackTrace() @@ -340,7 +338,7 @@ class OpenHumansUploader @Inject constructor( isSetup = false oAuthTokens = null projectMemberId = null - databaseHelper.clearOpenHumansQueue() +// databaseHelper.clearOpenHumansQueue() rxBus.send(OpenHumansFragment.UpdateViewEvent) } @@ -353,18 +351,18 @@ class OpenHumansUploader @Inject constructor( //Updating the notification for every item drastically slows down the operation if (currentProgress % 1000L == 0L) showOngoingNotification(maxProgress, currentProgress) } - copyDisposable = Completable.fromCallable { databaseHelper.clearOpenHumansQueue() } +// copyDisposable = Completable.fromCallable { databaseHelper.clearOpenHumansQueue() } // .andThen(Single.defer { Single.just(databaseHelper.getCountOfAllRows() + treatmentsPlugin.service.count()) }) // .doOnSuccess { maxProgress = it } // .flatMapObservable { Observable.defer { Observable.fromIterable(treatmentsPlugin.service.getTreatmentData()) } } // .map { enqueueTreatment(it); increaseCounter() } // .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) }) - .map { enqueueBGReading(it); increaseCounter() } - .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTherapyEventDataFromTime(0, true).blockingGet()) }) - .map { enqueueTherapyEvent(it); increaseCounter() } - .ignoreElements() +// .andThen(Observable.defer { Observable.fromIterable(repository.compatGetBgReadingsDataFromTime(0, true).blockingGet()) }) +// .map { enqueueBGReading(it); increaseCounter() } +// .ignoreElements() +// .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTherapyEventDataFromTime(0, true).blockingGet()) }) +// .map { enqueueTherapyEvent(it); increaseCounter() } +// .ignoreElements() // .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllExtendedBoluses()) }) // .map { enqueueExtendedBolus(it); increaseCounter() } // .ignoreElements() @@ -377,30 +375,30 @@ class OpenHumansUploader @Inject constructor( // .andThen(Observable.defer { Observable.fromIterable(databaseHelper.getAllTemporaryBasals()) }) // .map { enqueueTemporaryBasal(it); increaseCounter() } // .ignoreElements() - .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) }) - .map { enqueueTempTarget(it); increaseCounter() } - .ignoreElements() - .doOnSubscribe { - wakeLock.acquire(TimeUnit.MINUTES.toMillis(30)) - showOngoingNotification() - } - .doOnComplete { - isSetup = true - scheduleWorker(false) - showSetupFinishedNotification() - } - .doOnError { - logout() - showSetupFailedNotification() - } - .doFinally { - copyDisposable = null - NotificationManagerCompat.from(context).cancel(COPY_NOTIFICATION_ID) - wakeLock.release() - } - .onErrorComplete() - .subscribeOn(aapsSchedulers.io) - .subscribe() +// .andThen(Observable.defer { Observable.fromIterable(repository.compatGetTemporaryTargetData().blockingGet()) }) +// .map { enqueueTempTarget(it); increaseCounter() } +// .ignoreElements() +// .doOnSubscribe { +// wakeLock.acquire(TimeUnit.MINUTES.toMillis(30)) +// showOngoingNotification() +// } +// .doOnComplete { +// isSetup = true +// scheduleWorker(false) +// showSetupFinishedNotification() +// } +// .doOnError { +// logout() +// showSetupFailedNotification() +// } +// .doFinally { +// copyDisposable = null +// NotificationManagerCompat.from(context).cancel(COPY_NOTIFICATION_ID) +// wakeLock.release() +// } +// .onErrorComplete() +// .subscribeOn(aapsSchedulers.io) +// .subscribe() } private fun showOngoingNotification(maxProgress: Long? = null, currentProgress: Long? = null) { @@ -438,7 +436,7 @@ class OpenHumansUploader @Inject constructor( val notificationManager = NotificationManagerCompat.from(context) notificationManager.notify(FAILURE_NOTIFICATION_ID, notification) } - +/* @kotlin.ExperimentalStdlibApi fun uploadDataSegmentally(): Completable = uploadData(UPLOAD_SEGMENT_SIZE) @@ -478,7 +476,7 @@ class OpenHumansUploader @Inject constructor( .doOnSubscribe { aapsLogger.info(LTag.OHUPLOADER, "Starting upload") } - +*/ private fun uploadFile(accessToken: String, uploadData: UploadData) = Completable.defer { openHumansAPI.prepareFileUpload(accessToken, uploadData.fileName, uploadData.metadata) .flatMap { openHumansAPI.uploadFile(it.uploadURL, uploadData.content).andThen(Single.just(it.fileId)) } @@ -495,7 +493,7 @@ class OpenHumansUploader @Inject constructor( Single.just(oAuthTokens.accessToken) } } - +/* @kotlin.ExperimentalStdlibApi private fun gatherData(maxEntries: Long) = Single.defer { val items = databaseHelper.getAllOHQueueItems(maxEntries) @@ -571,7 +569,7 @@ class OpenHumansUploader @Inject constructor( highestQueueId = items.map { it.id }.maxOrNull() )) } - +*/ private fun ZipOutputStream.writeFile(name: String, bytes: ByteArray) { putNextEntry(ZipEntry(name)) write(bytes) @@ -579,7 +577,7 @@ class OpenHumansUploader @Inject constructor( } private fun removeUploadedEntriesFromQueue(highestId: Long) = Completable.fromCallable { - databaseHelper.removeAllOHQueueItemsWithIdSmallerThan(highestId) +// databaseHelper.removeAllOHQueueItemsWithIdSmallerThan(highestId) } private fun handleSignOut() { @@ -649,4 +647,5 @@ class OpenHumansUploader @Inject constructor( private fun onSharedPreferenceChanged(event: EventPreferenceChange) { if (event.changedKey == "key_oh_charging_only" && isSetup) scheduleWorker(true) } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt index 0467839741..68b96bf0fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt @@ -3,10 +3,8 @@ package info.nightscout.androidaps.plugins.general.overview.graphExtensions import android.graphics.Color import info.nightscout.androidaps.Constants import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.database.entities.TherapyEvent -import info.nightscout.androidaps.interfaces.GlucoseUnit -import info.nightscout.androidaps.interfaces.Interval +import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -17,7 +15,7 @@ class TherapyEventDataPoint @Inject constructor( private val resourceHelper: ResourceHelper, private val profileFunction: ProfileFunction, private val translator: Translator -) : DataPointWithLabelInterface, Interval { +) : DataPointWithLabelInterface { private var yValue = 0.0 @@ -52,7 +50,7 @@ class TherapyEventDataPoint @Inject constructor( if (data.note != null) data.note else translator.translate(data.type) - override fun getDuration(): Long = end() - start() + override fun getDuration(): Long = data.duration override fun getShape(): PointsWithLabelGraphSeries.Shape = when { data.type == TherapyEvent.Type.NS_MBG -> PointsWithLabelGraphSeries.Shape.MBG @@ -74,22 +72,4 @@ class TherapyEventDataPoint @Inject constructor( TherapyEvent.Type.APS_OFFLINE -> Color.GRAY and -0x7f000001 else -> Color.GRAY } - - // Interval interface - private var cutEnd: Long? = null - - override fun durationInMsec(): Long = data.duration - override fun start(): Long = data.timestamp - override fun originalEnd(): Long = data.timestamp + durationInMsec() - override fun end(): Long = cutEnd ?: originalEnd() - override fun cutEndTo(end: Long) { - cutEnd = end - } - - override fun match(time: Long): Boolean = start() <= time && end() >= time - override fun before(time: Long): Boolean = end() < time - override fun after(time: Long): Boolean = start() > time - override val isInProgress: Boolean get() = match(System.currentTimeMillis()) - override val isEndingEvent: Boolean get() = durationInMsec() == 0L - override val isValid: Boolean get() = data.type == TherapyEvent.Type.APS_OFFLINE } \ No newline at end of file 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 cef0babae1..0b11136ed1 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 @@ -28,6 +28,8 @@ import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.ui.SpinnerHelper +import info.nightscout.androidaps.utils.ui.TimeListEdit import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import java.text.DecimalFormat 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 deleted file mode 100644 index a8293002f8..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ /dev/null @@ -1,540 +0,0 @@ -package info.nightscout.androidaps.plugins.treatments; - -import android.content.Intent; -import android.os.IBinder; - -import androidx.annotation.Nullable; - -import com.j256.ormlite.android.apptools.OpenHelperManager; -import com.j256.ormlite.android.apptools.OrmLiteBaseService; -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.dao.DaoManager; -import com.j256.ormlite.stmt.PreparedQuery; -import com.j256.ormlite.stmt.QueryBuilder; -import com.j256.ormlite.stmt.Where; -import com.j256.ormlite.support.ConnectionSource; -import com.j256.ormlite.table.TableUtils; - -import org.apache.commons.lang3.StringUtils; -import org.jetbrains.annotations.NotNull; - -import java.sql.SQLException; -import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.db.DatabaseHelper; -import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.db.Treatment; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; -import info.nightscout.androidaps.interfaces.TreatmentServiceInterface; -import info.nightscout.androidaps.interfaces.UpdateReturn; -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.openhumans.OpenHumansUploader; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.rx.AapsSchedulers; - - -/** - * Created by mike on 24.09.2017. - */ - -public class TreatmentService extends OrmLiteBaseService implements TreatmentServiceInterface { - - @Inject AAPSLogger aapsLogger; - @Inject FabricPrivacy fabricPrivacy; - @Inject RxBusWrapper rxBus; - @Inject MedtronicPumpPlugin medtronicPumpPlugin; - @Inject DatabaseHelperInterface databaseHelper; - @Inject OpenHumansUploader openHumansUploader; - @Inject AapsSchedulers aapsSchedulers; - - public TreatmentService(HasAndroidInjector injector) { - injector.androidInjector().inject(this); - onCreate(); - dbInitialize(); - } - - /** - * This method is a simple re-implementation of the database create and up/downgrade functionality - * in SQLiteOpenHelper#getDatabaseLocked method. - *

- * It is implemented to be able to late initialize separate plugins of the application. - */ - protected void dbInitialize() { - DatabaseHelper helper = OpenHelperManager.getHelper(this, DatabaseHelper.class); - int newVersion = helper.getNewVersion(); - int oldVersion = helper.getOldVersion(); - - if (oldVersion > newVersion) { - onDowngrade(this.getConnectionSource(), oldVersion, newVersion); - } else { - onUpgrade(this.getConnectionSource(), oldVersion, newVersion); - } - } - - public TreatmentDaoWrapper getDao() { - try { - return new TreatmentDaoWrapper(DaoManager.createDao(this.getConnectionSource(), Treatment.class)); - } catch (SQLException e) { - aapsLogger.error("Cannot create Dao for Treatment.class"); - } - - return null; - } - - class TreatmentDaoWrapper { - private final Dao wrapped; - - TreatmentDaoWrapper(Dao wrapped) { - this.wrapped = wrapped; - } - - public void executeRaw(String statement, String... arguments) throws SQLException { - wrapped.executeRaw(statement, arguments); - } - - public List queryForAll() throws SQLException { - return wrapped.queryForAll(); - } - - public Treatment queryForId(long id) throws SQLException { - return wrapped.queryForId(id); - } - - public QueryBuilder queryBuilder() { - return wrapped.queryBuilder(); - } - - public List query(PreparedQuery data) throws SQLException { - return wrapped.query(data); - } - - public long countOf() throws SQLException { - return wrapped.countOf(); - } - } - - @Override - public void onCreate() { - super.onCreate(); - try { - aapsLogger.info(LTag.DATATREATMENTS, "onCreate"); - TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); - } catch (SQLException e) { - aapsLogger.error("Can't create database", e); - throw new RuntimeException(e); - } - } - - public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { - if (oldVersion == 7 && newVersion == 8) { - aapsLogger.debug("Upgrading database from v7 to v8"); - try { - TableUtils.dropTable(connectionSource, Treatment.class, true); - TableUtils.createTableIfNotExists(connectionSource, Treatment.class); - } catch (SQLException e) { - aapsLogger.error("Can't create database", e); - throw new RuntimeException(e); - } - } else if (oldVersion == 8 && newVersion == 9) { - aapsLogger.debug("Upgrading database from v8 to v9"); - try { - getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` ADD COLUMN boluscalc STRING;"); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } else { - aapsLogger.info(LTag.DATATREATMENTS, "onUpgrade"); -// this.resetFood(); - } - } - - public void onDowngrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { - if (oldVersion == 9 && newVersion == 8) { - try { - getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` DROP COLUMN boluscalc STRING;"); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - } - } - - public long count() { - try { - return this.getDao().countOf(); - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return 0L; - } - - /* - { - "_id": "551ee3ad368e06e80856e6a9", - "type": "food", - "category": "Zakladni", - "subcategory": "Napoje", - "name": "Mleko", - "portion": 250, - "carbs": 12, - "gi": 1, - "created_at": "2015-04-14T06:59:16.500Z", - "unit": "ml" - } - */ - // return true if new record is created - public UpdateReturn createOrUpdate(Treatment treatment) { - /* - if (treatment != null && treatment.source == Source.NONE) { - aapsLogger.error("Coder error: source is not set for treatment: " + treatment, new Exception()); - //FabricPrivacy.logException(new Exception("Coder error: source is not set for treatment: " + treatment)); - } - try { - Treatment old; - treatment.date = databaseHelper.roundDateToSec(treatment.date); - - if (treatment.source == Source.PUMP) { - // check for changed from pump change in NS - Treatment existingTreatment = getPumpRecordById(treatment.pumpId); - if (existingTreatment != null) { - boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment); - boolean sameSource = existingTreatment.source == treatment.source; - if (!equalRePumpHistory) { - // another treatment exists. Update it with the treatment coming from the pump - aapsLogger.debug(LTag.DATATREATMENTS, "Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); - long oldDate = existingTreatment.date; - - //preserve carbs - if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { - treatment.carbs = existingTreatment.carbs; - // preserve insulin - } else if (existingTreatment.isValid && existingTreatment.insulin > 0 && treatment.insulin == 0) { - treatment.insulin = existingTreatment.insulin; - } - - getDao().delete(existingTreatment); // need to delete/create because date may change too - existingTreatment.copyBasics(treatment); - getDao().create(existingTreatment); - DatabaseHelper.updateEarliestDataChange(oldDate); - DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(sameSource, false); //updating a pump treatment with another one from the pump is not counted as clash - } - return new UpdateReturn(equalRePumpHistory, false); - } - existingTreatment = getDao().queryForId(treatment.date); - if (existingTreatment != null) { - // another treatment exists with different pumpID. Update it with the treatment coming from the pump - boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment); - boolean sameSource = existingTreatment.source == treatment.source; - long oldDate = existingTreatment.date; - aapsLogger.debug(LTag.DATATREATMENTS, "Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); - - //preserve carbs - if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { - treatment.carbs = existingTreatment.carbs; - } - - getDao().delete(existingTreatment); // need to delete/create because date may change too - existingTreatment.copyFrom(treatment); - getDao().create(existingTreatment); - DatabaseHelper.updateEarliestDataChange(oldDate); - DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(equalRePumpHistory || sameSource, false); - } - getDao().create(treatment); - aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(true, true); - } - if (treatment.source == Source.NIGHTSCOUT) { - old = getDao().queryForId(treatment.date); - if (old != null) { - if (!old.isEqual(treatment)) { - boolean historyChange = old.isDataChanging(treatment); - long oldDate = old.date; - getDao().delete(old); // need to delete/create because date may change too - old.copyFrom(treatment); - getDao().create(old); - aapsLogger.debug(LTag.DATATREATMENTS, "Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); - if (historyChange) { - DatabaseHelper.updateEarliestDataChange(oldDate); - DatabaseHelper.updateEarliestDataChange(old.date); - } - scheduleTreatmentChange(treatment, false); - return new UpdateReturn(true, true); - } - aapsLogger.debug(LTag.DATATREATMENTS, "Equal record by date from: " + Source.getString(treatment.source) + " " + old.toString()); - return new UpdateReturn(true, false); - } - // find by NS _id - if (treatment._id != null) { - old = findByNSId(treatment._id); - if (old != null) { - if (!old.isEqual(treatment)) { - boolean historyChange = old.isDataChanging(treatment); - long oldDate = old.date; - getDao().delete(old); // need to delete/create because date may change too - old.copyFrom(treatment); - getDao().create(old); - aapsLogger.debug(LTag.DATATREATMENTS, "Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); - if (historyChange) { - DatabaseHelper.updateEarliestDataChange(oldDate); - DatabaseHelper.updateEarliestDataChange(old.date); - } - scheduleTreatmentChange(treatment, false); - return new UpdateReturn(true, true); - } - aapsLogger.debug(LTag.DATATREATMENTS, "Equal record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); - return new UpdateReturn(true, false); - } - } - getDao().create(treatment); - aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment, false); - return new UpdateReturn(true, true); - } - if (treatment.source == Source.USER) { - getDao().create(treatment); - aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(true, true); - } - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - */ - return new UpdateReturn(false, false); - } - - - @NotNull public UpdateReturn createOrUpdateMedtronic(@NotNull Treatment treatment, boolean fromNightScout) { -/* - if (MedtronicHistoryData.doubleBolusDebug) - aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); - - try { - treatment.date = databaseHelper.roundDateToSec(treatment.date); - - Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date); - - if (MedtronicHistoryData.doubleBolusDebug) - aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment); - - if (existingTreatment == null) { - getDao().create(treatment); - aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); - DatabaseHelper.updateEarliestDataChange(treatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(true, true); - } else { - - if (existingTreatment.date == treatment.date) { - if (MedtronicHistoryData.doubleBolusDebug) - aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date==treatment.date)"); - - // we will do update only, if entry changed - if (!optionalTreatmentCopy(existingTreatment, treatment, fromNightScout)) { - return new UpdateReturn(true, false); - } - getDao().update(existingTreatment); - DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(true, false); - } else { - if (MedtronicHistoryData.doubleBolusDebug) - aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date != treatment.date)"); - - // date is different, we need to remove entry - getDao().delete(existingTreatment); - optionalTreatmentCopy(existingTreatment, treatment, fromNightScout); - getDao().create(existingTreatment); - DatabaseHelper.updateEarliestDataChange(existingTreatment.date); - scheduleTreatmentChange(treatment, true); - return new UpdateReturn(true, false); //updating a pump treatment with another one from the pump is not counted as clash - } - } - - } catch (SQLException e) { - aapsLogger.error("Unhandled SQL exception: {}", e.getMessage(), e); - } - - */ - return new UpdateReturn(false, false); - } - - - private boolean optionalTreatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { - - aapsLogger.debug(LTag.DATATREATMENTS, "optionalTreatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); - - boolean changed = false; - - if (oldTreatment.date != newTreatment.date) { - oldTreatment.date = newTreatment.date; - changed = true; - } - - if (oldTreatment.isSMB != newTreatment.isSMB) { - if (!oldTreatment.isSMB) { - oldTreatment.isSMB = newTreatment.isSMB; - changed = true; - } - } - - if (!isSame(oldTreatment.carbs, newTreatment.carbs)) { - if (isSame(oldTreatment.carbs, 0.0d)) { - oldTreatment.carbs = newTreatment.carbs; - changed = true; - } - } - - if (oldTreatment.mealBolus != (oldTreatment.carbs > 0)) { - oldTreatment.mealBolus = (oldTreatment.carbs > 0); - changed = true; - } - - if (!isSame(oldTreatment.insulin, newTreatment.insulin)) { - if (!fromNightScout) { - oldTreatment.insulin = newTreatment.insulin; - changed = true; - } - } - - if (!StringUtils.equals(oldTreatment._id, newTreatment._id)) { - if (StringUtils.isBlank(oldTreatment._id)) { - oldTreatment._id = newTreatment._id; - changed = true; - } - } - - int source = Source.NONE; - - if (oldTreatment.pumpId == 0) { - if (newTreatment.pumpId > 0) { - oldTreatment.pumpId = newTreatment.pumpId; - source = Source.PUMP; - changed = true; - } - } - - if (source == Source.NONE) { - - if (oldTreatment.source == newTreatment.source) { - source = oldTreatment.source; - } else { - source = (oldTreatment.source == Source.NIGHTSCOUT || newTreatment.source == Source.NIGHTSCOUT) ? Source.NIGHTSCOUT : Source.USER; - } - } - - if (oldTreatment.source != source) { - oldTreatment.source = source; - changed = true; - } - - aapsLogger.debug(LTag.DATATREATMENTS, "optionalTreatmentCopy [changed={}, newAfterChange={}]", changed, oldTreatment.toString()); - return changed; - } - - - public static boolean isSame(Double d1, Double d2) { - double diff = d1 - d2; - - return (Math.abs(diff) <= 0.00001); - } - - public Treatment getRecord(long pumpId, long date) { - - Treatment record = null; - - if (pumpId > 0) { - - record = getPumpRecordById(pumpId); - - if (record != null) { - return record; - } - } - - try { - record = getDao().queryForId(date); - } catch (SQLException ex) { - aapsLogger.error("Error getting entry by id ({}", date); - } - - return record; - - } - - - /** - * Returns the record for the given id, null if none, throws RuntimeException - * if multiple records with the same pump id exist. - */ - @Nullable - public Treatment getPumpRecordById(long pumpId) { - try { - QueryBuilder queryBuilder = getDao().queryBuilder(); - Where where = queryBuilder.where(); - where.eq("pumpId", pumpId); - queryBuilder.orderBy("date", true); - - List result = getDao().query(queryBuilder.prepare()); - if (result.isEmpty()) - return null; - if (result.size() > 1) - aapsLogger.warn(LTag.DATATREATMENTS, "Multiple records with the same pump id found (returning first one): " + result.toString()); - return result.get(0); - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - /** - * finds treatment by its NS Id. - * - * @param _id - * @return - */ - @Nullable - public Treatment findByNSId(String _id) { - try { - TreatmentDaoWrapper daoTreatments = getDao(); - QueryBuilder queryBuilder = daoTreatments.queryBuilder(); - Where where = queryBuilder.where(); - where.eq("_id", _id); - queryBuilder.limit(10L); - PreparedQuery preparedQuery = queryBuilder.prepare(); - List trList = daoTreatments.query(preparedQuery); - if (trList.size() != 1) { - //log.debug("Treatment findTreatmentById query size: " + trList.size()); - return null; - } else { - //log.debug("Treatment findTreatmentById found: " + trList.get(0).log()); - return trList.get(0); - } - } catch (SQLException e) { - aapsLogger.error("Unhandled exception", e); - } - return null; - } - - @Nullable - @Override - public IBinder onBind(Intent intent) { - return 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 deleted file mode 100644 index 04345c3c6d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ /dev/null @@ -1,306 +0,0 @@ -package info.nightscout.androidaps.plugins.treatments; - -import android.content.Context; - -import java.util.List; -import java.util.stream.Collectors; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.database.AppRepository; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; -import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; -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.TreatmentServiceInterface; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.rx.AapsSchedulers; -import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; - -@Singleton -public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { - - private final SP sp; - private final RxBusWrapper rxBus; - private final ProfileFunction profileFunction; - private final ActivePlugin activePlugin; - private final FabricPrivacy fabricPrivacy; - private final DateUtil dateUtil; - private final DatabaseHelperInterface databaseHelper; - private final AppRepository repository; - - private final CompositeDisposable disposable = new CompositeDisposable(); - - protected TreatmentServiceInterface service; - - @Inject - public TreatmentsPlugin( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - RxBusWrapper rxBus, - AapsSchedulers aapsSchedulers, - ResourceHelper resourceHelper, - Context context, - SP sp, - ProfileFunction profileFunction, - ActivePlugin activePlugin, - FabricPrivacy fabricPrivacy, - DateUtil dateUtil, - DatabaseHelperInterface databaseHelper, - AppRepository repository - ) { - super(new PluginDescription() - .mainType(PluginType.TREATMENT) - .pluginIcon(R.drawable.ic_treatments) - .pluginName(R.string.treatments) - .shortName(R.string.treatments_shortname) - .alwaysEnabled(true) - .description(R.string.description_treatments) - .setDefault(), - aapsLogger, resourceHelper, injector - ); - this.rxBus = rxBus; - this.sp = sp; - this.profileFunction = profileFunction; - this.activePlugin = activePlugin; - this.fabricPrivacy = fabricPrivacy; - this.dateUtil = dateUtil; - this.databaseHelper = databaseHelper; - this.repository = repository; - } - - @Override - protected void onStart() { - this.service = new TreatmentService(getInjector()); - super.onStart(); -// disposable.add(rxBus -// .toObservable(EventReloadProfileSwitchData.class) -// .observeOn(aapsSchedulers.getIo()) -// .subscribe(event -> initializeProfileSwitchData(range()), -// fabricPrivacy::logException -// )); - } - - @Override - protected void onStop() { - disposable.clear(); - super.onStop(); - } - - @Override - public TreatmentServiceInterface getService() { - return this.service; - } - - protected long range() { - double dia = Constants.defaultDIA; - if (profileFunction.getProfile() != null) - dia = profileFunction.getProfile().getDia(); - return (long) (60 * 60 * 1000L * (24 + dia)); - } - - /** - * Returns all Treatments after specified timestamp. Also returns invalid entries (required to - * map "Fill Cannula" entries to history (and not to add double bolus for it) - * - * @param fromTimestamp - * @return - */ - @Deprecated - @Override - public List getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) { - return repository.getBolusesIncludingInvalidFromTimeToTime(fromTimestamp, dateUtil.now(), true) - .blockingGet() - .stream() - .map(bolus -> new Treatment(getInjector(), bolus)) - .collect(Collectors.toList()); -/* - List in5minback = new ArrayList<>(); - - long time = System.currentTimeMillis(); - synchronized (treatments) { -// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); - - for (Treatment t : treatments) { - if (t.date >= fromTimestamp && t.date <= time) - in5minback.add(t); - } -// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); - return in5minback; - } -*/ - } -/* - @Override - public long getLastBolusTime() { - Treatment last = getService().getLastBolus(false); - if (last == null) { - getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: NOTHING FOUND"); - return 0; - } else { - getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: " + dateUtil.dateAndTimeString(last.date)); - return last.date; - } - } - - public long getLastBolusTime(boolean excludeSMB) { - Treatment last = getService().getLastBolus(excludeSMB); - if (last == null) { - getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: NOTHING FOUND"); - return 0; - } else { - getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: " + dateUtil.dateAndTimeString(last.date)); - return last.date; - } - } - - public long getLastCarbTime() { - Treatment last = getService().getLastCarb(); - if (last == null) { - getAapsLogger().debug(LTag.DATATREATMENTS, "Last Carb time: NOTHING FOUND"); - return 0; - } else { - getAapsLogger().debug(LTag.DATATREATMENTS, "Last Carb time: " + dateUtil.dateAndTimeString(last.date)); - return last.date; - } - } - - - */ - - @Deprecated - @Override - public boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus) { - throw new IllegalStateException("Migrate to new DB"); - //log.debug("Adding new ExtentedBolus record" + extendedBolus.log()); - /* - boolean newRecordCreated = databaseHelper.createOrUpdate(extendedBolus); - if (newRecordCreated) { - if (extendedBolus.durationInMinutes == 0) { - if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) - nsUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); - else - nsUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); - } else if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) - nsUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); - else - nsUpload.uploadExtendedBolus(extendedBolus); - } - return newRecordCreated; - */ - } - - @Deprecated - @Override - public boolean addToHistoryTempBasal(TemporaryBasal tempBasal) { - throw new IllegalStateException("Migrate to new DB"); -/* - //log.debug("Adding new TemporaryBasal record" + tempBasal.toString()); - boolean newRecordCreated = databaseHelper.createOrUpdate(tempBasal); - if (newRecordCreated) { - if (tempBasal.durationInMinutes == 0) - nsUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId); - else if (tempBasal.isAbsolute) - nsUpload.uploadTempBasalStartAbsolute(tempBasal, null); - else - nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date)); - } - return newRecordCreated; - */ - } - - @Deprecated - public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { - throw new IllegalStateException("Migrate to new DB"); -/* - UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout); - - return new TreatmentUpdateReturn(resultRecord.getSuccess(), resultRecord.getNewRecord()); - */ - } - - // return true if new record is created - @Deprecated - @Override - public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) { - throw new IllegalStateException("Migrate to new DB"); -/* - boolean medtronicPump = activePlugin.getActivePump() instanceof MedtronicPumpPlugin; - - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump); - - Treatment treatment = new Treatment(); - treatment.date = detailedBolusInfo.timestamp; - treatment.source = (detailedBolusInfo.getPumpType() == PumpType.USER) ? Source.USER : Source.PUMP; - treatment.pumpId = detailedBolusInfo.getBolusPumpId() != null ? detailedBolusInfo.getBolusPumpId() : 0; - treatment.insulin = detailedBolusInfo.insulin; - treatment.isValid = detailedBolusInfo.getBolusType() != DetailedBolusInfo.BolusType.PRIMING; - treatment.isSMB = detailedBolusInfo.getBolusType() == DetailedBolusInfo.BolusType.SMB; - if (detailedBolusInfo.carbTime == 0) - treatment.carbs = detailedBolusInfo.carbs; - treatment.mealBolus = treatment.carbs > 0; - // treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null; - treatment.boluscalc = null; - UpdateReturn creatOrUpdateResult; - - getAapsLogger().debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment); - - if (!medtronicPump) - creatOrUpdateResult = getService().createOrUpdate(treatment); - else - creatOrUpdateResult = getService().createOrUpdateMedtronic(treatment, false); - - boolean newRecordCreated = creatOrUpdateResult.getNewRecord(); - //log.debug("Adding new Treatment record" + treatment.toString()); - if (detailedBolusInfo.carbTime != 0) { - - Treatment carbsTreatment = new Treatment(); - carbsTreatment.source = (detailedBolusInfo.getPumpType() == PumpType.USER) ? Source.USER : Source.PUMP; - carbsTreatment.pumpId = detailedBolusInfo.getCarbsPumpId() != null ? detailedBolusInfo.getCarbsPumpId() : 0; // but this should never happen - carbsTreatment.date = detailedBolusInfo.timestamp + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records - carbsTreatment.carbs = detailedBolusInfo.carbs; - - getAapsLogger().debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}" + carbsTreatment); - - if (!medtronicPump) - getService().createOrUpdate(carbsTreatment); - else - getService().createOrUpdateMedtronic(carbsTreatment, false); - //log.debug("Adding new Treatment record" + carbsTreatment); - } - if (newRecordCreated && detailedBolusInfo.getBolusType() != DetailedBolusInfo.BolusType.PRIMING) - nsUpload.uploadTreatmentRecord(detailedBolusInfo); - - if (!allowUpdate && !creatOrUpdateResult.getSuccess()) { - getAapsLogger().error("Treatment could not be added to DB", new Exception()); - - String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, dateUtil.dateAndTimeString(treatment.date)); - - ErrorHelperActivity.Companion.runAlarm(context, status, resourceHelper.gs(R.string.error_adding_treatment_title), R.raw.error); - - Bundle bundle = new Bundle(); - bundle.putString(FirebaseAnalytics.Param.ITEM_LIST_ID, "TreatmentClash"); - bundle.putString(FirebaseAnalytics.Param.ITEM_LIST_NAME, status); - fabricPrivacy.logCustom(bundle); - } - - return newRecordCreated; - */ - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/events/EventTreatmentUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/events/EventTreatmentUpdateGui.kt deleted file mode 100644 index ff42917aec..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/events/EventTreatmentUpdateGui.kt +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.plugins.treatments.events - -import info.nightscout.androidaps.events.EventUpdateGui - -class EventTreatmentUpdateGui : EventUpdateGui() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.kt b/app/src/main/java/info/nightscout/androidaps/utils/ui/NumberPickerVertical.kt similarity index 82% rename from app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.kt rename to app/src/main/java/info/nightscout/androidaps/utils/ui/NumberPickerVertical.kt index 5e7a0d7e90..495dc01e7f 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/ui/NumberPickerVertical.kt @@ -1,10 +1,9 @@ -package info.nightscout.androidaps.utils +package info.nightscout.androidaps.utils.ui import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.ui.NumberPicker class NumberPickerVertical : NumberPicker { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SpinnerHelper.java b/app/src/main/java/info/nightscout/androidaps/utils/ui/SpinnerHelper.java similarity index 99% rename from app/src/main/java/info/nightscout/androidaps/utils/SpinnerHelper.java rename to app/src/main/java/info/nightscout/androidaps/utils/ui/SpinnerHelper.java index a45fcd5a57..191f539680 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SpinnerHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/ui/SpinnerHelper.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.utils; +package info.nightscout.androidaps.utils.ui; import android.view.MotionEvent; import android.view.View; diff --git a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java b/app/src/main/java/info/nightscout/androidaps/utils/ui/TimeListEdit.java similarity index 98% rename from app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java rename to app/src/main/java/info/nightscout/androidaps/utils/ui/TimeListEdit.java index 33a24e3244..591da73eaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/ui/TimeListEdit.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.utils; +package info.nightscout.androidaps.utils.ui; import android.content.Context; import android.text.Editable; @@ -26,7 +26,10 @@ import java.util.List; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.SafeParse; import info.nightscout.androidaps.utils.ui.NumberPicker; +import info.nightscout.androidaps.utils.ui.SpinnerHelper; /** * Created by mike on 29.12.2016. diff --git a/app/src/main/res/layout/timelistedit_element_vertical.xml b/app/src/main/res/layout/timelistedit_element_vertical.xml index d10a7f46ab..a76a8bc20b 100644 --- a/app/src/main/res/layout/timelistedit_element_vertical.xml +++ b/app/src/main/res/layout/timelistedit_element_vertical.xml @@ -20,13 +20,13 @@ android:layout_height="wrap_content" android:orientation="horizontal"> - - diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 1e932c24dd..49ac21447c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -135,8 +135,6 @@ Pump Which pump would you like to use with AndroidAPS? - Treatments - Which plugin should be used for treatment handling? Profile Which profile should AndroidAPS use? APS diff --git a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index fad417344b..bd1f676d4e 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -23,7 +23,6 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin @Mock lateinit var resourceHelper: ResourceHelper - @Mock lateinit var treatmentsInterface: TreatmentsInterface @Mock lateinit var iobCobCalculator: IobCobCalculator @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt index a12a382840..5167b1195b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt @@ -4,9 +4,6 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.database.AppRepository -import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Test @@ -17,23 +14,14 @@ import org.powermock.modules.junit4.PowerMockRunner @Suppress("SpellCheckingInspection") @RunWith(PowerMockRunner::class) -@PrepareForTest(FabricPrivacy::class, DatabaseHelperInterface::class, AppRepository::class) +@PrepareForTest(FabricPrivacy::class, AppRepository::class) class TreatmentsPluginTest : TestBaseWithProfile() { @Mock lateinit var sp: SP - @Mock lateinit var treatmentService: TreatmentService @Mock lateinit var repository: AppRepository - @Mock lateinit var databaseHelper: DatabaseHelperInterface val injector = HasAndroidInjector { AndroidInjector { - if (it is TemporaryBasal) { - it.aapsLogger = aapsLogger - it.activePlugin = activePluginProvider - it.profileFunction = profileFunction - it.sp = sp - it.dateUtil = DateUtil(context) - } } } diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt index 8569d710e0..55c5c13bdf 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.kt @@ -66,7 +66,6 @@ class ActionStartTempTargetTest : ActionsTestBase() { } val updated = mutableListOf().apply { - // TODO insert all updated TTs } `when`( diff --git a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt index 919a2e597a..e164ace6e2 100644 --- a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt +++ b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt @@ -32,7 +32,6 @@ class ComboPluginTest : TestBase() { @Mock lateinit var pumpSync: PumpSync @Mock lateinit var sp: SP @Mock lateinit var context: Context - @Mock lateinit var databaseHelper: DatabaseHelperInterface @Mock lateinit var dateUtil: DateUtil val injector = HasAndroidInjector { diff --git a/core/src/main/java/info/nightscout/androidaps/data/Intervals.kt b/core/src/main/java/info/nightscout/androidaps/data/Intervals.kt deleted file mode 100644 index 0ae6352231..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/data/Intervals.kt +++ /dev/null @@ -1,72 +0,0 @@ -package info.nightscout.androidaps.data - -import androidx.collection.LongSparseArray -import info.nightscout.androidaps.interfaces.Interval -import java.util.* - -/** - * Created by mike on 09.05.2017. - */ -// Zero duration means end of interval -abstract class Intervals { - - var rawData: LongSparseArray = LongSparseArray()// oldest at index 0 - - @Synchronized fun reset(): Intervals { - rawData = LongSparseArray() - return this - } - - protected abstract fun merge() - - /** - * The List must be sorted by `T.start()` in ascending order - */ - @Synchronized fun add(list: List) { - for (interval in list) { - rawData.put(interval.start(), interval) - } - merge() - } - - @Synchronized fun add(interval: T) { - rawData.put(interval.start(), interval) - merge() - } - - @get:Synchronized val list: List - get() { - val list: MutableList = ArrayList() - for (i in 0 until rawData.size()) list.add(rawData.valueAt(i)) - return list - } - @get:Synchronized val reversedList: List - get() { - val list: MutableList = ArrayList() - for (i in rawData.size() - 1 downTo 0) list.add(rawData.valueAt(i)) - return list - } - - @Synchronized protected fun binarySearch(value: Long): Int { - var lo = 0 - var hi = rawData.size() - 1 - while (lo <= hi) { - val mid = lo + hi ushr 1 - val midVal: Interval = rawData.valueAt(mid) - when { - midVal.before(value) -> lo = mid + 1 - midVal.after(value) -> hi = mid - 1 - midVal.match(value) -> return mid // value found - } - } - return lo.inv() // value not present - } - - abstract fun getValueByInterval(time: Long): T? - - @Synchronized fun size(): Int = rawData.size() - - @Synchronized operator fun get(index: Int): T? = rawData.valueAt(index) - - @Synchronized fun getReversed(index: Int): T = rawData.valueAt(size() - 1 - index) -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.kt b/core/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.kt deleted file mode 100644 index 9c8b642baf..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.kt +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.data - -import info.nightscout.androidaps.interfaces.Interval - -class NonOverlappingIntervals : Intervals { - - constructor() : super() - constructor(other: Intervals) { - rawData = other.rawData.clone() - } - - @Synchronized public override fun merge() { - for (index in 0 until rawData.size() - 1) { - val i: T = rawData.valueAt(index) - val startOfNewer = rawData.valueAt(index + 1).start() - if (i.originalEnd() > startOfNewer) { - i.cutEndTo(startOfNewer) - } - } - } - - @Synchronized override fun getValueByInterval(time: Long): T? { - val index = binarySearch(time) - return if (index >= 0) rawData.valueAt(index) else null - } -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.kt b/core/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.kt deleted file mode 100644 index ad6d189b3b..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.data - -import info.nightscout.androidaps.interfaces.Interval - -class OverlappingIntervals : Intervals { - - constructor() : super() - constructor(other: Intervals) { - rawData = other.rawData.clone() - } - - @Synchronized override fun merge() { - var needToCut = false - var cutTime: Long = 0 - for (index in rawData.size() - 1 downTo 0) { //begin with newest - val cur: Interval = rawData.valueAt(index) - if (cur.isEndingEvent) { - needToCut = true - cutTime = cur.start() - } else { - //event that is no EndingEvent might need to be stopped by an ending event - if (needToCut && cur.end() > cutTime) { - cur.cutEndTo(cutTime) - } - } - } - } - - @Synchronized override fun getValueByInterval(time: Long): T? { - for (index in rawData.size() - 1 downTo 0) { //begin with newest - val cur = rawData.valueAt(index) - if (cur!!.match(time)) { - return cur - } - } - return null - } -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.kt b/core/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.kt deleted file mode 100644 index 1f7097b59b..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.kt +++ /dev/null @@ -1,115 +0,0 @@ -package info.nightscout.androidaps.data - -import androidx.collection.LongSparseArray -import info.nightscout.androidaps.interfaces.Interval -import java.util.* - -// Zero duration means profile is valid until is changed -// When no interval match the latest record without duration is used -class ProfileIntervals { - - private var rawData: LongSparseArray // oldest at index 0 - - constructor() { - rawData = LongSparseArray() - } - - constructor(other: ProfileIntervals) { - rawData = other.rawData.clone() - } - - @Synchronized fun reset(): ProfileIntervals { - rawData = LongSparseArray() - return this - } - - @Synchronized fun add(newInterval: T) { - if (newInterval.isValid) { - rawData.put(newInterval.start(), newInterval) - merge() - } - } - - @Synchronized fun add(list: List) { - for (interval in list) { - if (interval.isValid) rawData.put(interval.start(), interval) - } - merge() - } - - @Synchronized private fun merge() { - for (index in 0 until rawData.size() - 1) { - val i: T = rawData.valueAt(index) - val startOfNewer = rawData.valueAt(index + 1)!!.start() - if (i.originalEnd() > startOfNewer) { - i.cutEndTo(startOfNewer) - } - } - } - - @Synchronized fun getValueToTime(time: Long): Interval? { - var index = binarySearch(time) - if (index >= 0) return rawData.valueAt(index) - // if we request data older than first record, use oldest with zero duration instead - index = 0 - while (index < rawData.size()) { - if (rawData.valueAt(index)!!.durationInMsec() == 0L) { - //log.debug("Requested profile for time: " + DateUtil.dateAndTimeString(time) + ". Providing oldest record: " + rawData.valueAt(0).toString()); - return rawData.valueAt(index) - } - index++ - } - return null - } - - @get:Synchronized val list: List - get() { - val list: MutableList = ArrayList() - for (i in 0 until rawData.size()) list.add(rawData.valueAt(i)) - return list - } - @get:Synchronized val reversedList: List - get() { - val list: MutableList = ArrayList() - for (i in rawData.size() - 1 downTo 0) list.add(rawData.valueAt(i)) - return list - } - - @Synchronized private fun binarySearch(value: Long): Int { - if (rawData.size() == 0) return -1 - var lo = 0 - var hi = rawData.size() - 1 - while (lo <= hi) { - val mid = lo + hi ushr 1 - val midVal: Interval = rawData.valueAt(mid) - when { - midVal.match(value) -> return mid // value found - midVal.before(value) -> lo = mid + 1 - midVal.after(value) -> hi = mid - 1 - } - } - // not found, try nearest older with duration 0 - lo -= 1 - while (lo >= 0 && lo < rawData.size()) { - if (rawData.valueAt(lo)!!.isEndingEvent) return lo - lo-- - } - return -1 // value not present - } - - @Synchronized fun size(): Int { - return rawData.size() - } - - @Synchronized operator fun get(index: Int): T? { - return rawData.valueAt(index) - } - - @Synchronized fun getReversed(index: Int): T { - return rawData.valueAt(size() - 1 - index) - } - - override fun toString(): String { - return rawData.toString() - } -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/core/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java deleted file mode 100644 index f00a49dbe6..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ /dev/null @@ -1,306 +0,0 @@ -package info.nightscout.androidaps.db; - -/** - * Created by mike on 21.05.2017. - */ - -import android.graphics.Color; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -import org.json.JSONObject; - -import java.util.Objects; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.Insulin; -import info.nightscout.androidaps.interfaces.Interval; -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.JsonHelper; -import info.nightscout.androidaps.utils.Round; - -/** - * Created by mike on 21.05.2017. - */ - -@Deprecated -@DatabaseTable(tableName = "ExtendedBoluses") -public class ExtendedBolus implements Interval, DataPointWithLabelInterface { - - @Inject ActivePlugin activePlugin; - @Inject DateUtil dateUtil; - - private HasAndroidInjector injector; - - @DatabaseField(id = true) - public long date; - - @DatabaseField - public boolean isValid = true; - - @DatabaseField(index = true) - public long pumpId = 0; - - @DatabaseField - public int source = Source.NONE; - @DatabaseField - public String _id = null; // NS _id - - @DatabaseField - public double insulin = 0d; - @DatabaseField - public int durationInMinutes = 0; // duration == 0 means end of extended bolus - - @DatabaseField - public int insulinInterfaceID = Insulin.InsulinType.OREF_RAPID_ACTING.getValue(); - - @DatabaseField - public double dia = Constants.defaultDIA; - - @Deprecated - public ExtendedBolus() { - injector = StaticInjector.Companion.getInstance(); - injector.androidInjector().inject(this); - } - - public ExtendedBolus(HasAndroidInjector injector) { - this.injector = injector; - injector.androidInjector().inject(this); - } - - public ExtendedBolus(HasAndroidInjector injector, long date) { - this(injector); - this.date = date; - } - - public ExtendedBolus date(long date) { - this.date = date; - return this; - } - - public ExtendedBolus insulin(double insulin) { - this.insulin = insulin; - return this; - } - - public ExtendedBolus pumpId(long pumpId) { - this.pumpId = pumpId; - return this; - } - - public ExtendedBolus source(int source) { - this.source = source; - return this; - } - - public ExtendedBolus durationInMinutes(int durationInMinutes) { - this.durationInMinutes = durationInMinutes; - return this; - } - - public ExtendedBolus _id(String _id) { - this._id = _id; - return this; - } - - public boolean isEqual(ExtendedBolus other) { - if (date != other.date) { - return false; - } - if (durationInMinutes != other.durationInMinutes) - return false; - if (insulin != other.insulin) - return false; - if (pumpId != other.pumpId) - return false; - if (!Objects.equals(_id, other._id)) - return false; - return true; - } - - public void copyFrom(ExtendedBolus t) { - date = t.date; - _id = t._id; - durationInMinutes = t.durationInMinutes; - insulin = t.insulin; - pumpId = t.pumpId; - } - - public static ExtendedBolus createFromJson(HasAndroidInjector injector, JSONObject json) { - ExtendedBolus extendedBolus = new ExtendedBolus(injector) - .source(Source.NIGHTSCOUT) - .date(JsonHelper.safeGetLong(json, "mills")) - .durationInMinutes(JsonHelper.safeGetInt(json, "duration")) - .insulin(JsonHelper.safeGetDouble(json, "relative") / 60 * JsonHelper.safeGetInt(json, "duration")) - ._id(JsonHelper.safeGetString(json, "_id")) - .pumpId(JsonHelper.safeGetLong(json, "pumpId")); - return extendedBolus; - } - // -------- Interval interface --------- - - Long cuttedEnd = null; - - public long durationInMsec() { - return durationInMinutes * 60 * 1000L; - } - - public long start() { - return date; - } - - // planned end time at time of creation - public long originalEnd() { - return date + durationInMinutes * 60 * 1000L; - } - - // end time after cut - public long end() { - if (cuttedEnd != null) - return cuttedEnd; - return originalEnd(); - } - - public void cutEndTo(long end) { - cuttedEnd = end; - } - - public boolean match(long time) { - if (start() <= time && end() >= time) - return true; - return false; - } - - public boolean before(long time) { - if (end() < time) - return true; - return false; - } - - public boolean after(long time) { - if (start() > time) - return true; - return false; - } - - @Override - public boolean isInProgress() { - return match(System.currentTimeMillis()); - } - - @Override - public boolean isEndingEvent() { - return durationInMinutes == 0; - } - - @Override - public boolean isValid() { - return true; - } - - // -------- Interval interface end --------- - - public String log() { - return "ExtendedBolus{" + - "date= " + date + - ", date= " + dateUtil.dateAndTimeString(date) + - ", isValid=" + isValid + - ", _id= " + _id + - ", pumpId= " + pumpId + - ", insulin= " + insulin + - ", durationInMinutes= " + durationInMinutes + - "}"; - } - - public double absoluteRate() { - return Round.roundTo(insulin / durationInMinutes * 60, 0.01); - } - - public double insulinSoFar() { - return absoluteRate() * getRealDuration() / 60d; - } - - public int getRealDuration() { - return getDurationToTime(System.currentTimeMillis()); - } - - private int getDurationToTime(long time) { - long endTime = Math.min(time, end()); - long msecs = endTime - date; - return Math.round(msecs / 60f / 1000); - } - - public int getPlannedRemainingMinutes() { - float remainingMin = (end() - System.currentTimeMillis()) / 1000f / 60; - return (remainingMin < 0) ? 0 : Math.round(remainingMin); - } - - public String toString() { - return "E " + DecimalFormatter.INSTANCE.to2Decimal(absoluteRate()) + "U/h @" + - dateUtil.timeString(date) + - " " + getRealDuration() + "/" + durationInMinutes + "min"; - } - - public String toStringMedium() { - return DecimalFormatter.INSTANCE.to2Decimal(absoluteRate()) + "U/h " - + getRealDuration() + "/" + durationInMinutes + "'"; - } - - public String toStringTotal() { - return DecimalFormatter.INSTANCE.to2Decimal(insulin) + "U ( " + - DecimalFormatter.INSTANCE.to2Decimal(absoluteRate()) + " U/h )"; - } - - // -------- DataPointWithLabelInterface -------- - @Override - public double getX() { - return date; - } - - // default when no sgv around available - private double yValue = 0; - - - @Override - public double getY() { - return yValue; - } - - @Override - public void setY(double y) { - yValue = y; - } - - @Override - public String getLabel() { - return toStringTotal(); - } - - @Override - public long getDuration() { - return durationInMinutes * 60 * 1000L; - } - - @Override - public PointsWithLabelGraphSeries.Shape getShape() { - return PointsWithLabelGraphSeries.Shape.EXTENDEDBOLUS; - } - - @Override - public float getSize() { - return 10; - } - - @Override - public int getColor() { - return Color.CYAN; - } - -} diff --git a/core/src/main/java/info/nightscout/androidaps/db/InsightBolusID.java b/core/src/main/java/info/nightscout/androidaps/db/InsightBolusID.java deleted file mode 100644 index b860fa5b03..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/InsightBolusID.java +++ /dev/null @@ -1,27 +0,0 @@ -package info.nightscout.androidaps.db; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -@DatabaseTable(tableName = "InsightBolusIDs") -public class InsightBolusID { - - @DatabaseField(generatedId = true) - public Long id; - - @DatabaseField - public String pumpSerial; - - @DatabaseField - public Long timestamp; - - @DatabaseField - public Integer bolusID; - - @DatabaseField - public Long startID; - - @DatabaseField - public Long endID; - -} diff --git a/core/src/main/java/info/nightscout/androidaps/db/InsightHistoryOffset.java b/core/src/main/java/info/nightscout/androidaps/db/InsightHistoryOffset.java deleted file mode 100644 index 6be8140f05..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/InsightHistoryOffset.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.db; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -@DatabaseTable(tableName = "InsightHistoryOffsets") -public class InsightHistoryOffset { - - @DatabaseField(id = true, canBeNull = false) - public String pumpSerial; - - @DatabaseField - public long offset; -} diff --git a/core/src/main/java/info/nightscout/androidaps/db/InsightPumpID.java b/core/src/main/java/info/nightscout/androidaps/db/InsightPumpID.java deleted file mode 100644 index 2e2bf05253..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/InsightPumpID.java +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.db; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -@DatabaseTable(tableName = "InsightPumpIDs") -public class InsightPumpID { - - @DatabaseField(generatedId = true) - public Long id; - - @DatabaseField - public long timestamp; - - @DatabaseField - public String eventType; - - @DatabaseField - public String pumpSerial; - - @DatabaseField - public long eventID; - -} diff --git a/core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt b/core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt deleted file mode 100644 index 5876076cbf..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/OHQueueItem.kt +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.db - -import com.j256.ormlite.field.DatabaseField -import com.j256.ormlite.table.DatabaseTable - -@DatabaseTable(tableName = "OpenHumansQueue") -data class OHQueueItem @JvmOverloads constructor( - @DatabaseField(generatedId = true) - val id: Long = 0, - @DatabaseField - val file: String = "", - @DatabaseField - val content: String = "" -) \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/db/Source.java b/core/src/main/java/info/nightscout/androidaps/db/Source.java deleted file mode 100644 index c126794769..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/Source.java +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.db; - -/** - * Created by mike on 21.05.2017. - */ - -public class Source { - public final static int NONE = 0; - public final static int PUMP = 1; // Pump history - public final static int NIGHTSCOUT = 2; // created in NS - public final static int USER = 3; // created by user or driver not using history - - public static String getString(int source) { - switch (source) { - case PUMP: - return "PUMP"; - case NIGHTSCOUT: - return "NIGHTSCOUT"; - case USER: - return "USER"; - } - return "NONE"; - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/core/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java deleted file mode 100644 index afa2474367..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ /dev/null @@ -1,370 +0,0 @@ -package info.nightscout.androidaps.db; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -import java.util.Objects; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.Interval; -import info.nightscout.androidaps.interfaces.Profile; -import info.nightscout.androidaps.interfaces.ProfileFunction; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.sharedPreferences.SP; - -/** - * Created by mike on 21.05.2017. - */ - -@Deprecated -@DatabaseTable(tableName = "TemporaryBasals") -public class TemporaryBasal implements Interval { - - @Inject public AAPSLogger aapsLogger; - @Inject public ProfileFunction profileFunction; - @Inject public ActivePlugin activePlugin; - @Inject public SP sp; - @Inject public DateUtil dateUtil; - - private HasAndroidInjector injector; - - @DatabaseField(id = true) - public long date; - - @DatabaseField - public boolean isValid = true; - - @DatabaseField(index = true) - public long pumpId = 0; - - @DatabaseField - public int source = Source.NONE; - @DatabaseField - public String _id = null; // NS _id - - @DatabaseField - public int durationInMinutes = 0; // duration == 0 means end of temp basal - @DatabaseField - public boolean isAbsolute = false; - - public boolean isFakeExtended = false; - - @DatabaseField - public int percentRate = 0; - @DatabaseField - public double absoluteRate = 0d; - - public double netExtendedRate = 0d; - - @Deprecated - public TemporaryBasal() { - injector = StaticInjector.Companion.getInstance(); - injector.androidInjector().inject(this); - } - - public TemporaryBasal(HasAndroidInjector injector) { - this.injector = injector; - injector.androidInjector().inject(this); - } - - public TemporaryBasal date(long date) { - this.date = date; - return this; - } - - public TemporaryBasal duration(int durationInMinutes) { - this.durationInMinutes = durationInMinutes; - return this; - } - - public TemporaryBasal absolute(double absoluteRate) { - this.absoluteRate = absoluteRate; - this.isAbsolute = true; - return this; - } - - public TemporaryBasal percent(int percentRate) { - this.percentRate = percentRate; - this.isAbsolute = false; - return this; - } - - public TemporaryBasal source(int source) { - this.source = source; - return this; - } - - public TemporaryBasal pumpId(long pumpId) { - this.pumpId = pumpId; - return this; - } - - public TemporaryBasal(ExtendedBolus extendedBolus) { - injector = StaticInjector.Companion.getInstance(); - injector.androidInjector().inject(this); - double basal = profileFunction.getProfile(extendedBolus.date).getBasal(extendedBolus.date); - this.date = extendedBolus.date; - this.isValid = extendedBolus.isValid; - this.source = extendedBolus.source; - this._id = extendedBolus._id; - this.durationInMinutes = extendedBolus.durationInMinutes; - this.isAbsolute = true; - this.isFakeExtended = true; - this.netExtendedRate = extendedBolus.absoluteRate(); - this.absoluteRate = basal + extendedBolus.absoluteRate(); - this.pumpId = extendedBolus.pumpId; - } - - public TemporaryBasal clone() { - TemporaryBasal t = new TemporaryBasal(injector); - t.date = date; - t.isValid = isValid; - t.source = source; - t._id = _id; - t.pumpId = pumpId; - t.durationInMinutes = durationInMinutes; - t.isAbsolute = isAbsolute; - t.percentRate = percentRate; - t.absoluteRate = absoluteRate; - return t; - } - - public boolean isEqual(TemporaryBasal other) { - if (date != other.date) { - return false; - } - if (durationInMinutes != other.durationInMinutes) - return false; - if (isAbsolute != other.isAbsolute) - return false; - if (percentRate != other.percentRate) - return false; - if (absoluteRate != other.absoluteRate) - return false; - if (netExtendedRate != other.netExtendedRate) - return false; - if (isFakeExtended != other.isFakeExtended) - return false; - if (pumpId != other.pumpId) - return false; - if (!Objects.equals(_id, other._id)) - return false; - return true; - } - - public void copyFrom(TemporaryBasal t) { - date = t.date; - _id = t._id; - durationInMinutes = t.durationInMinutes; - isAbsolute = t.isAbsolute; - percentRate = t.percentRate; - absoluteRate = t.absoluteRate; - pumpId = t.pumpId; - isFakeExtended = t.isFakeExtended; - netExtendedRate = t.netExtendedRate; - } - - public void copyFromPump(TemporaryBasal t) { - durationInMinutes = t.durationInMinutes; - isAbsolute = t.isAbsolute; - percentRate = t.percentRate; - absoluteRate = t.absoluteRate; - pumpId = t.pumpId; - } - - // -------- Interval interface --------- - - Long cuttedEnd = null; - - public long durationInMsec() { - return durationInMinutes * 60 * 1000L; - } - - public long start() { - return date; - } - - // planned end time at time of creation - public long originalEnd() { - return date + durationInMinutes * 60 * 1000L; - } - - // end time after cut - public long end() { - if (cuttedEnd != null) - return cuttedEnd; - return originalEnd(); - } - - public void cutEndTo(long end) { - cuttedEnd = end; - } - - public boolean match(long time) { - if (start() <= time && end() >= time) - return true; - return false; - } - - public boolean before(long time) { - if (end() < time) - return true; - return false; - } - - public boolean after(long time) { - if (start() > time) - return true; - return false; - } - - @Override - public boolean isInProgress() { - return match(System.currentTimeMillis()); - } - - @Override - public boolean isEndingEvent() { - return durationInMinutes == 0; - } - - @Override - public boolean isValid() { - return true; - } - - // -------- Interval interface end --------- - - public int getRealDuration() { - return getDurationToTime(System.currentTimeMillis()); - } - - private int getDurationToTime(long time) { - long endTime = Math.min(time, end()); - long msecs = endTime - date; - return Math.round(msecs / 60f / 1000); - } - - public int getPlannedRemainingMinutes() { - float remainingMin = (end() - System.currentTimeMillis()) / 1000f / 60; - return (remainingMin < 0) ? 0 : Math.round(remainingMin); - } - - public int getPlannedRemainingMinutesRoundedUp() { - float remainingMin = (end() - System.currentTimeMillis()) / 1000f / 60; - return (remainingMin < 0) ? 0 : (int) Math.ceil(remainingMin); - } - - - public double tempBasalConvertedToAbsolute(long time, Profile profile) { - if (isFakeExtended) { - return profile.getBasal(time) + netExtendedRate; - } else if (isAbsolute) { - return absoluteRate; - } else { - return profile.getBasal(time) * percentRate / 100; - } - } - - public int tempBasalConvertedToPercent(long time, Profile profile) { - if (isFakeExtended) { - return (int) ((profile.getBasal(time) + netExtendedRate) / profile.getBasal(time)) * 100; - } else if (isAbsolute) { - return (int) (absoluteRate / profile.getBasal(time) * 100); - } else { - return percentRate; - } - } - - public String toString() { - return "TemporaryBasal{" + - "date=" + date + - ", date=" + dateUtil.dateAndTimeString(date) + - ", isValid=" + isValid + - ", pumpId=" + pumpId + - ", _id=" + _id + - ", percentRate=" + percentRate + - ", absoluteRate=" + absoluteRate + - ", durationInMinutes=" + durationInMinutes + - ", isAbsolute=" + isAbsolute + - ", isFakeExtended=" + isFakeExtended + - ", netExtendedRate=" + netExtendedRate + - '}'; - } - - public String toStringFull() { - if (isFakeExtended) { - - Profile profile = profileFunction.getProfile(); - if (profile == null) - return "null"; - Double currentBasalRate = profile.getBasal(); - double rate = currentBasalRate + netExtendedRate; - return DecimalFormatter.INSTANCE.to2Decimal(rate) + "U/h (" + DecimalFormatter.INSTANCE.to2Decimal(netExtendedRate) + "E) @" + - dateUtil.timeString(date) + - " " + getRealDuration() + "/" + durationInMinutes + "'"; - } else if (isAbsolute) { - return DecimalFormatter.INSTANCE.to2Decimal(absoluteRate) + "U/h @" + - dateUtil.timeString(date) + - " " + getRealDuration() + "/" + durationInMinutes + "'"; - } else { // percent - return percentRate + "% @" + - dateUtil.timeString(date) + - " " + getRealDuration() + "/" + durationInMinutes + "'"; - } - } - - public String toStringShort() { - if (isAbsolute || isFakeExtended) { - - double rate; - if (isFakeExtended) { - Profile profile = profileFunction.getProfile(); - if (profile == null) - return "null"; - double currentBasalRate = profile.getBasal(); - rate = currentBasalRate + netExtendedRate; - } else { - rate = absoluteRate; - } - - return DecimalFormatter.INSTANCE.to2Decimal(rate) + "U/h"; - } else { // percent - return percentRate + "%"; - } - } - - public String toStringVeryShort() { - Profile profile = profileFunction.getProfile(); - - if (profile == null) - return "null"; - - if (isAbsolute || isFakeExtended) { - - double rate; - if (isFakeExtended) { - double currentBasalRate = profile.getBasal(); - rate = currentBasalRate + netExtendedRate; - } else { - rate = absoluteRate; - } - return DecimalFormatter.INSTANCE.to2Decimal(rate) + "U/h"; - } else { // percent - return percentRate + "%"; - } - } - - public long getDate() { - return this.date; - } - - public long getPumpId() { - return this.pumpId; - } -} diff --git a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java b/core/src/main/java/info/nightscout/androidaps/db/Treatment.java deleted file mode 100644 index 5e3314d8ff..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/db/Treatment.java +++ /dev/null @@ -1,280 +0,0 @@ -package info.nightscout.androidaps.db; - -import android.graphics.Color; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import com.j256.ormlite.field.DatabaseField; -import com.j256.ormlite.table.DatabaseTable; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.Objects; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.core.R; -import info.nightscout.androidaps.database.entities.Bolus; -import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.Insulin; -import info.nightscout.androidaps.interfaces.Profile; -import info.nightscout.androidaps.interfaces.ProfileFunction; -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.DefaultValueHelper; -import info.nightscout.androidaps.utils.JsonHelper; -import info.nightscout.androidaps.utils.resources.ResourceHelper; - -@Deprecated -@DatabaseTable(tableName = Treatment.TABLE_TREATMENTS) -public class Treatment implements DataPointWithLabelInterface { - @Inject public DefaultValueHelper defaultValueHelper; - @Inject public ResourceHelper resourceHelper; - @Inject public ProfileFunction profileFunction; - @Inject public ActivePlugin activePlugin; - @Inject public DateUtil dateUtil; - - public static final String TABLE_TREATMENTS = "Treatments"; - - @DatabaseField(id = true) - public long date; - - @DatabaseField - public boolean isValid = true; - - @DatabaseField(index = true) - public long pumpId = 0; - - @DatabaseField - public int source = Source.NONE; - @DatabaseField - public String _id; - - @DatabaseField - public double insulin = 0d; - @DatabaseField - public double carbs = 0d; - @DatabaseField - public boolean mealBolus = true; // true for meal bolus , false for correction bolus - @DatabaseField - public boolean isSMB = false; - - @DatabaseField - public int insulinInterfaceID = Insulin.InsulinType.OREF_RAPID_ACTING.getValue(); // currently unused, will be used in the future - @DatabaseField - public double dia = Constants.defaultDIA; // currently unused, will be used in the future - @DatabaseField - public String boluscalc; - - public Treatment() { - StaticInjector.Companion.getInstance().androidInjector().inject(this); // TODO it will be removed by new database - } - - public Treatment(HasAndroidInjector injector) { - injector.androidInjector().inject(this); - } - - public Treatment(HasAndroidInjector injector, Bolus bolus) { - this(injector); - date = bolus.getTimestamp(); - isValid = bolus.isValid(); - pumpId = (bolus.getInterfaceIDs().getPumpId() != null) ? bolus.getInterfaceIDs().getPumpId() : 0; - source = (bolus.getInterfaceIDs().getPumpId() != null) ? Source.PUMP : Source.USER; - _id = bolus.getInterfaceIDs().getNightscoutId(); - insulin = bolus.getAmount(); - isSMB = bolus.getType() == Bolus.Type.SMB; - } - - @NonNull public String toString() { - return "Treatment{" + - "date= " + date + - ", date= " + dateUtil.dateAndTimeString(date) + - ", isValid= " + isValid + - ", isSMB= " + isSMB + - ", _id= " + _id + - ", pumpId= " + pumpId + - ", insulin= " + insulin + - ", carbs= " + carbs + - ", mealBolus= " + mealBolus + - ", source= " + source + - "}"; - } - - public boolean isDataChanging(Treatment other) { - if (date != other.date) - return true; - if (!isSame(insulin, other.insulin)) - return true; - if (!isSame(carbs, other.carbs)) - return true; - return false; - } - - public boolean isEqual(Treatment other) { - if (date != other.date) - return false; - if (!isSame(insulin, other.insulin)) - return false; - if (!isSame(carbs, other.carbs)) - return false; - if (mealBolus != other.mealBolus) - return false; - if (pumpId != other.pumpId) - return false; - if (isSMB != other.isSMB) - return false; - if (!Objects.equals(_id, other._id)) - return false; - return true; - } - - public boolean isEqualWithoutPumpId(Treatment other) { - if (date != other.date) - return false; - if (!isSame(insulin, other.insulin)) - return false; - if (!isSame(carbs, other.carbs)) - return false; - if (mealBolus != other.mealBolus) - return false; - if (isSMB != other.isSMB) - return false; - if (!Objects.equals(_id, other._id)) - return false; - return true; - } - - public boolean isSame(Double d1, Double d2) { - double diff = d1 - d2; - - return (Math.abs(diff) <= 0.000001); - } - - @Nullable - public JSONObject getBoluscalc() { - try { - if (boluscalc != null) - return new JSONObject(boluscalc); - } catch (JSONException ignored) { - } - return null; - } - - public double getIc() { - JSONObject bw = getBoluscalc(); - if (bw == null || !bw.has("ic")) { - Profile profile = profileFunction.getProfile(date); - return profile.getIc(date); - } - return JsonHelper.safeGetDouble(bw, "ic"); - } - - /* - * mealBolus, _id and isSMB cannot be known coming from pump. Only compare rest - * TODO: remove debug toasts - */ - public boolean equalsRePumpHistory(Treatment other) { - if (date != other.date) { - return false; - } - - if (!isSame(insulin, other.insulin)) - return false; - - if (!isSame(carbs, other.carbs)) - return false; - - return true; - } - - public void copyFrom(Treatment t) { - date = t.date; - _id = t._id; - insulin = t.insulin; - carbs = t.carbs; - mealBolus = t.mealBolus; - pumpId = t.pumpId; - isSMB = t.isSMB; - } - - public void copyBasics(Treatment t) { - date = t.date; - insulin = t.insulin; - carbs = t.carbs; - pumpId = t.pumpId; - source = t.source; - } - - // ----------------- DataPointInterface -------------------- - @Override - public double getX() { - return date; - } - - // default when no sgv around available - private double yValue = 0; - - @Override - public double getY() { - return isSMB ? defaultValueHelper.determineLowLine() : yValue; - } - - @Override - public String getLabel() { - String label = ""; - if (insulin > 0) - label += DecimalFormatter.INSTANCE.toPumpSupportedBolus(insulin, activePlugin.getActivePump(), resourceHelper); - if (carbs > 0) - label += "~" + resourceHelper.gs(R.string.format_carbs, (int) carbs); - return label; - } - - @Override - public long getDuration() { - return 0; - } - - @Override - public PointsWithLabelGraphSeries.Shape getShape() { - if (isSMB) - return PointsWithLabelGraphSeries.Shape.SMB; - else - return PointsWithLabelGraphSeries.Shape.BOLUS; - } - - @Override - public float getSize() { - return 2; - } - - @Override - public int getColor() { - if (isSMB) - return resourceHelper.gc(R.color.tempbasal); - else if (isValid) - return Color.CYAN; - else - return resourceHelper.gc(android.R.color.holo_red_light); - } - - @Override - public void setY(double y) { - yValue = y; - } - - // ----------------- DataPointInterface end -------------------- - - public long getDate() { - return this.date; - } - - public long getPumpId() { - return this.pumpId; - } -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/db/StaticInjector.kt b/core/src/main/java/info/nightscout/androidaps/di/StaticInjector.kt similarity index 95% rename from core/src/main/java/info/nightscout/androidaps/db/StaticInjector.kt rename to core/src/main/java/info/nightscout/androidaps/di/StaticInjector.kt index 6dea876733..daf3d7c0b2 100644 --- a/core/src/main/java/info/nightscout/androidaps/db/StaticInjector.kt +++ b/core/src/main/java/info/nightscout/androidaps/di/StaticInjector.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.db +package info.nightscout.androidaps.di import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/ActivePlugin.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/ActivePlugin.kt index b007705b0b..3f8545afb5 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/ActivePlugin.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/ActivePlugin.kt @@ -40,11 +40,6 @@ interface ActivePlugin { */ val activeSensitivity: Sensitivity - /** - * Currently selected Treatments plugin - */ - val activeTreatments: TreatmentsInterface - /** * Currently selected Overview plugin * Always OverviewPlugin diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt deleted file mode 100644 index fe783413a0..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/DatabaseHelperInterface.kt +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.androidaps.interfaces - -import info.nightscout.androidaps.db.* - -interface DatabaseHelperInterface { - - fun resetDatabases() - - fun createOrUpdate(record: OmnipodHistoryRecord) - fun createOrUpdate(record: OHQueueItem) - fun delete(extendedBolus: ExtendedBolus) - fun createOrUpdate(tempBasal: TemporaryBasal): Boolean - @Deprecated("Use new DB") - fun findTempBasalByPumpId(id: Long): TemporaryBasal? - @Deprecated("Use new DB") - fun getTemporaryBasalsDataFromTime(mills: Long, ascending: Boolean): List - fun getAllOmnipodHistoryRecordsFromTimestamp(timestamp: Long, ascending: Boolean): List - fun findOmnipodHistoryRecordByPumpId(pumpId: Long): OmnipodHistoryRecord? - @Deprecated("Use new DB") - fun getExtendedBolusByPumpId(pumpId: Long): ExtendedBolus? - fun getAllOHQueueItems(maxEntries: Long): List - - // old DB model - - fun getOHQueueSize(): Long - fun clearOpenHumansQueue() - fun removeAllOHQueueItemsWithIdSmallerThan(id: Long) - -} diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/Interval.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/Interval.kt deleted file mode 100644 index 47c1d64bcf..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/Interval.kt +++ /dev/null @@ -1,20 +0,0 @@ -package info.nightscout.androidaps.interfaces - -interface Interval { - - fun durationInMsec(): Long - fun start(): Long - - // planned end time at time of creation - fun originalEnd(): Long - - // end time after cut - fun end(): Long - fun cutEndTo(end: Long) - fun match(time: Long): Boolean - fun before(time: Long): Boolean - fun after(time: Long): Boolean - val isInProgress: Boolean - val isEndingEvent: Boolean - val isValid: Boolean -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PluginType.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PluginType.kt index 315c2d6809..ca490bda53 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PluginType.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PluginType.kt @@ -6,5 +6,5 @@ package info.nightscout.androidaps.interfaces * set by [info.nightscout.androidaps.interfaces.PluginDescription.mainType] */ enum class PluginType { - GENERAL, TREATMENT, SENSITIVITY, PROFILE, APS, PUMP, CONSTRAINTS, LOOP, BGSOURCE, INSULIN + GENERAL, SENSITIVITY, PROFILE, APS, PUMP, CONSTRAINTS, LOOP, BGSOURCE, INSULIN } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt deleted file mode 100644 index 3c6b9ae8eb..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentServiceInterface.kt +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.interfaces - -import info.nightscout.androidaps.db.Treatment - -interface TreatmentServiceInterface { - - fun createOrUpdateMedtronic(treatment: Treatment, fromNightScout: Boolean): UpdateReturn - fun createOrUpdate(treatment: Treatment): UpdateReturn -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java deleted file mode 100644 index 6c0da50113..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ /dev/null @@ -1,29 +0,0 @@ -package info.nightscout.androidaps.interfaces; - -import java.util.List; - -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.db.Treatment; -import info.nightscout.androidaps.plugins.treatments.TreatmentUpdateReturn; - -/** - * Created by mike on 14.06.2016. - */ -public interface TreatmentsInterface { - - TreatmentServiceInterface getService(); - - @Deprecated - List getTreatmentsFromHistoryAfterTimestamp(long timestamp); - - boolean addToHistoryTempBasal(TemporaryBasal tempBasal); - - boolean addToHistoryExtendedBolus(ExtendedBolus extendedBolus); - - boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate); - - TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout); - -} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/UpdateReturn.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/UpdateReturn.kt deleted file mode 100644 index f0321ba25a..0000000000 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/UpdateReturn.kt +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.interfaces - -class UpdateReturn(var success: Boolean, var newRecord: Boolean) { - - override fun toString(): String { - return "UpdateReturn [" + - "newRecord=" + newRecord + - ", success=" + success + - ']' - } -} \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 8b145c52a4..378a931a9f 100644 --- a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -4,7 +4,11 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.extensions.pureProfileFromJson -import info.nightscout.androidaps.interfaces.* +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.Config +import info.nightscout.androidaps.interfaces.Profile +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileStore import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper @@ -21,7 +25,6 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin @Mock lateinit var resourceHelper: ResourceHelper - @Mock lateinit var treatmentsInterface: TreatmentsInterface @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper diff --git a/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt b/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt deleted file mode 100644 index 2f0c580b83..0000000000 --- a/core/src/test/java/info/nightscout/androidaps/data/NonOverlappingIntervalsTest.kt +++ /dev/null @@ -1,55 +0,0 @@ -package info.nightscout.androidaps.data - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.utils.T -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class NonOverlappingIntervalsTest : TestBase() { - - private val startDate = System.currentTimeMillis() - var list = NonOverlappingIntervals() - - val injector = HasAndroidInjector { AndroidInjector {} } - - @Test - fun doTests() { - // create one 10h interval and test value in and out - list.add(TemporaryBasal(injector).date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0)) - Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs())) - Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1)) - - // stop temp after 5h - list.add(TemporaryBasal(injector).date(startDate + T.hours(5).msecs()).duration(0)) - Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs())) - Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01) - Assert.assertEquals(1.0, list.getValueByInterval(startDate + T.hours(5).msecs() - 1)!!.absoluteRate, 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(5).msecs() + 1)) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1)) - - // insert 1h interval inside - list.add(TemporaryBasal(injector).date(startDate + T.hours(3).msecs()).duration(T.hours(1).mins().toInt()).absolute(2.0)) - Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs())) - Assert.assertEquals(1.0, list.getValueByInterval(startDate)!!.absoluteRate, 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(5).msecs() - 1)) - Assert.assertEquals(2.0, list.getValueByInterval(startDate + T.hours(3).msecs())!!.absoluteRate, 0.01) - Assert.assertEquals(2.0, list.getValueByInterval(startDate + T.hours(4).msecs() - 1)!!.absoluteRate, 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(4).msecs() + 1)) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1)) - } - - @Test - fun testCopyConstructor() { - list.reset() - list.add(TemporaryBasal(injector).date(startDate).duration(T.hours(10).mins().toInt()).absolute(1.0)) - val list2 = NonOverlappingIntervals(list) - Assert.assertEquals(1, list2.list.size.toLong()) - } -} \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt b/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt deleted file mode 100644 index 09b41eb0fb..0000000000 --- a/core/src/test/java/info/nightscout/androidaps/data/OverlappingIntervalsTest.kt +++ /dev/null @@ -1,58 +0,0 @@ -package info.nightscout.androidaps.data - -import info.nightscout.androidaps.utils.T -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner -import java.util.* - -@RunWith(PowerMockRunner::class) -class OverlappingIntervalsTest { - - private val startDate = System.currentTimeMillis() - private var list = OverlappingIntervals() - @Test fun doTests() { - // create one 10h interval and test value in and out - list.add(TempTargetTest().date(startDate).duration(T.hours(10).mins()).low(100.0).high(100.0)) - Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs())) - Assert.assertEquals(100.0, list.getValueByInterval(startDate)!!.target(), 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1)) - - // stop temp target after 5h - list.add(TempTargetTest().date(startDate + T.hours(5).msecs()).duration(0)) - Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs())) - Assert.assertEquals(100.0, list.getValueByInterval(startDate)!!.target(), 0.01) - Assert.assertEquals(100.0, list.getValueByInterval(startDate + T.hours(5).msecs() - 1)!!.target(), 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(5).msecs() + 1)) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1)) - - // insert 1h interval inside - list.add(TempTargetTest().date(startDate + T.hours(3).msecs()).duration(T.hours(1).mins()).low(200.0).high(200.0)) - Assert.assertEquals(null, list.getValueByInterval(startDate - T.secs(1).msecs())) - Assert.assertEquals(100.0, list.getValueByInterval(startDate)!!.target(), 0.01) - Assert.assertEquals(100.0, list.getValueByInterval(startDate + T.hours(5).msecs() - 1)!!.target(), 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(5).msecs() + 1)) - Assert.assertEquals(200.0, list.getValueByInterval(startDate + T.hours(3).msecs())!!.target(), 0.01) - Assert.assertEquals(100.0, list.getValueByInterval(startDate + T.hours(4).msecs() + 1)!!.target(), 0.01) - Assert.assertEquals(null, list.getValueByInterval(startDate + T.hours(10).msecs() + 1)) - } - - @Test fun testCopyConstructor() { - list.reset() - list.add(TempTargetTest().date(startDate).duration(T.hours(10).mins()).low(100.0).high(100.0)) - val list2 = OverlappingIntervals(list) - Assert.assertEquals(1, list2.list.size.toLong()) - } - - @Test fun testReversingArrays() { - val someList: MutableList = ArrayList() - someList.add(TempTargetTest().date(startDate).duration(T.hours(3).mins()).low(200.0).high(200.0)) - someList.add(TempTargetTest().date(startDate + T.hours(1).msecs()).duration(T.hours(1).mins()).low(100.0).high(100.0)) - list.reset() - list.add(someList) - Assert.assertEquals(startDate, list[0]?.data?.timestamp) - Assert.assertEquals(startDate + T.hours(1).msecs(), list.getReversed(0).data.timestamp) - Assert.assertEquals(startDate + T.hours(1).msecs(), list.reversedList[0].data.timestamp) - } -} \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt b/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt deleted file mode 100644 index b2d530ddcc..0000000000 --- a/core/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.kt +++ /dev/null @@ -1,82 +0,0 @@ -package info.nightscout.androidaps.data - -import info.nightscout.androidaps.TestBaseWithProfile -import info.nightscout.androidaps.TestPumpPlugin -import info.nightscout.androidaps.utils.T -import org.junit.Assert -import org.junit.Before -import org.junit.Test -import org.junit.runner.RunWith -import org.mockito.Mockito.`when` -import org.powermock.modules.junit4.PowerMockRunner -import java.util.* - -@RunWith(PowerMockRunner::class) -class ProfileIntervalsTest : TestBaseWithProfile() { - @Test - fun fake() {} -/* - lateinit var testPumpPlugin: TestPumpPlugin - private val startDate = System.currentTimeMillis() - var list = ProfileIntervals() - - @Before - fun mock() { - testPumpPlugin = TestPumpPlugin(profileInjector) - `when`(activePluginProvider.activePump).thenReturn(testPumpPlugin) - } - - @Test - fun doTests() { - // create one 10h interval and test value in and out - list.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(10).mins().toInt()).profileName("1").profile(validProfile)) - // for older date first record should be returned only if has zero duration - Assert.assertEquals(null, list.getValueToTime(startDate - T.secs(1).msecs())) - Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch).profileName) - Assert.assertEquals(null, list.getValueToTime(startDate + T.hours(10).msecs() + 1)) - list.reset() - list.add(ProfileSwitch(profileInjector).date(startDate).profileName("1").profile(validProfile)) - Assert.assertEquals("1", (list.getValueToTime(startDate - T.secs(1).msecs()) as ProfileSwitch?)!!.profileName) - Assert.assertEquals("1", (list.getValueToTime(startDate) as ProfileSwitch).profileName) - Assert.assertEquals("1", (list.getValueToTime(startDate + T.hours(10).msecs() + 1) as ProfileSwitch?)!!.profileName) - - // switch to different profile after 5h - list.add(ProfileSwitch(profileInjector).date(startDate + T.hours(5).msecs()).duration(0).profileName("2").profile(validProfile)) - Assert.assertEquals("1", (list.getValueToTime(startDate - T.secs(1).msecs()) as ProfileSwitch?)!!.profileName) - Assert.assertEquals("1", (list.getValueToTime(startDate + T.hours(5).msecs() - 1) as ProfileSwitch?)!!.profileName) - Assert.assertEquals("2", (list.getValueToTime(startDate + T.hours(5).msecs() + 1) as ProfileSwitch?)!!.profileName) - - // insert 1h interval inside - list.add(ProfileSwitch(profileInjector).date(startDate + T.hours(6).msecs()).duration(T.hours(1).mins().toInt()).profileName("3").profile(validProfile)) - Assert.assertEquals("2", (list.getValueToTime(startDate + T.hours(6).msecs() - 1) as ProfileSwitch?)!!.profileName) - Assert.assertEquals("3", (list.getValueToTime(startDate + T.hours(6).msecs() + 1) as ProfileSwitch?)!!.profileName) - Assert.assertEquals("2", (list.getValueToTime(startDate + T.hours(7).msecs() + 1) as ProfileSwitch?)!!.profileName) - } - - @Test - fun testCopyConstructor() { - list.reset() - list.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(10).mins().toInt()).profileName("4").profile(validProfile)) - val list2 = ProfileIntervals(list) - Assert.assertEquals(1, list2.list.size.toLong()) - } - - @Test fun invalidProfilesShouldNotBeReturned() { - list.reset() - list.add(ProfileSwitch(profileInjector).date(startDate + T.hours(1).msecs()).profileName("6")) - Assert.assertEquals(null, list[0]) - } - - @Test fun testReversingArrays() { - val someList: MutableList = ArrayList() - someList.add(ProfileSwitch(profileInjector).date(startDate).duration(T.hours(3).mins().toInt()).profileName("5").profile(validProfile)) - someList.add(ProfileSwitch(profileInjector).date(startDate + T.hours(1).msecs()).duration(T.hours(1).mins().toInt()).profileName("6").profile(validProfile)) - list.reset() - list.add(someList) - Assert.assertEquals(startDate, list[0]?.date) - Assert.assertEquals(startDate + T.hours(1).msecs(), list.getReversed(0).date) - Assert.assertEquals(startDate + T.hours(1).msecs(), list.reversedList[0].date) - } - - */ -} \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/data/TempTargetTest.kt b/core/src/test/java/info/nightscout/androidaps/data/TempTargetTest.kt deleted file mode 100644 index f8b5364341..0000000000 --- a/core/src/test/java/info/nightscout/androidaps/data/TempTargetTest.kt +++ /dev/null @@ -1,86 +0,0 @@ -package info.nightscout.androidaps.data - -import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.database.entities.TemporaryTarget -import info.nightscout.androidaps.database.interfaces.end -import info.nightscout.androidaps.interfaces.GlucoseUnit -import info.nightscout.androidaps.interfaces.Interval -import info.nightscout.androidaps.interfaces.Profile -import info.nightscout.androidaps.utils.DecimalFormatter -import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.concurrent.TimeUnit - -class TempTargetTest( - var data: TemporaryTarget = TemporaryTarget( - timestamp = 0, - utcOffset = 0, - reason = TemporaryTarget.Reason.CUSTOM, - highTarget = 0.0, - lowTarget = 0.0, - duration = 0 - ) -) : Interval { - - fun date(timestamp: Long): TempTargetTest { - data.timestamp = timestamp - return this - } - - fun duration(duration: Long): TempTargetTest { - data.duration = T.mins(duration).msecs() - return this - } - - fun low(low: Double): TempTargetTest { - data.lowTarget = low - return this - } - - fun high(high: Double): TempTargetTest { - data.highTarget = high - return this - } - - fun target(): Double { - return (data.lowTarget + data.highTarget) / 2 - } - - // -------- Interval interface --------- - - private var cuttedEnd: Long? = null - - override fun durationInMsec(): Long = data.duration - override fun start(): Long = data.timestamp - override fun originalEnd(): Long = data.end // planned end time at time of creation - override fun end(): Long = cuttedEnd ?: originalEnd() // end time after cut - override fun cutEndTo(end: Long) { - cuttedEnd = end - } - - override fun match(time: Long): Boolean = start() <= time && end() >= time - override fun before(time: Long): Boolean = end() < time - override fun after(time: Long): Boolean = start() > time - override val isInProgress: Boolean get() = match(System.currentTimeMillis()) - override val isEndingEvent: Boolean get() = data.duration == 0L - override val isValid: Boolean get() = true - - // -------- Interval interface end --------- -/* - fun lowValueToUnitsToString(units: String): String = - if (units == Constants.MGDL) DecimalFormatter.to0Decimal(data.lowTarget) - else DecimalFormatter.to1Decimal(data.lowTarget * Constants.MGDL_TO_MMOLL) - - fun highValueToUnitsToString(units: String): String = - if (units == Constants.MGDL) DecimalFormatter.to0Decimal(data.highTarget) - else DecimalFormatter.to1Decimal(data.highTarget * Constants.MGDL_TO_MMOLL) - - override fun toString(): String = data.toString() - - fun friendlyDescription(units: String, resourceHelper: ResourceHelper): String = - Profile.toTargetRangeString(data.lowTarget, data.highTarget, GlucoseUnit.MGDL, units) + - units + - "@" + resourceHelper.gs(R.string.format_mins, TimeUnit.MILLISECONDS.toMinutes(data.duration)) + "(" + data.reason.text + ")" - */ -} \ No newline at end of file diff --git a/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 8b145c52a4..902fbb0df5 100644 --- a/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -21,7 +21,6 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin @Mock lateinit var resourceHelper: ResourceHelper - @Mock lateinit var treatmentsInterface: TreatmentsInterface @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java index 9fc1d98ccd..f79d4d083e 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.java @@ -21,7 +21,6 @@ import info.nightscout.androidaps.danar.DanaRPlugin; import info.nightscout.androidaps.interfaces.ActivePlugin; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.ConfigBuilder; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; diff --git a/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 8b145c52a4..902fbb0df5 100644 --- a/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -21,7 +21,6 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin @Mock lateinit var resourceHelper: ResourceHelper - @Mock lateinit var treatmentsInterface: TreatmentsInterface @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper diff --git a/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 8b145c52a4..902fbb0df5 100644 --- a/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -21,7 +21,6 @@ open class TestBaseWithProfile : TestBase() { @Mock lateinit var activePluginProvider: ActivePlugin @Mock lateinit var resourceHelper: ResourceHelper - @Mock lateinit var treatmentsInterface: TreatmentsInterface @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var profileFunction: ProfileFunction @Mock lateinit var defaultValueHelper: DefaultValueHelper diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt index 9f7bb11d92..c480316c8e 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt @@ -852,7 +852,7 @@ class MedtronicPumpPlugin @Inject constructor( //aapsLogger.debug(LTag.PUMP, "HST: Target Date: " + targetDate); val responseTask2 = rileyLinkMedtronicService.medtronicUIComm.executeCommand(MedtronicCommandType.GetHistoryData, - arrayListOf(/*lastPumpHistoryEntry*/ null, targetDate) as ArrayList?) + arrayListOf(/*lastPumpHistoryEntry*/ null, targetDate) as? ArrayList?) if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: After task") val historyResult = responseTask2.result as PumpHistoryResult? if (debugHistory) aapsLogger.debug(LTag.PUMP, "HST: History Result: " + historyResult.toString()) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index cb904b9afe..95573de246 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -4,9 +4,7 @@ import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.DetailedBolusInfo -import info.nightscout.androidaps.db.* import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -49,7 +47,6 @@ class MedtronicHistoryData @Inject constructor( val medtronicUtil: MedtronicUtil, val medtronicPumpHistoryDecoder: MedtronicPumpHistoryDecoder, val medtronicPumpStatus: MedtronicPumpStatus, - val databaseHelper: DatabaseHelperInterface, val pumpSync: PumpSync, val pumpSyncStorage: info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage ) { @@ -81,7 +78,7 @@ class MedtronicHistoryData @Inject constructor( if (entryByPumpId != null && entryByPumpId.hasBolusChanged(validEntry)) { newEntries.add(validEntry) allHistory.remove(entryByPumpId) - allPumpIds.remove(validEntry.pumpId); + allPumpIds.remove(validEntry.pumpId) } } } @@ -479,11 +476,11 @@ class MedtronicHistoryData @Inject constructor( if (bolusDTO.bolusType == PumpBolusType.Extended) { addExtendedBolus(bolus, bolusDTO, multiwave) - continue; + continue } else if (bolusDTO.bolusType == PumpBolusType.Multiwave) { multiwave = true aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "Multiwave bolus from pump, extended bolus and normal bolus will be added.")) - addExtendedBolus(bolus, bolusDTO, multiwave); + addExtendedBolus(bolus, bolusDTO, multiwave) } val deliveredAmount: Double = if (multiwave) bolusDTO.immediateAmount!! else bolusDTO.deliveredAmount diff --git a/core/src/main/java/info/nightscout/androidaps/db/OmnipodHistoryRecord.java b/omnipod-common/src/main/java/info/nightscout/androidaps/db/OmnipodHistoryRecord.java similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/db/OmnipodHistoryRecord.java rename to omnipod-common/src/main/java/info/nightscout/androidaps/db/OmnipodHistoryRecord.java diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index a1c5ead10b..04f52fc52d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -648,10 +648,12 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements Pump, Riley return deliverBolus(detailedBolusInfo); } else { // no bolus required, carb only treatment - activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true); +// activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, true); - return new PumpEnactResult(getInjector()).success(true).enacted(true).bolusDelivered(0d) - .carbsDelivered(detailedBolusInfo.carbs); +// return new PumpEnactResult(getInjector()).success(true).enacted(true).bolusDelivered(0d) +// .carbsDelivered(detailedBolusInfo.carbs); +// Needs refactor + throw new IllegalStateException("Not implemented"); } } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java index 78151262e9..ab6b018f84 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java @@ -16,14 +16,13 @@ import javax.inject.Singleton; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.OmnipodHistoryRecord; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.extensions.PumpStateExtensionKt; import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; +import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -97,7 +96,6 @@ public class AapsOmnipodErosManager { private final ActivePlugin activePlugin; private final SP sp; private final OmnipodManager delegate; - private final DatabaseHelperInterface databaseHelper; private final OmnipodAlertUtil omnipodAlertUtil; private final Context context; private final PumpSync pumpSync; @@ -128,7 +126,6 @@ public class AapsOmnipodErosManager { ResourceHelper resourceHelper, HasAndroidInjector injector, ActivePlugin activePlugin, - DatabaseHelperInterface databaseHelper, OmnipodAlertUtil omnipodAlertUtil, Context context, PumpSync pumpSync) { @@ -141,7 +138,6 @@ public class AapsOmnipodErosManager { this.resourceHelper = resourceHelper; this.injector = injector; this.activePlugin = activePlugin; - this.databaseHelper = databaseHelper; this.omnipodAlertUtil = omnipodAlertUtil; this.context = context; this.pumpSync = pumpSync; @@ -704,13 +700,15 @@ public class AapsOmnipodErosManager { carbInfo.setCarbsTimestamp(detailedBolusInfo.getCarbsTimestamp()); carbInfo.carbs = detailedBolusInfo.carbs; carbInfo.setPumpType(PumpType.USER); - activePlugin.getActiveTreatments().addToHistoryTreatment(carbInfo, false); - +// activePlugin.getActiveTreatments().addToHistoryTreatment(carbInfo, false); +// Needs refactor // remove carbs from bolusInfo to not trigger any unwanted code paths in // TreatmentsPlugin.addToHistoryTreatment() method detailedBolusInfo.carbs = 0; } - activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); +// activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); +// Needs refactor + throw new IllegalStateException("Not implemented"); } public synchronized void createSuspendedFakeTbrIfNotExists() { @@ -749,8 +747,9 @@ public class AapsOmnipodErosManager { public boolean hasSuspendedFakeTbr() { PumpSync.PumpState pumpState = pumpSync.expectedPumpState(); if (pumpState.getTemporaryBasal() != null && pumpState.getTemporaryBasal().getPumpId() != null) { - OmnipodHistoryRecord historyRecord = databaseHelper.findOmnipodHistoryRecordByPumpId(pumpState.getTemporaryBasal().getPumpId()); - return historyRecord != null && PodHistoryEntryType.getByCode(historyRecord.getPodEntryTypeCode()).equals(PodHistoryEntryType.SET_FAKE_SUSPENDED_TEMPORARY_BASAL); +// OmnipodHistoryRecord historyRecord = databaseHelper.findOmnipodHistoryRecordByPumpId(pumpState.getTemporaryBasal().getPumpId()); +// return historyRecord != null && PodHistoryEntryType.getByCode(historyRecord.getPodEntryTypeCode()).equals(PodHistoryEntryType.SET_FAKE_SUSPENDED_TEMPORARY_BASAL); + throw new IllegalStateException("Not implemented"); } return false; } @@ -853,9 +852,9 @@ public class AapsOmnipodErosManager { omnipodHistoryRecord.setSuccess(success); omnipodHistoryRecord.setPodSerial(podStateManager.hasPodState() ? String.valueOf(podStateManager.getAddress()) : "None"); - databaseHelper.createOrUpdate(omnipodHistoryRecord); - - return omnipodHistoryRecord.getPumpId(); +// databaseHelper.createOrUpdate(omnipodHistoryRecord); +// return omnipodHistoryRecord.getPumpId(); + throw new IllegalStateException("Not implemented"); } private void executeCommand(Runnable runnable) { diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java index 9a8485f689..1ad2887005 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java @@ -9,7 +9,6 @@ import org.apache.commons.lang3.StringUtils; import javax.inject.Inject; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; @@ -37,7 +36,6 @@ public class RileyLinkOmnipodService extends RileyLinkService { @Inject OmnipodErosPumpPlugin omnipodErosPumpPlugin; @Inject AapsOmnipodUtil aapsOmnipodUtil; @Inject PodStateManager podStateManager; - @Inject DatabaseHelperInterface databaseHelper; @Inject AapsOmnipodErosManager aapsOmnipodErosManager; @Inject OmnipodRileyLinkCommunicationManager omnipodRileyLinkCommunicationManager; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java index b534861b81..e74215e8a8 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java @@ -10,11 +10,10 @@ import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; +import androidx.annotation.NonNull; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import androidx.annotation.NonNull; - import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; @@ -24,14 +23,13 @@ import java.util.List; import javax.inject.Inject; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; -import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.db.OmnipodHistoryRecord; -import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; +import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; +import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair; import info.nightscout.androidaps.plugins.pump.common.utils.ProfileUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.R; import info.nightscout.androidaps.plugins.pump.omnipod.eros.definition.PodHistoryEntryType; @@ -43,7 +41,6 @@ public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { @Inject AAPSLogger aapsLogger; @Inject AapsOmnipodUtil aapsOmnipodUtil; @Inject ResourceHelper resourceHelper; - @Inject DatabaseHelperInterface databaseHelper; private Spinner historyTypeSpinner; private TextView statusView; @@ -69,9 +66,9 @@ public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { GregorianCalendar gc = new GregorianCalendar(); gc.add(Calendar.HOUR_OF_DAY, -24); - databaseHelper.getAllOmnipodHistoryRecordsFromTimestamp(gc.getTimeInMillis(), false); - - fullHistoryList.addAll(databaseHelper.getAllOmnipodHistoryRecordsFromTimestamp(gc.getTimeInMillis(), true)); +// databaseHelper.getAllOmnipodHistoryRecordsFromTimestamp(gc.getTimeInMillis(), false); +// fullHistoryList.addAll(databaseHelper.getAllOmnipodHistoryRecordsFromTimestamp(gc.getTimeInMillis(), true)); + throw new IllegalStateException("Not implemented"); } From beb8ba7efcd98abb0cd075c7ac6e1b4c4aff4653 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 30 May 2021 14:51:57 +0200 Subject: [PATCH 05/91] enable MDT plugin --- .../androidaps/dependencyInjection/PluginsModule.kt | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) 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 d0335c03ab..40bce88096 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -39,6 +39,7 @@ import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin 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.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin @@ -145,11 +146,11 @@ abstract class PluginsModule { @IntKey(140) abstract fun bindComboPlugin(plugin: ComboPlugin): PluginBase - // @Binds - // @PumpDriver - // @IntoMap - // @IntKey(150) - // abstract fun bindMedtronicPumpPlugin(plugin: MedtronicPumpPlugin): PluginBase + @Binds + @PumpDriver + @IntoMap + @IntKey(150) + abstract fun bindMedtronicPumpPlugin(plugin: MedtronicPumpPlugin): PluginBase // @Binds // @PumpDriver From 8904c7d2a74491e8dd5b11a589be9e70e22281e6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 May 2021 05:45:46 +0000 Subject: [PATCH 06/91] Bump kotlin_version from 1.5.0-release-764 to 1.5.10 Bumps `kotlin_version` from 1.5.0-release-764 to 1.5.10. Updates `kotlin-gradle-plugin` from 1.5.0-release-764 to 1.5.10 Updates `kotlin-stdlib-jdk7` from 1.5.0-release-764 to 1.5.10 - [Release notes](https://github.com/JetBrains/kotlin/releases) - [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md) - [Commits](https://github.com/JetBrains/kotlin/commits/v1.5.10) Updates `kotlin-reflect` from 1.5.0-release-764 to 1.5.10 - [Release notes](https://github.com/JetBrains/kotlin/releases) - [Changelog](https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md) - [Commits](https://github.com/JetBrains/kotlin/commits/v1.5.10) Signed-off-by: dependabot[bot] --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 003562e695..7f5602306e 100644 --- a/build.gradle +++ b/build.gradle @@ -1,7 +1,7 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { - ext.kotlin_version = '1.5.0-release-764' + ext.kotlin_version = '1.5.10' ext { // kotlin 1.5.0 prevents travis from pass // remove @kotlin.ExperimentalStdlibApi everywhere when upgrade From a95fabee68985bead6452e5a57862cf1e6d2e745 Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Mon, 31 May 2021 13:41:31 +0100 Subject: [PATCH 07/91] - fix of the problem encountered by Ghosa Sardes --- .../pump/medtronic/data/MedtronicHistoryData.kt | 13 +++++++++---- .../pump/medtronic/data/dto/TempBasalProcessDTO.kt | 14 +++++++++++--- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index 95573de246..180b5f9d1f 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -600,7 +600,9 @@ class MedtronicHistoryData @Inject constructor( } processDTO = TempBasalProcessDTO( itemOne = treatment, - processOperation = TempBasalProcessDTO.Operation.Add) + processOperation = TempBasalProcessDTO.Operation.Add, + aapsLogger = aapsLogger + ) } } if (processDTO != null) { @@ -841,7 +843,8 @@ class MedtronicHistoryData @Inject constructor( outList.add(TempBasalProcessDTO( itemOne = filtered2Items[i], itemTwo = filtered2Items[i + 1], - processOperation = TempBasalProcessDTO.Operation.Add)) + processOperation = TempBasalProcessDTO.Operation.Add, + aapsLogger = aapsLogger)) i += 2 } @@ -906,14 +909,16 @@ class MedtronicHistoryData @Inject constructor( outList.add(TempBasalProcessDTO( itemOne = items[items.size - 1], itemTwo = itemTwo, - processOperation = TempBasalProcessDTO.Operation.Add)) + processOperation = TempBasalProcessDTO.Operation.Add, + aapsLogger = aapsLogger)) return outList } items = getFilteredItems(tempData, PumpHistoryEntryType.Rewind) if (items.size > 0) { outList.add(TempBasalProcessDTO( itemOne = items[0], - processOperation = TempBasalProcessDTO.Operation.Add)) + processOperation = TempBasalProcessDTO.Operation.Add, + aapsLogger = aapsLogger)) return outList } return outList diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.kt index 02ddb39f46..9cbb0b6dbc 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.kt @@ -1,11 +1,14 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry class TempBasalProcessDTO constructor(var itemOne: PumpHistoryEntry, var itemTwo: PumpHistoryEntry? = null, - var processOperation: Operation = Operation.None) { + var processOperation: Operation = Operation.None, + var aapsLogger: AAPSLogger) { + var cancelPresent: Boolean = false val atechDateTime: Long @@ -16,8 +19,13 @@ class TempBasalProcessDTO constructor(var itemOne: PumpHistoryEntry, val duration: Int get() = if (itemTwo == null) { - val tbr = itemOne.getDecodedDataEntry("Object") as TempBasalPair - tbr.durationMinutes + val tbr = itemOne.getDecodedDataEntry("Object") as? TempBasalPair + if (tbr != null) + tbr.durationMinutes + else { + aapsLogger.error("Couldn't find TempBasalPair in entry: $itemOne") + 0 + } } else { DateTimeUtil.getATechDateDiferenceAsMinutes(itemOne.atechDateTime, itemTwo!!.atechDateTime) } From 596012ab102bd7dcdb4fffe01e6642d4e575b8b9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 31 May 2021 15:29:42 +0200 Subject: [PATCH 08/91] move logs, eng_mode to AAPS directory --- app/src/main/AndroidManifest.xml | 10 ++++++---- app/src/main/assets/logback.xml | 2 +- .../general/maintenance/MaintenanceFragment.kt | 4 +++- .../plugins/general/maintenance/MaintenancePlugin.kt | 9 +++++---- .../androidaps/receivers/KeepAliveReceiver.kt | 4 ++++ .../androidaps/utils/buildHelper/BuildHelper.kt | 10 ++++++---- .../general/maintenance/PrefFileListProvider.kt | 11 ++++++++++- 7 files changed, 35 insertions(+), 15 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 77b68adf4a..ab34d9dfe1 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -52,7 +52,8 @@ android:name="com.google.android.gms.car.application" android:resource="@xml/automotive_app_desc" /> - + @@ -60,7 +61,8 @@ - + @@ -115,11 +117,11 @@ - + - + + value="${EXT_DIR:-/sdcard}/AAPS/logs/${PACKAGE_NAME}" /> ${EXT_FILES_DIR}/AndroidAPS.log diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index 36df705147..eea9b5d3c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -63,7 +63,9 @@ class MaintenanceFragment : DaggerFragment() { binding.logSend.setOnClickListener { maintenancePlugin.sendLogs() } binding.logDelete.setOnClickListener { uel.log(Action.DELETE_LOGS, Sources.Maintenance) - maintenancePlugin.deleteLogs() + Thread { + maintenancePlugin.deleteLogs(5) + }.start() } binding.navResetdb.setOnClickListener { activity?.let { activity -> diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index 571cd19656..cf5c9a6621 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -35,6 +35,7 @@ class MaintenancePlugin @Inject constructor( aapsLogger: AAPSLogger, private val buildHelper: BuildHelper, private val config: Config, + private val fileListProvider: PrefFileListProvider, private val loggerUtils: LoggerUtils ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) @@ -53,7 +54,7 @@ class MaintenancePlugin @Inject constructor( val recipient = sp.getString(R.string.key_maintenance_logs_email, "logs@androidaps.org") val amount = sp.getInt(R.string.key_maintenance_logs_amount, 2) val logs = getLogFiles(amount) - val zipDir = context.getExternalFilesDir("exports") + val zipDir = fileListProvider.ensureExportDirExists() val zipFile = File(zipDir, constructName()) aapsLogger.debug("zipFile: ${zipFile.absolutePath}") val zip = zipLogs(zipFile, logs) @@ -65,14 +66,14 @@ class MaintenancePlugin @Inject constructor( //todo replace this with a call on startup of the application, specifically to remove // unnecessary garbage from the log exports - fun deleteLogs() { + fun deleteLogs(keep: Int) { val logDir = File(loggerUtils.logDirectory) val files = logDir.listFiles { _: File?, name: String -> (name.startsWith("AndroidAPS") && name.endsWith(".zip")) } Arrays.sort(files) { f1: File, f2: File -> f1.name.compareTo(f2.name) } var delFiles = listOf(*files) - val amount = sp.getInt(R.string.key_logshipper_amount, 5) + val amount = sp.getInt(R.string.key_logshipper_amount, keep) val keepIndex = amount - 1 if (keepIndex < delFiles.size) { delFiles = delFiles.subList(keepIndex, delFiles.size) @@ -80,7 +81,7 @@ class MaintenancePlugin @Inject constructor( file.delete() } } - val exportDir = File(loggerUtils.logDirectory, "exports") + val exportDir = fileListProvider.ensureExportDirExists() if (exportDir.exists()) { val expFiles = exportDir.listFiles() for (file in expFiles) { 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 48f073e804..1d475d162d 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -28,6 +28,7 @@ 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.plugins.configBuilder.RunningConfiguration +import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy @@ -72,6 +73,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var maintenancePlugin: MaintenancePlugin init { (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) @@ -93,6 +95,8 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { localAlertUtils.checkStaleBGAlert() checkPump() checkAPS() + maintenancePlugin.deleteLogs(30) + return Result.success() } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt index 0cb6b5c772..04dbd0d789 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt @@ -2,20 +2,22 @@ package info.nightscout.androidaps.utils.buildHelper import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.interfaces.Config -import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils +import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider import java.io.File import javax.inject.Inject import javax.inject.Singleton @Singleton -class BuildHelper @Inject constructor(private val config: Config, loggerUtils: LoggerUtils) { +class BuildHelper @Inject constructor( + private val config: Config, + fileListProvider: PrefFileListProvider +) { private var devBranch = false private var engineeringMode = false init { - val extFilesDir = loggerUtils.logDirectory - val engineeringModeSemaphore = File(extFilesDir, "engineering__mode") + val engineeringModeSemaphore = File(fileListProvider.ensureExtraDirExists(), "engineering__mode") engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(Regex(".*[a-zA-Z]+.*")) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt index 86208dce3e..a89dc204e1 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt @@ -32,6 +32,7 @@ class PrefFileListProvider @Inject constructor( private val path = File(Environment.getExternalStorageDirectory().toString()) private val aapsPath = File(path, "AAPS" + File.separator + "preferences") private val exportsPath = File(path, "AAPS" + File.separator + "exports") + private val extraPath = File(path, "AAPS" + File.separator + "extra") private const val IMPORT_AGE_NOT_YET_OLD_DAYS = 60 } @@ -90,13 +91,21 @@ class PrefFileListProvider @Inject constructor( return File(path, resourceHelper.gs(R.string.app_name) + "Preferences") } - fun ensureExportDirExists() { + fun ensureExportDirExists(): File { if (!aapsPath.exists()) { aapsPath.mkdirs() } if (!exportsPath.exists()) { exportsPath.mkdirs() } + return exportsPath + } + + fun ensureExtraDirExists(): File { + if (!extraPath.exists()) { + extraPath.mkdirs() + } + return extraPath } fun newExportFile(): File { From ffde47d53198f94fcc14bb5fc76874b49c785450 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 31 May 2021 18:03:57 +0200 Subject: [PATCH 09/91] fix Dana 5 BLE comm --- .../androidaps/danars/comm/DanaRS_Packet.java | 248 ------------------ .../androidaps/danars/comm/DanaRS_Packet.kt | 157 +++++++++++ .../androidaps/danars/services/BLEComm.kt | 77 +++--- .../jniLibs/arm64-v8a/libBleEncryption.so | Bin 22776 -> 22776 bytes .../jniLibs/armeabi-v7a/libBleEncryption.so | Bin 26548 -> 26548 bytes .../src/main/jniLibs/x86/libBleEncryption.so | Bin 22432 -> 22432 bytes .../main/jniLibs/x86_64/libBleEncryption.so | Bin 23056 -> 23056 bytes .../danars/comm/DanaRsMessageHashTableTest.kt | 2 +- 8 files changed, 195 insertions(+), 289 deletions(-) delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.java create mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.java b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.java deleted file mode 100644 index ff99f0d891..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.java +++ /dev/null @@ -1,248 +0,0 @@ -package info.nightscout.androidaps.danars.comm; - -import android.annotation.TargetApi; -import android.os.Build; - -import org.joda.time.DateTime; - -import java.nio.charset.StandardCharsets; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.danars.encryption.BleEncryption; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.utils.DateUtil; - -public class DanaRS_Packet { - - @Inject AAPSLogger aapsLogger; - @Inject DateUtil dateUtil; - - protected HasAndroidInjector injector; - - private static final int TYPE_START = 0; - private static final int OPCODE_START = 1; - public static final int DATA_START = 2; - - private boolean received; - public boolean failed; - protected int type = BleEncryption.DANAR_PACKET__TYPE_RESPONSE; // most of the messages, should be changed for others - protected int opCode; - - public DanaRS_Packet(HasAndroidInjector injector) { - received = false; - failed = false; - this.injector = injector; - injector.androidInjector().inject(this); - } - - public boolean success() { - return !failed; - } - public void setReceived() { - received = true; - } - - public boolean isReceived() { - return received; - } - - public int getType() { - return type; - } - - public int getOpCode() { - return opCode; - } - - public int getCommand() { - return ((type & 0xFF) << 8) + (opCode & 0xFF); - } - - public byte[] getRequestParams() { - return null; - } - - // STATIC FUNCTIONS - - public int getCommand(byte[] data) { - int type = byteArrayToInt(getBytes(data, TYPE_START, 1)); - int opCode = byteArrayToInt(getBytes(data, OPCODE_START, 1)); - return ((type & 0xFF) << 8) + (opCode & 0xFF); - } - - public void handleMessage(byte[] data) { - } - - public void handleMessageNotReceived() { - failed = true; - } - - public String getFriendlyName() { - return "UNKNOWN_PACKET"; - } - - protected byte[] getBytes(byte[] data, int srcStart, int srcLength) { - try { - byte[] ret = new byte[srcLength]; - - System.arraycopy(data, srcStart, ret, 0, srcLength); - - return ret; - } catch (Exception e) { - aapsLogger.error(LTag.PUMPBTCOMM, "Unhandled exception", e); - } - return null; - } - - protected static int byteArrayToInt(byte[] b) { - int ret; - - switch (b.length) { - case 1: - ret = b[0] & 0x000000FF; - break; - case 2: - ret = ((b[1] & 0x000000FF) << 8) + (b[0] & 0x000000FF); - break; - case 3: - ret = ((b[2] & 0x000000FF) << 16) + ((b[1] & 0x000000FF) << 8) + (b[0] & 0x000000FF); - break; - case 4: - ret = ((b[3] & 0x000000FF) << 24) + ((b[2] & 0x000000FF) << 16) + ((b[1] & 0x000000FF) << 8) + (b[0] & 0x000000FF); - break; - default: - ret = -1; - break; - } - return ret; - } - - public static synchronized long dateTimeSecFromBuff(byte[] buff, int offset) { - return - new DateTime( - 2000 + intFromBuff(buff, offset, 1), - intFromBuff(buff, offset + 1, 1), - intFromBuff(buff, offset + 2, 1), - intFromBuff(buff, offset + 3, 1), - intFromBuff(buff, offset + 4, 1), - intFromBuff(buff, offset + 5, 1) - ).getMillis(); - } - - protected static int intFromBuff(byte[] b, int srcStart, int srcLength) { - int ret; - - switch (srcLength) { - case 1: - ret = b[DATA_START + srcStart + 0] & 0x000000FF; - break; - case 2: - ret = ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 0] & 0x000000FF); - break; - case 3: - ret = ((b[DATA_START + srcStart + 2] & 0x000000FF) << 16) + ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 0] & 0x000000FF); - break; - case 4: - ret = ((b[DATA_START + srcStart + 3] & 0x000000FF) << 24) + ((b[DATA_START + srcStart + 2] & 0x000000FF) << 16) + ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 0] & 0x000000FF); - break; - default: - ret = -1; - break; - } - return ret; - } - - protected static int intFromBuffMsbLsb(byte[] b, int srcStart, int srcLength) { - int ret; - - switch (srcLength) { - case 1: - ret = b[DATA_START + srcStart] & 0x000000FF; - break; - case 2: - ret = ((b[DATA_START + srcStart] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 1] & 0x000000FF); - break; - case 3: - ret = ((b[DATA_START + srcStart] & 0x000000FF) << 16) + ((b[DATA_START + srcStart + 1] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 2] & 0x000000FF); - break; - case 4: - ret = ((b[DATA_START + srcStart] & 0x000000FF) << 24) + ((b[DATA_START + srcStart + 1] & 0x000000FF) << 16) + ((b[DATA_START + srcStart + 2] & 0x000000FF) << 8) + (b[DATA_START + srcStart + 3] & 0x000000FF); - break; - default: - ret = -1; - break; - } - return ret; - } - - @TargetApi(Build.VERSION_CODES.KITKAT) - public static String stringFromBuff(byte[] buff, int offset, int length) { - byte[] strbuff = new byte[length]; - System.arraycopy(buff, offset, strbuff, 0, length); - return new String(strbuff, StandardCharsets.UTF_8); - } - - public long dateFromBuff(byte[] buff, int offset) { - return - new DateTime( - 2000 + byteArrayToInt(getBytes(buff, offset, 1)), - byteArrayToInt(getBytes(buff, offset + 1, 1)), - byteArrayToInt(getBytes(buff, offset + 2, 1)), - 0, - 0 - ).getMillis(); - } - - @TargetApi(Build.VERSION_CODES.KITKAT) - - public static String asciiStringFromBuff(byte[] buff, int offset, int length) { - byte[] strbuff = new byte[length]; - System.arraycopy(buff, offset, strbuff, 0, length); - return new String(strbuff, StandardCharsets.UTF_8); - } - - public static String toHexString(byte[] buff) { - if (buff == null) - return ""; - - StringBuilder sb = new StringBuilder(); - - int count = 0; - for (byte element : buff) { - sb.append(String.format("%02X ", element)); - if (++count % 4 == 0) sb.append(" "); - } - - return sb.toString(); - } - - final private static char[] hexArray = "0123456789ABCDEF".toCharArray(); - - public static String bytesToHex(byte[] bytes) { - char[] hexChars = new char[bytes.length * 2]; - for (int j = 0; j < bytes.length; j++) { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - return new String(hexChars); - } - - public static byte[] hexToBytes(String s) { - int len = s.length(); - byte[] data = new byte[len / 2]; - for (int i = 0; i < len; i += 2) { - data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) - + Character.digit(s.charAt(i + 1), 16)); - } - return data; - } - - public static int ByteToInt(byte b) { - return b & 0x000000FF; - } - -} diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt new file mode 100644 index 0000000000..ba0e31ebb9 --- /dev/null +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt @@ -0,0 +1,157 @@ +package info.nightscout.androidaps.danars.comm + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.danars.encryption.BleEncryption +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.utils.DateUtil +import org.joda.time.DateTime +import java.nio.charset.StandardCharsets +import javax.inject.Inject + +open class DanaRS_Packet(protected var injector: HasAndroidInjector) { + + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var dateUtil: DateUtil + + var isReceived = false + private set + var failed = false + var type = BleEncryption.DANAR_PACKET__TYPE_RESPONSE // most of the messages, should be changed for others + protected set + var opCode = 0 + protected set + + fun success(): Boolean = !failed + + fun setReceived() { + isReceived = true + } + + val command: Int + get() = (type and 0xFF shl 8) + (opCode and 0xFF) + + open fun getRequestParams(): ByteArray = ByteArray(0) + + fun getCommand(data: ByteArray): Int { + val type = byteArrayToInt(getBytes(data, TYPE_START, 1)) + val opCode = byteArrayToInt(getBytes(data, OPCODE_START, 1)) + return (type and 0xFF shl 8) + (opCode and 0xFF) + } + + open fun handleMessage(data: ByteArray) {} + open fun handleMessageNotReceived() { + failed = true + } + + open fun getFriendlyName(): String = "UNKNOWN_PACKET" + + protected fun getBytes(data: ByteArray, srcStart: Int, srcLength: Int): ByteArray { + val ret = ByteArray(srcLength) + System.arraycopy(data, srcStart, ret, 0, srcLength) + return ret + } + + fun dateFromBuff(buff: ByteArray, offset: Int): Long = + DateTime( + 2000 + byteArrayToInt(getBytes(buff, offset, 1)), + byteArrayToInt(getBytes(buff, offset + 1, 1)), + byteArrayToInt(getBytes(buff, offset + 2, 1)), + 0, + 0 + ).millis + + protected fun byteArrayToInt(b: ByteArray): Int = + when (b.size) { + 1 -> b[0].toInt() and 0xFF + 2 -> (b[1].toInt() and 0xFF shl 8) + (b[0].toInt() and 0xFF) + 3 -> (b[2].toInt() and 0xFF shl 16) + (b[1].toInt() and 0xFF shl 8) + (b[0].toInt() and 0xFF) + 4 -> (b[3].toInt() and 0xFF shl 24) + (b[2].toInt() and 0xFF shl 16) + (b[1].toInt() and 0xFF shl 8) + (b[0].toInt() and 0xFF) + else -> -1 + } + + @Synchronized fun dateTimeSecFromBuff(buff: ByteArray, offset: Int): Long = + DateTime( + 2000 + intFromBuff(buff, offset, 1), + intFromBuff(buff, offset + 1, 1), + intFromBuff(buff, offset + 2, 1), + intFromBuff(buff, offset + 3, 1), + intFromBuff(buff, offset + 4, 1), + intFromBuff(buff, offset + 5, 1) + ).millis + + protected fun intFromBuff(b: ByteArray, srcStart: Int, srcLength: Int): Int = + when (srcLength) { + 1 -> b[DATA_START + srcStart + 0].toInt() and 0xFF + 2 -> (b[DATA_START + srcStart + 1].toInt() and 0xFF shl 8) + (b[DATA_START + srcStart + 0].toInt() and 0xFF) + 3 -> (b[DATA_START + srcStart + 2].toInt() and 0xFF shl 16) + (b[DATA_START + srcStart + 1].toInt() and 0xFF shl 8) + (b[DATA_START + srcStart + 0].toInt() and 0xFF) + 4 -> (b[DATA_START + srcStart + 3].toInt() and 0xFF shl 24) + (b[DATA_START + srcStart + 2].toInt() and 0xFF shl 16) + (b[DATA_START + srcStart + 1].toInt() and 0xFF shl 8) + (b[DATA_START + srcStart + 0].toInt() and 0xFF) + else -> -1 + } + + protected fun intFromBuffMsbLsb(b: ByteArray, srcStart: Int, srcLength: Int): Int = + when (srcLength) { + 1 -> b[DATA_START + srcStart].toInt() and 0xFF + 2 -> (b[DATA_START + srcStart].toInt() and 0xFF shl 8) + (b[DATA_START + srcStart + 1].toInt() and 0xFF) + 3 -> (b[DATA_START + srcStart].toInt() and 0xFF shl 16) + (b[DATA_START + srcStart + 1].toInt() and 0xFF shl 8) + (b[DATA_START + srcStart + 2].toInt() and 0xFF) + 4 -> (b[DATA_START + srcStart].toInt() and 0xFF shl 24) + (b[DATA_START + srcStart + 1].toInt() and 0xFF shl 16) + (b[DATA_START + srcStart + 2].toInt() and 0xFF shl 8) + (b[DATA_START + srcStart + 3].toInt() and 0xFF) + else -> -1 + } + + fun stringFromBuff(buff: ByteArray, offset: Int, length: Int): String { + val stringBuff = ByteArray(length) + System.arraycopy(buff, offset, stringBuff, 0, length) + return String(stringBuff, StandardCharsets.UTF_8) + } + + companion object { + + private const val TYPE_START = 0 + private const val OPCODE_START = 1 + const val DATA_START = 2 + + fun asciiStringFromBuff(buff: ByteArray, offset: Int, length: Int): String { + val stringBuff = ByteArray(length) + System.arraycopy(buff, offset, stringBuff, 0, length) + return String(stringBuff, StandardCharsets.UTF_8) + } + + fun toHexString(buff: ByteArray?): String { + if (buff == null) return "null" + val sb = StringBuilder() + for ((count, element) in buff.withIndex()) { + sb.append(String.format("%02X ", element)) + if ((count + 1) % 4 == 0) sb.append(" ") + } + return sb.toString() + } + + @Suppress("SpellCheckingInspection") + private val hexArray = "0123456789ABCDEF".toCharArray() + fun bytesToHex(bytes: ByteArray): String { + val hexChars = CharArray(bytes.size * 2) + for (j in bytes.indices) { + val v: Int = bytes[j].toInt() and 0xFF + hexChars[j * 2] = hexArray[v ushr 4] + hexChars[j * 2 + 1] = hexArray[v and 0x0F] + } + return String(hexChars) + } + + fun hexToBytes(s: String): ByteArray { + val len = s.length + val data = ByteArray(len / 2) + var i = 0 + while (i < len) { + data[i / 2] = ((Character.digit(s[i], 16) shl 4) + + Character.digit(s[i + 1], 16)).toByte() + i += 2 + } + return data + } + } + + init { + @Suppress("LeakingThis") + injector.androidInjector().inject(this) + } +} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt index 61c506d835..866eee6251 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt @@ -18,6 +18,8 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.danars.encryption.EncryptionType import info.nightscout.androidaps.danars.events.EventDanaRSPairingSuccess import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.extensions.notify +import info.nightscout.androidaps.extensions.waitMillis import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag @@ -28,8 +30,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils -import info.nightscout.androidaps.extensions.notify -import info.nightscout.androidaps.extensions.waitMillis import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.util.* @@ -62,6 +62,8 @@ class BLEComm @Inject internal constructor( private const val PACKET_START_BYTE = 0xA5.toByte() private const val PACKET_END_BYTE = 0x5A.toByte() + private const val BLE5_PACKET_START_BYTE = 0xAA.toByte() + private const val BLE5_PACKET_END_BYTE = 0xEE.toByte() } private var scheduledDisconnection: ScheduledFuture<*>? = null @@ -327,12 +329,8 @@ class BLEComm @Inject internal constructor( private fun addToReadBuffer(buffer: ByteArray) { //log.debug("addToReadBuffer " + DanaRS_Packet.toHexString(buffer)); - if (buffer.isEmpty()) { - return - } - if (bufferLength == 1024) { - aapsLogger.debug(LTag.PUMPBTCOMM, "1024 XXXXXXXXXXXXXX") - } + if (buffer.isEmpty()) return + synchronized(readBuffer) { // Append incoming data to input buffer System.arraycopy(buffer, 0, readBuffer, bufferLength, buffer.size) @@ -343,7 +341,6 @@ class BLEComm @Inject internal constructor( @kotlin.ExperimentalStdlibApi private fun readDataParsing(receivedData: ByteArray) { //aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< readDataParsing " + DanaRS_Packet.toHexString(receivedData)) - var startSignatureFound = false var packetIsValid = false var isProcessing: Boolean isProcessing = true @@ -363,10 +360,11 @@ class BLEComm @Inject internal constructor( while (isProcessing) { var length = 0 synchronized(readBuffer) { - // Find packet start [A5 A5] + // Find packet start [A5 A5] or [AA AA] if (bufferLength >= 6) { for (idxStartByte in 0 until bufferLength - 2) { - if (readBuffer[idxStartByte] == PACKET_START_BYTE && readBuffer[idxStartByte + 1] == PACKET_START_BYTE) { + if (readBuffer[idxStartByte] == PACKET_START_BYTE && readBuffer[idxStartByte + 1] == PACKET_START_BYTE || + readBuffer[idxStartByte] == BLE5_PACKET_START_BYTE && readBuffer[idxStartByte + 1] == BLE5_PACKET_START_BYTE) { if (idxStartByte > 0) { // if buffer doesn't start with signature remove the leading trash aapsLogger.debug(LTag.PUMPBTCOMM, "Shifting the input buffer by $idxStartByte bytes") @@ -374,29 +372,25 @@ class BLEComm @Inject internal constructor( bufferLength -= idxStartByte if (bufferLength < 0) bufferLength = 0 } - startSignatureFound = true + // A5 A5 LEN TYPE CODE PARAMS CHECKSUM1 CHECKSUM2 5A 5A or + // AA AA LEN TYPE CODE PARAMS CHECKSUM1 CHECKSUM2 EE EE + // ^---- LEN -----^ + // total packet length 2 + 1 + readBuffer[2] + 2 + 2 + length = readBuffer[2].toInt() + // 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 || + readBuffer[length + 5] == BLE5_PACKET_END_BYTE && readBuffer[length + 6] == BLE5_PACKET_END_BYTE) { + packetIsValid = true + } else { + aapsLogger.error(LTag.PUMPBTCOMM, "Error in input data. Resetting buffer.") + bufferLength = 0 + } 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].toInt() - // 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 - } else if (readBuffer[length + 5] == readBuffer[length + 6]) { - // BLE5 - packetIsValid = true - readBuffer[length + 5] = PACKET_END_BYTE - readBuffer[length + 6] = PACKET_END_BYTE - } else { - aapsLogger.error(LTag.PUMPBTCOMM, "Error in input data. Resetting buffer.") - bufferLength = 0 + break } } } @@ -414,9 +408,11 @@ class BLEComm @Inject internal constructor( bufferLength -= length + 7 // now we have encrypted packet in inputBuffer - //aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< PROCESSING: " + DanaRS_Packet.toHexString(inputBuffer)) + val decrypted = bleEncryption.getDecryptedPacket(inputBuffer) + //aapsLogger.debug(LTag.PUMPBTCOMM, "XXXXXX <<<<< PROCESSING: " + DanaRS_Packet.toHexString(inputBuffer)) + //aapsLogger.debug(LTag.PUMPBTCOMM, "XXXXXY <<<<< PROCESSING: " + DanaRS_Packet.toHexString(decrypted)) // decrypt the packet - bleEncryption.getDecryptedPacket(inputBuffer)?.let { decryptedBuffer -> + decrypted?.let { decryptedBuffer -> if (decryptedBuffer[0] == BleEncryption.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE.toByte()) { when (decryptedBuffer[1]) { // 1st packet exchange @@ -450,8 +446,9 @@ class BLEComm @Inject internal constructor( // Retrieve message code from received buffer and last message sent processMessage(decryptedBuffer) } - } ?: throw IllegalStateException("Null decryptedInputBuffer") - startSignatureFound = false + } + if (decrypted == null) + throw IllegalStateException("Null decryptedInputBuffer") packetIsValid = false if (bufferLength < 6) { // stop the loop @@ -722,8 +719,8 @@ class BLEComm @Inject internal constructor( encryptedCommandSent = true processedMessage = message val command = byteArrayOf(message.type.toByte(), message.opCode.toByte()) - val params = message.requestParams - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.friendlyName + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)) + val params = message.getRequestParams() + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)) var bytes = bleEncryption.getEncryptedPacket(message.opCode, params, null) // aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + DanaRS_Packet.toHexString(bytes)) if (encryption != EncryptionType.ENCRYPTION_DEFAULT) @@ -783,7 +780,7 @@ class BLEComm @Inject internal constructor( //SystemClock.sleep(200); if (!message.isReceived) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Reply not received " + message.friendlyName) + aapsLogger.warn(LTag.PUMPBTCOMM, "Reply not received " + message.getFriendlyName()) message.handleMessageNotReceived() } // verify encryption for v3 @@ -803,7 +800,7 @@ class BLEComm @Inject internal constructor( danaRSMessageHashTable.findMessage(receivedCommand) } if (message != null) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + message.friendlyName + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(decryptedBuffer)) // process received data message.handleMessage(decryptedBuffer) message.setReceived() diff --git a/danars/src/main/jniLibs/arm64-v8a/libBleEncryption.so b/danars/src/main/jniLibs/arm64-v8a/libBleEncryption.so index 7c0c49b7e8aa0a11be777b6cad2624200c37989d..baf90143284bf75740351f28416241fa26698748 100644 GIT binary patch delta 3775 zcmc&%eNa@_6~A}iF6^$mu!{=|xUh?BR1nz(BOi)kQHW?Of-WphRIqBRsfjVM({$_v zoJ}m9V9VwtgJzP7kxs#(7H91M)>hE8Lo?cnP1D$DgO)UCJ_e^Id22Mc=kB|YY-sy; z&dk~0J0JJld(J)gy}R;BDxak7sg#7$R+bM`k|?Q2EQ(AK;*g8iD01siB?U~f4n!K|f z|HIt`+p50dj~-do@iT6>BF{liN46vDkvYvo&O}b*0#Y)v8<}TjM&?PRBF7_J;V7N8 z-GxsxkY^!tvME541R4dVAezMUY{UfQ3}l1QNr=3ZIw2z|mb=!b-V2z!9*yZCk@VYEytv$d7Ywxg^4j^ZFw7BlGay`B9OyDnQ;B%XBPK6j#ME zSBPn4G3^|&%ojwu4mcT?YFVHR+QwT8X?C| zO!Ge={0GF6F9`nw!oPtZ2BcJ6YLprqw?4h4F}ypzND7}ex+q+ovAmfQO5VW{;>eS& zW}cyjtmVf7Nj>wDkS!u%pE%~Ko(O%_G`%W6-KfOVU>x47f}r1IhF+7&+!|w_4cAQe zH1(8m&qFcR6fm3ZY5Yv6)E#3@fMsZPt0u&O7^@Z@L#r#sIuc{m!K-GwS#(C!=WPg? z?eMnQl;(&TGZ8Z;4eq1I1+xiysXk$H-`O57A$``w3RD+;&N}d=(Oz}1e6UKR zEP2ZtzCmoycFkXXk)|YH#E3pqx+{tg=qx2=XIKRz(o{Z{A%jGdUiCmvY25%&i$jwAwq>So6 zxD|gSeKjFP@JhDdadVz;Fguy-aZzS2XlzdvAw$GANJ`IoMK2>`PE%+hA9p5M)J-?Bk_IAxhU*rVp`LhAby-Jk(D?V8A z{XA;yI4t=gs9iXd?t|?M_i7|Nyt6P*BL!ea-fXQDkQ*RB?{yl4PxCxr$TLB{XMXL9 zlz}lxfBe{r`T-X$d#gLRSvF8#Bzu!D!aI=L6n(vHq(ddE4P+115=Q-dPy`(2tCugCZV7POt-b_lSrd89hsA)iE{$2Vcq!konMb{NP zMEwwoKEF}$ee;UsXjNZZQ8&;Pgz800mjrF{Fj2;K2L19`iG=R&8}5!a;-{>GNp$r7 zKB?zEHYdK(`<6T6L-^kA+u9HxKEJ3oPP_FJ)&ZptwuBEYsnFW=SbpS5-X6TVTQD@V zm+jCb-GLM3OH9X&%2eD3d_E_g3^)0{N$JnSzbyX^)fWC6gB4Wxn&~WQX&=7(_^qkt zB4hk3WBLw9} z$1x6K#lJ8P=5zsZ4&tHrF%Dws1S?>Ed?>!j*j~g}CK-DX(R-V*Q;4R|7<&`3<{o2r z5Vc=0W`hSR-MSxMVC)R6shp)ry$Fw1W`5g&YsT)GB7UFRi)_LihNiSwG<QYC7MA9E3w-uo|KL20Z$3<{B@i z+{(v^;n8K_vN}=EON)B^eu!nD-v1tBd|K6?PuGR|G1T9~{OrcpQ96T#+ZGSil_`dC z6v@X}rl?ViMcIqeRUJ1Pd2zjW7^_gk3KabjEG6Yu-8K{_!beyBR2TMEb!wW`PyO^y zJD-8md2ByUs(f*p%&!%(_J2;3KbR)VLKauDB(hZ8IrtryQ!xy$DWf$&tDSh3vZ|fd zCiP3KIFJ^oMQwvg5yiEOSYUtk+N?=_rAA_m?dGU18+$4$cfsxI=H@Z}mjLN&LJg@2 zN7f#Z=v6qpzL_>bn%`rs5s9eihYhIh68WfD1&93}qnhR947ltsG+0C_EMToGnktN1 zpcdFr=dn&t)dh#^JW1-VtJqrrf3M3+>Md95qhc9>^!hww%s;tx^@Y~X<%*YzEpWKr tV~qJ1c)7mNpk6KUA`&Qq)_?^X0$#(^|3?S~il#QWX{`ttz7lZK{{WPaSPB3D delta 4302 zcmc&&eNa@_6~A}iF1YKiuw-#rMR!4BSVUM9#WfCB{tGFALNvOV;^wEq@oK&P4yurH`{%iM!!raoMM z-wz&}+S~Erii0EWU$5=wdMoH|&{R+g$Oz)i26BR?a0YEMC<7D^ngrsDaDXO&lGt%N zwa$cI8psSv1@V@w0=Y}zM1gjoMf7I?6F}2J1|gGxd}ch4youBj7y8o>?Ji?FdfdXu zEYhrEK5Ooq$L4;yza$Wk&tqv#TMb_=kLLn$PZ?~l)JZFtRd1(0=GNbX{#w1ARp?Xb z0PoRr>`8qtEnuhhPWR0s3_doaDymV;UDv%pO zet;(hZCC}eRYa-e1wcEX0!c<`6Ui5H?N&v=?uoNHDuhqH@Notz9t*jNvu|3IuMQm) zGb|Mm9~WiI5HtLZhc{aQciBYv;6ZI)NLe>HKsPZgT za6!oT3Hxqljkh~Cx>fP0&^{xykx+5`D#^OFzIM;fy4so@J0GmswWqGWA@r1K2Bn0Z znpnDm5Q@LgF+$sa+bn#EIClEOM<^&&+Hv`mW}m58lNx-W8E+7fwA`eEcJA+HU!pU1W&SJS!dMLaW@WwK1KFpIr~ zUSNKEC*8-~Db=XjlX&iCAElh3nauB~rZd@f$9kF)Dx4Cpqm67yYBk-7oRPc z)G1@y10oXxC4-ave61mkb_4Hi&E_2Lyo}LQ5Jma@I-AFW4 zKl2qzpJ1~y4={Ju#03*b^ZQ*b&dBjnXZVu@61|?_ix$xdLpS1&O)*hYAnNn|Dgp`q zby2yK4Q5uR_LSCy-N|IPlNukscIMcWYZ!2?#^>#6sfnBggwUhn32`@XL+6B9S7>m8%o{p+_mD&o{SiijLx5`*iwt<$iCD{$SmdWf~ zc8;#4iVbC_>szWKE@qwmI+fVP*|~Ve<;-2%pRD+OzJEj5MT;&5TEq_7;*0VF!(%FP zsVZWkect6pvKt4wQr%5e5u>5c>poBN@RboVwm)YkKBhm;Eod4y!az3$J{hkWiGgQH z-jz62hF8kyg!g<=d@Pg-lw<27c-HB!$s4jLOoce3(f;la-;(T1K@F0 z^7cp@B5BYQ1p0+0w-E36gtP@FY71oF<$gmKv#4hQ@;oPRF?F%sdAxrj?=efiP09Il z{gvTviRH|>ccEm9oG0qoE~zr|szm%_jpqaW9K7)_xf5psXF=*2>nHpz87#@S`ti96 zZrf!IJwIn{oPO3<*qfiX3Ol2Pw*3uW)NYTCK6DD;S+z+tk#ZEd9>RP;#(j}phqI1-H z@k_b0WXA(b>bLFLyQ`sYXFYjz+oP_93m3ZT>gyWnw(eMmFY(St*6*#~w&H=kMohNUEgJ6ot@X_8Ir-QDMmS#n9ux+UQ(9r&lp{IjIMMVVS z;b&W6gCRc~{#EbrGaWf(=xpmyuzBc(wvj{O8^PvS)yRRs@c!*{~BlLd@Pp4}xeRzD|8KHf%S-%sS#Aa9e=f`2 zzze|Ff!$xp@>O8lx3a9q7FaX}2kdCc3`5ylaLrbg*_#$&qKTNeavxi1o|gEm?x?u9 zDEIx%(A%&e9JTSrFMbUmJr>wEE`=TX2S6w9An%5}5(&uW_GOb?9Po=Ei@b!+b|{o< zWTlt@i#vi%qx@tT1g^Y<4DsojZh{MgOQCFa*<@2HW)(#GQgoax=GhG(d&>3qPK$xQ z99eCHmzYVA2FSyZkMbDC4sdOs%JKyzVlOxkGH+8OegHND1!#@u5sm-kw!^aAq1f7x z?3>^Q4a)5D!G^y?4OF%g>`x=I+^cvpG=NPE8JGOh(4<`vE5ub%yA;B?(*BI%@uu-t zZsYlNG*#5oIVV2$^VMr~E;IXh^>n<~qpO>mTq4N-2~9)`Tpo(9IVRD|?C|;~T(ljPxz_Ds z-s8wNK{_CA-5M@uhbwbUF0oWB?)}R7MxS7P%(|gqJP%qvkev;=RxPrI9(H&`Zjx4H z4O8>k#~X5zc9g2A)X+fLl&Tz4%n$o@Rr9TxOH?Zj+u7l&TvN

UckZ`6K)c$l@i gVEh+`kFBjPVCB_`>`=95yq+7^s15_6kE)&Y-w6OSJpcdz diff --git a/danars/src/main/jniLibs/armeabi-v7a/libBleEncryption.so b/danars/src/main/jniLibs/armeabi-v7a/libBleEncryption.so index 4778aca663f1d0bbc3674de53b4fcf25ea02f2ca..f5daf1449d693d9be3843e36ac13b3e9318e9e98 100644 GIT binary patch delta 8481 zcmc&)dstIfw%;c&5)2x^2ahP>p@ISipJ-7d#sF$7S}V1+78Nn_(BOEdbjE3@wf(Tg z5!}uUQmxi&>*Lx^6l|SVD|VEzUfW{rIJULZ)Y0J;5o&FYbJ5)2Iyph?z2A5Ly!-op z`R%nIYp=c5I{Q4J;d7zkbD_Fm>Y~Mr5!4LDz?cBK@C;Du$4(_*c*H3R9^5N}O@Bh=e z*c3I8cM0auJX%jKVc?f|nj*$|43-2+C@QhEid<;a#GlFIq;2^J(D?K|GL4`2GkMX^ z+yI|FgZXw@z65#JBaktV42%UIF*7z0?If3A{)bjXUmibIGlsF4 zS&ZrBh6Gp`Ihe6cvfPG=y6LbOJ0}J6d73KR`Bfrg4tc~`sC*tOGi3QM&~P$=u_tBu zH!xurG*-%TGc?V|mP)WBX*`JbvXRI=d4;baKcCK+MV56m9$Uzl=O>cS1`TKIu-xz+ z3^)b@D9cG<6*vb$SSZVSY+*Q@9x!+p?zHgy#pxjSa!)dJN zk_|Gcos3PMNsIXx+<^(dft)SN&%+XX83Ysq>-IG(8N1OZ>Mx^zN1y&_826{ij9KLc zEo7fx=qY`$MJOZ$s8j&-ZotS{uB zYa;7aK?-GkRPbP>VBl#XbDRcA31i{lK|mxB1yG6y$}m(+Kr9dkBmg4-q={5uD?@}C zE=86KAU&j#hTn0(B)`buREDcTDu^&cBKK!AP_g>k*etH={|~1PQVL*^TZyoJY1B~g z1OQW|Lct<)10@+1tt{xkh@s>sGJ7~c%TgiJ`vJ6#K%w}dI3<&))*nEkuuxzuKz^Y8 z1xgGmAprqQ{t1*|R3-xCM;uv_Z^*xaf^a=l$fuOzL2N+aJn;9&^Z7zd4z5_brSukZ zEuzjM>4sg(*pp3x$RXg?JLQMTcSusRV+-c(-8)&lmJFD8~YYLPtdbjFxJQ zMT6;Rp@I~As8AY=f&TDF%It@W0$P+z!Q(?;;<=$(?g~v8mh!gHXyF163ES#4;vPt@ zE-3S}Wi8SXX>27%Amyq*}zQBI7F zZ6JnYDu{y+^G#GiE>;pF7*)gwb~P~qx1AWCttEyxb`m4g_7EeO`-tNhJ3x$pA0|eW zT*OGA24Z;bI5GTlf*2XtNF0nK>h(dMjV>9 zUQ?g1x>oRCCvF7lOZwCo_NmY9Q@8f1XY{F$N4-9AV3iP}V!LlJw$;7K=WF-y*ukTn zzedgN^Z8EXAsoln+Fo`2P1H7OtAlDZ+tfTr9CSfjE7&iJ?l4Uqi&xf!+M;aViuy(c zcV~s>Ja5(J2l~}@0(up7!t1qJdZ}l~-9dVmsJ!TF@p&(F2DyibgY+8earnIFJAEy> z+Ta1Mij(YA6gI5_I-lafLtfCio?i_d%JCQDSq3}(s_je6Gg z{mDErLZ2s^jQ_IxydUteljv9WREG-nq8JBW*9G{r7d#kpqs7XWjpvQcZw2_k2ZI{JbzBVdm!XEbpk-6t}F@2M` z9qr4}v%S%srEukm*?O`kPc-Xawy~~oSe2-6PPB9-^FK!o52}{5RP$R=r8!lmCb6 z=rMy{@Z^aF*h7`PQ>s_;w&?h{FBdU(6t_MTun#Gb0PI2AD?l8eTEtV0gJ*QFBIPTf zegn4RU;2~M59~+Kespbh7MYW)4@y6M6pG;@qi3X81m~^BW^-v_{+e-8WEFaPIs%51 z^Kz5RpkW>V#uziQs@HL8Xd|~dWVbnFw=IO*zUQ$+*G6;~M%s=R`n**gBgKta=S8fu z-gtBkKQMHBq-%}OyXK)~)+d)0(lU33#-!P$Wzr!3u;#LuFE3FkFHw#q7X5?bA|NjJ zDts-Q_^e^Eqq|pPd}%ejT7{+hdj1G{qHOi0wdkwX`&!oVnqddk>sB_2xqNy|O22ib z{_NUk9LJxF85(Xbh1u;R#X~UrAardvuH*Y-CPX>VzNS5(o1C*fxw`zyNLB=2O)rn_X*Yhn7rYh?OunEqyk-px);d4jQz7vf$D9Dba!CBU!+e5olyILx0j ztr}8Ru*^2Lz~{Z*Hd6c;7M+Gg4aTwjj%k9^T;lUKwe_{AA-Q`6EGn+fx-1?xXbY%M zVgEw3#Oq2hFJq(21H&wmsh34-BENe#p8H<+(_q9 z%v9JTY(DS!K6a9pOU2#GBW<^fY9&i6mp`y{a}oN@-xT|8HOsb+Z#=pjwiX3!eX)pa zeX)3pE%JLtb{VplAGfo_{>=}ryu*WW>6I-a%bP@_JNJKF zs7IFhFVl#|Uo3O`-MGxL`dt3(qF3{!+3d7^qrE0G;%mPotp3=(dC9nz2&#_8T%}ku|TL;_y-Fy^sxDoXlP{dX;_jH#_-Uk+ntX{+Ue58 zNG22oP5$I)*J_{l$=0{U_t@{n_ZjUvxQLckh${Vi;(I(gVW@Lbug^1DCs5?z6(i0m zzm~DHe`O7`n~Qv2ORK*nwYMchZW-O%GNtu_Hygt+-V|PRBtOztZ}-PdoBtqgI%!AI z&LV%{Oug5`x_sK4O1c`PCG8Zt)2p}GNV!pOz|pC*>+E^rz~q`tb3PraX8ZnbgX%5Y zGotFlu9Nq@J-67YCGg;Zd5nGVC}VE}`+(mAl|a*M|J}0E6|SjP*QmCIV&}?gO|5Fj zeeZR?Y|20x0==x*qnJheya9z^V<6m*9t5r41 zZOU4fC}3O3Sa*xqj|o^?s8uJ1T=lgmYlR(_CA-9a2CbF)_@N}D3L@j@lcJoCte0J? zYGsXLn?lwxOwtj=6gz^;bIL<8C&<8{kJT!7s3%uuh9EI_i9t-YgVlvv&zI*~&LJIH ztzc%=o)%w=+U3Zi2a8IVY0j^$(e`M25P#Upk#5*q9wch?O8$pYS%QXtH)>Gm#GAFV z@W2l=A5;AC4c8?;V06lWYaW)U!p`VUZqV=Ib4Jf_Hpp40Y4)|y3Bc?^Vlc+gnUW_a z7~hrh>%RB6XS6%ec1Uh}*K@E>&IWqll6zgAK+BuG;{z>k$SsFV9z5Sji&fuM;F?P? z2Ei>V7~?lGh0jbLlUaaUL7q4s2BjM-GYxQ>U(tA@*4kK(+i`O4LjMTCoP}|%=ueRD zpy<=z_fGThhUDDnb2upn_C9MQBnM5&679xNTb^j=F)1lR34b&t2EU~#Nlpja=_Z{g zIxf&nn&y2{il?6BEZiJv&idqPw3q0s@8WA$Qj+8|k_3Y}jU~nQ$_fKZih^`p_LcuR z;Q&O1M4J!R!`id8j=bsqkQdf?kD!Ar%WOfqdX+DqrZ>*ZXKw zqJOb`udMKNd6<2^W4CnevZTn1p>8cw<2>G0KLXwb>VQgM6YxtQ*p45C>ArVS2Y)*? zZWe7!!K$Dk7$-tG9B|)j!DB&*vC>gv;2S2EGIi15X0!fLZ2L@Gu})2ED0Y#ru#O_zXAz z{5}&ewVO~`3Sz*u2I{h_q~Pzuxdq6yhaKi#rhuom9#n}BP04Km{m z|2nt;IEwcwx)is$-25*SN@LGTk)y|=yYP*nb^wl*ATdSXD5b*Y@>BeYiSzMTv47%j z;bopRsUu{LG((YSf-iFT^z=ExB>r0ZDt(Z9sN5r5O|c|VYK?>h$7z{~FEgYji0g0UY4^Y^AF zDn@j0_w>P0BS=j$sR?#pZe#H(s7l1#^bT&YOpFPZ6!nLqFqqX16%KqriUofPSouoJ zIN>9{1HW$msU=?6#=9+PnGNm21eVy|tT25gGJ{6iU{LP{pKKRWgD$FT6+_kAH15_Q zWivCix2WrwTTz!Q`Ldv$7tAo{7PQkY3fu2_i`o;g?7!nxKW+?Tm+-CO5b8gHwYE^a z8?oaqq@LQQwdti9zY}u}p9Co{GQ0MO&g42tdh*-(^%rHIS}Ifd8<``79)31+WaOSUysQO>95UI~b_v2g zZ&jPgmV^1%xO(Q~)VekWdggWc(%}9!MQ!3TTDr0A8xc3<9To(7K(8M%+jz;$5tafd zK%Cm{c}v>Zsn!(6{vM7uEAU_Oh2RA0BG`euIPLMBJDSpsu8=!hR;r{8INJCZGsjL& zmXxGI$=EhErW{RXYz3x054-}^$IUvRP=(zxCh^a*iiU>WGTC~(18?`Et%_`0*l`}fXhv<73uhatF@QQtj)pU?g+PtVqey@ih?OYyyM0J;O3GM{Ds-}h=HBuN0hG@9|@Ulw#~5ND@gUPtUX>sC%-@2G~9mk z%y4{)gzgi^RDaak`sWO^J#P)MC)tG>xT0n?*7$+XoD;9I-YgnkUoF$S5Za5(wS^nR7Qr-Vsj7d@GKLtJk{0Vpus0UoYJHR1eKd=vY6W9&x0)7W<1GWNH zz-HhT;3c2}_zm!@V0@l?4wZicegTvLYk^XL7GDjl0#*VmfMvk5z%#(pz+xZ|cmjAF zm=DYY9tDbF_+#KXKsGQ7$ONVX8Ng&m` zL;^#AK|nYV3iJbXKoFn?zUjxmooAoE7`p{08g<(}b&Fnvmh~PjG{2Lgh`L^D4Nx({C6twTrUMZu!U8f~oyL zmw((oFfFX=_P3kCq-P1(<#M_z@=+m+i@<1S+rj5h`4UV9u^;>fS-_;o0j34^fyqOA z<@OU`(sK?>8@MXVZZM7eyDVRm<*3^}X9KNRhzboTCnm+z0cJn?+qJ}y%fZxs9ef;I zdB^8G0nYfz=WGO5fX{%dz_fwmVA_De>o;gFm^R=M{Tndd^*KYx75S);0Xyr{7Jeht zf3fH%O?}1FQ3@yh9XU|a@aQ=Xm;lTKa)5cjv%pHA7&rxd3S0ud0z&XKS_V7^wBp|O zC7^`Dg=_ua_$^o*H*&TIhdFM0(w{x><(gf=51M$^(xkNb+7;J_N=T>F)_q;0XT7(wN9DoV-0g-`WjW@gA5o+y~ck z;n}C1ZYcSGM9lxOc>VongH=L4*A>L*$W4Uzd0Ih?nw+HNPZY%K$W4S~{vt-vb_rGd zAV$%qH}Fpj;?=dN)$%(9@fvddl~6uxWt@(pLa^|hl`&%je)y4GBo~SUmCXP(V|^*c z6lc{Vyl&+%UGIMv@Y5?}G_4De2n+Z>SH`8Cz~?wZT|kMfgY>*3*C|(||7Cave~;nc ouL$RJ3-#)VH59#P3ggw%|1t2F3*&VbWR&Gud@ra!Qm7RE8z@>^nE(I) delta 8802 zcmc&)dt6gjw%#WskYLd8l2?@QlAxeLLD8ZjV!%gRe6-fqT2#=0JgqYqo!$m5Ge6qu z6uNB(8Lzc7w#8PbQP5gj6&=fH>->rx$7&xl(drN&DA;;)>;-ebb#j8V_x^GJyZh&t zZ?FAWYwfl6+2?_+p9`&@3-yIFOP^wlpkgRG#stv0r-3pL_WCe(5%87!6=3};pd4s; zb9s8k62`n>)C(v*;jH!eKgy1+c$h#>-|;07+f~`RPo?@-Uj@I7D1C zfw3HDBKenC(uZ>xQ_KC8;ML<9YnJ65=chleXhGuA50gP2&H1&;-f!Xh4{47L^}F}7VEaTO}B&SMN#C6ix6!~6us zo{;5#hYJB=jMd3<2Q;0=lImcRT-=ZL!9?t5*}_%GSEnhi*k6~%?mlvb>NM(S_*UK8OX1oD7@h1Ni*4F)LS*m^7yhyum{-V%*U z3=j*%0SN#$4Ko5%;61~I$8d2nY-yGXP?-$SGALA3W&pHPsnD^N#n?!O&A_l+shIiA zfbXo7l8L|^0Kt$7)+>z~3!VyO0aOrp$z4gnPYR%s1%EKI%KQLwdmP|BEy;Dt2ra`~ zu0)KXCN`czMXgyWA(&H(N1E-u#p&1*iDQ* zwU-!a+eaLS`wTHsdw>}Euo2@}Y9&U*ju8hi_AxQ`S{v~QD`RJ=g3Wl27#s2eF|Laa zVr=|N#0dKpVr=$rhz*R{iLnoF5RYQaL5%(9B*u2>BgO^t12Hy$NQ{IG5F_PEd&*7a zDEk{XN7`SptNTvgOn!>7mb{SdLK$m+<+|$A?bqXf{P?D~t{+wp8CKU0t1E}q2kt$X z`@^uh6Llqf<0fOT*tfdf-Oc=3=mcvuYIe8VUA-KsIZ|QXZu?SHxB1s=8q}})aX&Hi zf`6l6xhUF$)J-f-)evZoG=D3Gv?;kgH)8(g9Cd-W->=CBy~-w^-#6xlNIhZqLbc2| z;-b4V5OUyxEjhjhx2x@zqTcN~duxwW0ALGx2r%q^XYZq$I!h1;@1+^^*eaY?OUR|L1vbdMKBcjur?H5F5f3%Nj z+r`~zUxS|AZT4J+ZMm4IC4ZKSChf1ytZyv5GHN@FS$&iE(#QnAMoCK}w?>xD-)U$U z>)ZUW1_eUC)0rYA#ND}ET%;9@|MoT2JU-Zij$2q*BVlVh;!tO@=jMt9+RI`c zPmh`uy3V;=EW{di$}6RMJ>MJ^7hCW+W7&wP4cjLTXoYM7MgxZ*!$tfUKN&STw_U82 z)USnsS}ew6{CwGQOS@Pjxm{zZ&n2hwwSF0=4?{fy#hi&^2|`$mCFhfQ9;%-fu@gP^ z9`4^2 z!Om9L*`%Lb!6%PNi!fEVUCVxAW>a$iIx=G&6P;QqnK=Y`W5s3BBAcj_O;p3gs_!T} z0XJ>L%5v-Q+n&`2? zD~FOv`#|$j+~k3OEkS)T4#d3b92O%KXmDAy z!f30u1R7eok70dSf8lEL;X=3T)2>AE44gVm{rbavt0CQLE5#+%HQcGz5C=kH+{Xq<7pN+NR>SDmq37USF2_;3qHOKLt9OM6LoDY?$Bz_1_}Sk;#gqJG8wbjtb6d(2eFcr9mz_$>#bwR^-T0K5ZuGygsp^#tKCk*TGNT&y zqp-XvITNdTlgSe?K#MzZr_iV}27Kf0^l21!WvvVo1N7<~>f_oZy$YgM#kVGfS$(Bj z^>6W{rcUuZOZ?mfJr#t=Cc=Bi$|ihv`B%@c4kVR&k2&Qo)%3dT0PJN+`!1m=Fz3_i z{H$}>!9t^866&3u?oN+A1?)8dH50I=I$Qk0U*$wuqAY&=r>l#G>1f&XS5AIBX-TTa zvkfhNyXvwP2mporzU!8go$A0_PTd6L4|<k5iwd`;QB@gyU+t?^-t0v{zQ0&nHcY7E<}66DA23 zZbjX~-oxp-cQ+))^2U{X4nI+3w9calz${!f83@H?J6JekL^1E{Qyei{+ z-j-F;ysg#yWQC`zgDi_H-$b9r!ji^Z47D4P+FSD&yAFH-oCFR4rt!F*fS@J_+kj1g z!f@XucJp^rV&~BU6>K{+`QwOq4uQDux{iBprM|AR;hql;)aQ}|k&!D>8*SPLE6D15 z7dI-%JaFP$2=fOMWAJ-*;sjvrhz(ECODd#UC*}>HCWW*iC5plj%JlVJ3evEib9@b}63Dui%~P zQ{Z2Cr%J<%m;-D94o~-7Qm@*s@z2uAV*VjtGFg515F1_ND4a5WVv6>vv?X4wzQR|e zFBU%G@1?&X?BNTi_5>74GZaPxVzGwLowiWO=dVm#pYV`e@qMK%8X=T6i>~FFxK~G1l#4+Zm3R;P|OH9RbA@ z{^N{Byq)uhmMXsK;f{ym6&*c%WTsKu*5lJ;FbBj8x{mhn?95ojo*up~GfVMY4{y%Q z6jt$@nK8m5?l*I`FplTWoR;h_O&Em=)ez2$#ACv90Ml-tkF{{W=Wa{7`QWBUO@dvu9`hXn8>H&H=mcyjuRBTVRmYE ze7BI!jNKgy!&Q;#e5D2Y4K46omoU-qqN-6bM)j(%-Qnlc!3^D&3H}B*PZwC zxyUT)LmGqa1nKGM;7ZWXXTBK?+UovP~g8m){L)T zeM(Vb=<1A5;j`w96H0l}oWuxS7vA>#1Ku^5EBXXs&^6#NnCD~u68_el=@b3C6zF-h z&z*|!I~0w^)nwY#^|gqrbypS=J!&WphaFs-Jud4K6d+HILDx49cB&S4v7I6K?twen z%lJI85%oWTEAco$Ydm<@w``j&;O>qhrL+LMgKx~9JbkyMWDk`5!SNA>KZ5BI;7LFx zKsUwhHh-LgT1$*&M1!z@&~?lqn0+19*DCmek8yqD?=eHiiG5hmWn;^kxy=gY zwp+&%dAYfSi@Dmsd4ae}@#*O%KE|BFhnDmFu6g;`yjuqIfNR060oNn9E~52qeDbNn zh|8!yrsE~Kza4w0mxlb%JKz#~pF;DGIMF@{zzK@_{!x5%-tOp~(vU_B*^Ni3H}OE1 zg+U`Qs2TO!{9<0*_%prVb_sEUnUtOBO|tl4n+m7Y8MYs5`m!`ioBEXP#DHsjuNcqA z&bNfu_EsPA`Td4N0Sip#Ic9uzso#<_;Hv56d*&Mwt~d+g8T$+T{P>9SeYJVy{1Efz zoB&IbMQA`M8j4|K4gYR_oU+yF8{gu;AX^ZE_`?fR(h2v1N6W+ zc)KYUA8Y;b2}FxsFao|4m<`d1r`E%z&s!umkB-v(1qnE)gK zi9iAn2axe-U66FZ58lEHvFvHs;>QA%~`M$4LP5Gt_PfY>Xj&}POo^iV` zd)l2~npbzlZM}g0v;S~gJHYyXx~-SM#_!zLE8vVy&$!kukG%t6jJGl;Dl}n{(=(wD zOcNS=-PUiw_FEoDh^bwD+av41WS|*L?Z^5&?X6&H59#-`XMssiDVP>i2_}cPfXP1F zhsrq&xB;dW=K_X!B4fH~5EJov+pQyj<6_zt!OU-GT07HVCts^FLa<57`X8 zFVsjKuhsR`H}<@=vuB5G_UzdV&CWfw7=tOlalYQ_Y}z@I^?X>{W2@;oT-V!ptlL&I zysLM6v-72Wz1#Nvti8B=T}4aVvOB(3`kR8cG??+^1iS|P5!esB51ax%0X_qwannfw zrU27{GT#7o74;2^s(R!c|Et3ViWk zhPKbZckjC^l5xx_AvC*i*HzIm;V?Jg zc2_im2f?J_KKLwTd^fL9@YO4pT0`L6|0Cl555`;WKjW{&3x=jJT0Hl#o;@8#&^F`~ls*rL@=+o=sRMLM0;lExNr^&=7%X|iF KX*smcNBD0kPRmpP diff --git a/danars/src/main/jniLibs/x86/libBleEncryption.so b/danars/src/main/jniLibs/x86/libBleEncryption.so index e5ef3a17a49bcbc8d0c88fe2450c6e9bc0ab3b2f..b63dd5a2344d76a4cf40b9f74dfe441de32bb97b 100644 GIT binary patch delta 6218 zcmb_g3sh8P9{=uTpaFqF7;%&l2=IYoJX2GApbifc6?L>ythUG2=BAyr+}+rL25N>Y zyW{@p9DD3pd#ttRSW(Qf)*;sfAFEcBR8;7aQjJBWWu@hI_xHc|&H!rJcJ|Ks=Kp=) z|Ns5p-*d~e(w1i>-;L9sDiMN9xWE@Dgaoj00m>@9bjw0ShY1m3;L#L~z&8TlxarZ! zQGLZi=w;K-_APzzweXa`nH%@M^TMl+JvTi)>&<`A32D~Qec&AY z;!!zF6>`GFEi;AKg~9P6M%=>a2|~OI!0m;AYm0=~W8gobO>%;(I$wy#42o~SbMy6R z;ENL{)kgt)#tN~@7_k~Kbt+VY$;|OJ&~M2Q!ffE%VB&Q{g}4Ia7;gu@I$DU2jP^dz zZ2^8N6lVPGVIo%aqzln(5cE=RSb}R-rVw`+JtM#}r$C4g4Uy~7UK=BXYT%n8Vr?vF z3>A_9J7DzFm*^sDLAQ210%FkL%_<>ST}FF5;7-WfX0-npCKALJOFzMr7|=Aj`K_=G zVf2ej_Dc~o(LAAuV+sk{XU2aN3Jet(C}3ddvl_KwfHss7C`l-z=t1)@i;_`eOae;q zV@|_Sw5$Rgi82bsgc6AYb;J-9j(IFqNW)$5h6u_*Rr^>s)+eY7%jA!BU>#ZKL=<>a z(+NP!Uxr$~0>Vq7&#u*E(Ca@5)W(kvM~WemmypcU*^Pcwus z&ob0}*?c4_UP@Zx?lTA2m=!f`pDYog!95=huPGyNl#-&0q=%_8I%WCqfN}SkbYz3F za+|6yQrBhJDgt+Xud42L+ln^dKu%YJK5(0cGOuX6+1IdcjBt8CSh9SXyRT3acU8^K zF-z!B^evK~3S+Xb+72gJb~tSA)52265mYMs0^9zhs>eAQ>K!(vyw6k93M%h`z!T_K z94FlEg{!VzQQ7AGx}kL}sLmHLX)z_lUgO${VM-1ETUvxWkaOG4C}or0Tr9ai&XGFm zYo$eC;Hhb6(jZO-?zT6gl;?EXyTaU`491ike=B|OqF{YNlN3$n*U{`5$#C3wplayD-eW7~2Zx=n`~O3A*F~~s zu>bm1|B1%K!T|>IWRD9PS%QsTDUXR$oYBg9vr-l3-M)_!;&bJ&1ymfbj5u(b*O54F z`tw4)*U`s*I$lN}$6qQvO3?{6=^%|x@JSuilCWHQmSU|dhj$?5AjE6W@Gi|TdGE!+$__{3*yDMz0TFEq^tHX4-~B z>E*U+=>zJrtxOE6Yt^~x>bhy(hxJ z>822mK_)lQEc+j%8|gJWdnsVwEEj%8_l~+VL_J92E*g^DC=qQ*X6hG`H%qtC;*@n4 zCO%2sDUH&u<~veNvRrbU?oPXNM$nEyI=m9lUHJgJ()}WzZQytx{*}5cbSVvtP&ReZ z#`KYiFB;T?P~D7@9-_O`v*q6gs4IPgxaF@(9QPpL91m2uv}4DU*guGi7yE${X^yS(c=1HS>Y+<$o; z0mWffgi`&4Ea>ZuJbCU%G=6l695IdV9K9r!T>$g={IJ)Q!3PkfvL}%9AuO!y@wz+c z!_j$2)e&Rt_@6YUR60YhF%L=mXyn+Lm$GjV>1rP3IOX1cP-9jb7i!aQ$F9++}}f^&Ln0WHZIYtndc&AOLPWSWzD0`dP=)ti06 z-Ts~+@mu+{WMb)v_m5n7o)01a#Oqyy9MPmZ29C^ayFW*#a$kLgtTc7d^?3=dT7yNo&r>AV7lkS7 zo0J_!hFErV@z!t;=J=O^6$1#v2H15}S5|i;lI;zxZDa=8bAxvJfq+}nf^FU`#V;&% zeDi=av9X|o`;Kep*I*A{DUSaJ{h@S2>~MqA+kCPF(;wqO&iwow=FObk+c`5ag6~R5 zP%J)tKjCbe{!YI$yJ&m9J<3;aMFg9arY<^?ZWvYsq%ZQ zGZcs4y;Jf!{KsG6MVnKFk(QRonv?fKo@c+_!8xNN$|U#67_FO>f}$Zl=`YCO3NMefAN|#Pef@`KveL!lbLsJ(@yQyee z!VtrDoU!+y?UU~tO^2qnfUv$WDOP902i1*czo4}rPQBN2)& zpAigrnQ1_*LMqTp{RHv_3DRd?3FobunYdh6CGtF~dgn2Zc0W7*CpOg4t#28a!&Q14 z`tS>q;_Oq_BjF13yx-*>;FQaQ+jmp<%o4es^E82`%o+vPFPl|m|)d_W^?who*i@sXFrbEC(gV~uwr}pd zq`~}*tf+T>4qwtlM-s&r&!R=eso{Zrs`?Stlvu5YqfPv#lYzoZZqvW8@GxTNS2`jU zovTqi`)OBkn%sDRqDqn@IQteIL^Vy0euXY8NxN(uRxEx{6GgG+I(c?Xc-ej7_nX{d zVQKMTR1_U<)`g5i&bMU)<;PjKRCJrMIQM~ONX<2O8{;P0p z4D&h*x^ZVzbr%e_(ye8d@Q!a)70(lhL8}xZn~xh)piNcd=&xlHTsRrQIp zs#?28RSz=UtE#5}{RpECuQH8@S|Q-N{i=E$pdYXn@Km>|HgWr~s&)ak<0K`%M}Lp1 zrUEWKs;ct=I{{Y%@;TiHXoXAt->bQ5FDgCgXzWwfXecrl-Y5VpfW<2T{kT8Y0@lJ7 zyiTdjHS;bpHT&irk+Y)lqKUl+_6R>-zhJ(oM&U=rEZn-Rfcz}T#Y%r)kbQLrNcq_@ z4_^N2dv%Qo8N&|m0z}e?v%oWqKqo_fp<-w?+I9nG0`i@O9~*hbZ=~r9Q!af3ua@xG znl3! zX-c@JCf&L;J(3mW(oPS6iUo2hq?eYaM6lSdNIJSSErKPUiliuKTDX-RLAlQKNOlRA zYN~XmL^h$uC64NxDN*c3E*mD(GtT6wDRYG2GE>l7&g6&Y95KNPM*FCfL z`S;%c```cBuQ~LlaOh3JwP|+we8#8*GCbjo2>^~KP}ZrXOGI}7V?i1oP38jL1-$F| z!_z`qiWpPN^OvU%?aTTsWIfB%g!-soMt?K!W?f{_l`Vfrd3?m+oiUeQI>~#4yrk`r ztUnQ`boOiC;ubM-yxYRqNeGKzVQdSi@-i5^14!+KfaUWTJEh@eULi)>60;e5MWYyO zV61Kf8hFClE%`9up|Omu(>S&PHqBz}DndXKufT>UM=@s9@Xc_!XDDMcz(;s9@J*qN zWo!7;fSE9UI|||V2e2XRP%2~f8pB2Dp zAXZZm3z#>au@48SDk_2AkqP-pph9-=m|y{j1q>iFnQ6{_SK}3~@{G$g+;(y|lnh1L0ptnFj{@dWR z0Pyj@1kbk7_d$AVG{~M*+b7mDHVAA@1VP+F5U!ji2qotT!tHi~aQOm3xY$7uL*7Xc zVdx?Vr@9FuBwm7W+(*#N5?Bva;LVo=VaZ*Bi0OTTLG`~0i4fA|R~Nv-t8P zm)dueFha-D;;`6mKVvpQ)3o; zpMnf~OU&wKS6@kkK<{0xpp2`VpK{gi9?eRepDbOm-0oYTs9Ralba@Hqp<4tGzaKi$ zb^?JhHCkircbTaQ-vN`XzFJ4!C$e1YdJXSZLn>v3b3v-Xxh&P_Z1&n7$g;H7=d?C? zD^a~hA7dY;W-wK+jd9d9LGnOui_U$*yByUt$=YLYS+H*X>b1>eZ0(6L5a+i!N4NQv z#oQjY%GLszQU$$D4b1M%{7F-Y^t{?!BG|8I3hmXE!ZHYORM1@D$BDrGX^&AV3wL_Xar@9oVremN7%GkU`CXcr!j<`i){IuGkK%N#jIWAF5*G7)5ivqL zKN#T>F7VNjD}?p@pCZ=`zkrm35~n#8vy8#H4>Qdd-UoO1t;mXzn=ltwltr~eim7S> zCUB|BC}UO{%H!wsT6VGKDpJq zGQebxeo08>Z%2QN?vr0Y_b_f5zD-OEA)o?cUzj@U1ptN&ocIzjjq&yL;fm+_Fxv$;F=pM^R;$4pULX|5A} zH~DSzE5S9rm8?dIN##dqs7s7|X6gj7SN;EnY=!A zX(B}!(WBiJ0!14wX>FI+jnDx)?f3>pO~#k-gHdL@pB_~xWb;3adQmvXSB;*NM4?9_ zl@pisOS`9C5mp)QZ}a1$OBE{dA5zU9^SU6`-yTya2oZc%TFtUd{cBFalJ9rjUKY;a zle4(nS<>a)(`l+2uW0h>BOVR62M%{(7vg2@;N59@VvrAE<&;a8D0Wq=Bwv)Jn_ z>2~hv(pC8P9O;i#vGTu3MJGQnZlkIqN&I0Jk4ztvp<39bTUhW&_Oibcdpplf-=ChN zCIklIql-w8r~7X?_UWPd;beX#y>P@)P(5lso5u4qHrO5-5w|)*7_kf`ZrxI`S1NH! zZ|R?zL7gskQ__1gRKeFSeh*rv(n?mS(7wmR#8zx|>z?2Jwy$w>r}{M(cS|K+X{}qT z*FHsOs5;q_Io1Q-cRTsE@uSijG;*uodhO%G-c*@FRqOw~lk@Sb1Q-8od>r1P6XJ)u zKw)Zlk0x-a@xJgew?)SAr4wEgYWUX^;_!}{I9G7+)f2~L)tDNM_It?MU5fW;77F%z z?WU@Y{p;co zSNFg#9_r4Us&4AyJ4k%y(GPpYlN4}P7mCUlQqwV{x-dX`OQ}8~*pDkV*|zp!`u;W* z*HkYSCAXFurpB*nrrAw1jd!dju(-xy5vwf$(jK?e=qK!;MRFeqzwpW(FxS=+E)iuw zA2%$n~rY?EtXicsq0!;-yY0%?Al)R)5uIw zG7>|H?_BBdw0yS^{`RD-OcG9_>>kQUsHHP!?}|c6bm=d>1JcROlg&vr)lnEwx8x=s zsm$Yu%9X4hdz0X_dak{T)q=k{F+OW=AHFUSwpx!tHWub%qNz3wHOYF+-eg4Jba7q$ z*OSd@L~CjYuDJCJ&^X#82X#*#wUW=u8at)jRHe-D z)^h*C10TNnFU&K&yG5EDGxSMj|2WRGCK~r*+NwS3xXRnIo)OQd@p)5T#S-x8lmj@W z?aMZcO#+`Z&B{&FgZL-e!_fKn?D^D+UV`MnO4V&@H0P$h@A%LWnk%_He8W@)&5urv zCSLRO*q{hg!+~%QkDZXg6MC^f2B&dzfYoZSkqAuQ_RF9UoC*Xq$1IBS67> zW)%#fgf}%5!7p7*rq%_ozg3Jzf*AFa)5jb>c2+1tn>{ND@19vvkmqRPhjOCP{B6#B zv#zF3&~z(3JZ`q1Kzt;DefHys+n;AguTbR#51^_px#CdHpV$6H$?r~eslbO>rnX^E z8@!iFe9|5yOwMHI-zS}=l$nf(pW!*VkBO%#&mwtUZXBZCkXtssrk|*1l(x^*$n1B2 zZK|T{8Jzu1jd=pv{KMSjX`h*@GSyzGxW|4?Ff|&C_Pgk%>mJZ5z2Yf@ah2W>sKL+7 zSU=c*$haNH>*u5)a2My8;r7>a3Q)J?jl_FRo*pU6eH=h~`sMz~y!jvtv&4ci%|h8$ zWSK4|o4MUGHKvII;OBz-YMOZXdlup{&m|Sp=ISbnFc`XuKEy98WS+V6V;`2MrCoK& z=NJhdH!n7O?zYX=?HhOQ-LZRX>2|hjr6G2e>^Ca@cCSKe@!-+0S$v(9tfUEUXUv*uU6>LWMzAL-Y> zb^BALJZD}Ge|lbW;G$EqoXy|MkBkUN7eWoVH%rAp(gL!jm7kn9TFg7mug^;s7o6ck z@{>hl8$di?ly4AQ+W7MP7U%reASCC&{CEP5{R7Y2Jk!14%)vxEj3Rgq&c zG^rQ)Yx$$a6BqfP0FL~X-^q^;Jcj+{IQn&U(>7X2BZX#x%1Z2R>TC}z(K5WD?mE5s{7e4tyF z=|;F8aX>)pAU`pMtrE0_J}wrF7TbM%96;S|faKu&Ks04jEI$dj4Uq2X zI`OGSNn+rp_~r?9GjfN~Y( zPW^+02?n8u$1O_;CR?c#aO<*!K(cf!-?}U%m~5qTnjZue>7gol(Q2j-!g$0wDf1XEO~IQZHUXh4lhBCje*2vKg~5zWFG{5K`>A%#{{Q33`2 zK}mejq5{Si74WZ1l7rO0fq3%rV8VNW5*X1d}N)0!2i})Xx GfBZk=)KP)} diff --git a/danars/src/main/jniLibs/x86_64/libBleEncryption.so b/danars/src/main/jniLibs/x86_64/libBleEncryption.so index e4c02d8842ec29409e009d2a087df710386175a9..871e79aad523b93a3492707a7faa9d91cd22b1b5 100644 GIT binary patch delta 6673 zcmZ`;3qVs>n$Eo>3P?<#MBW6H$V&wj5S3H{iN*&?t@vuiTG=ku+Ob_7A5$7IVuNT) z`#ZDNjw9{Zovo{`uVSZl6jnyjwQ5&eJAI-L_dm~n z&OJG~HXjt4@o&rH6>go}G^#Tzya3V<-CVBl=J|c;BYK5@OQo8f2$=0MRJ#n-E`tPN zLDUly6{~xco))T7|GyyJ>YB3@{HQ{7_p5k`LjkO+{x`HQ#Og^I zsi13B?H@u=5#4pEbD;{Tq#2aG?@d>L3N9boL!gZ3j#2n-gF?^3592Lq3V&W9y8VbQ z`?*gBX6TYt!2s1D#iRf)tN0-`z&XW0m!~e@ld8U14WLcn3caeg3OZ`n$9VRtllv8~ z7h1I%yiJX9U4eB6R9|hX?*esl;cD!PY(=qM_46-ac@k!|)X%DZR;qr^Mae*!?t&`# zgKDrWQvtTC_zS85yvgmXivK~y>ud+M8kUAoLfHFZEQ&<$M>oT=9h^yjhR{OM!_gzq zd1kDowPssI|pN@e~89E~G9V<0N!`3^)m-rW=6HDGz+H zKE`9jKnsJR+&DE(M@xl6a^n;@MNWATIu=Au2}GwBU4FQjR~LhaxUl$TL!T|v_R zv<*^TBCT}?NyF(~V+<7=BVODX>X8cGen6*_Y=`mLj3(KbuVK4DmxN~9&pfY6;GE3w zWS&%z*+{l#DQh9!W!mz zi2{$v{L{?yo(ojS{9@*Lrw2-8{!!+6F9vdDejf8&)}YNACP%CTkr{HJ5tU zL*#BUcw`@~I)~Sv>srzl4(JI5atjV`AlD^yPFmFF-ef#89l?@$A)=*Qc)Y7PtjdYr%6E3TH}u1<%TuaV1FmExq@W$<%6J%*Mn zt3)JWn1Hb(ugB>#6e~iTN0Ej=YRqJ5<}IhsXq8cWEJ(Yg_kLx9*b>g-_RD%l{pD_i zaE4th@!4;pbO`bpSJ2d2p~pwkB`~hM^G;vVMFqB;1$DIFMqMr=)ucAC?O*8Yzv$Kt zg&^!B6n-}_IQk8UsdbJ4ehRj-Ro-V#UqLg~M#Xzpuvw4Z+XWxS8fGr(>o0LGVVyq1 zYyj>iiyOq$8V>Ub7|GSL%aE}Uq_C`VU`Clnt!ZW-tkR_ZQ!sqM5t`V zP{5+UBtym~5G~h&XPLRGFRs5T&-J>`xD*JARV6Dg!`84rgkjzfh(ANd3Z{Ux-_?7s z^3oaX)9AhX?wgVU5N2^8K)D+&7`rmtvE~C5)DQydK$#t=GbjHY9@wB|cZHq9_W6u* zqHV%ys*IjEru&v8d3*4X@{!;^;qrs%0&kc&R&BStX+@X2sj|)g7gnpi0KJ1a{7x9k z%jx~-?ZR8M!ZKa()1NI1!}?9t>83WG@IOyEgJxJhg1`FO3+Ld?)Nm399Cd4F%*8G5HztM1#o`_izRyi43M{fJ?P*=<-F?BLoVwZ{O-_vukkB1jeQrvdj zq})M+$Q(B@T94xmzTcC5|4z=Qm6pWq5VnyyzJA~<6FK=mh2nJaTW`?z_(f53abO~S z!PIbDPG#UkicVN2ymFu+VXGi)qLif7;p9{TC0s`!3%!*z%~FYj8G*hF3e?|83CX|5 zB#tK654=_?NAll6q-B3cq(M||Ew}8%c@MK2L1qt^(sAqWg)&;4Qa{k)kj=W-?9YFd z%}lA~q9h)uNPKJ19hJ)&_YEp<|0OsSatc11-mH<&O^XK@=J_GJ83L_d z!IMFP_+Y{OAVK6el$5qQwiDK-2L668Z@Z>mX(0`=o z435BpdF}b&u^h{RdhOXPG_B(;=(Q)0qkm6#P)&MT;(@WaX=qA2!SpI^8w;hq!j%Ja zGaeL#X4;*(%FyRp*m_SX7QE&iINIa%H$?VsVVCL6;g1Q+C~-u3 z245daeEDLNYnQi8Xmsrg90$_mI_>rM$F^ayskPhxEiD<*Db!GYPC7mx&Y9+^VabtD z?=6&mshmrL0=Wh6t#hV^xqUFvdkdv@G3K=o8U<=R6>w~3&Uu4dMCli^ z>+lWk5R9vMJXt`lOMY(t@n>?bo|&?}p#Vfq*2yNE><~ueWb+u}(Y+`Ick+x9>IeFNUc8?8=GjS{IvWU_F(u4K<10UVdDG) z1l)Xu!-}DFXriNiaV3;3l$c$phch3_BTORGs%YERx zT*U#@LlpH$h>!Ax)$jdOuGclFoN&pPL2vE4ex^;V*W_B~Z4=##I@L;)Y{qniMY5|p2yt51iJGfAZ(Ha;xccW@dSPTj=46=Q=2d_FIT&G$#)6j@ zD^C_w2;OgvymYyAeq=5-xPH{gIKD{to_WkDXP)O1nm%e)SQKW6Yh`>S?HP4SoIQfp zF6AEnBuNayIt3H(9!}=uBaf*q%*) zEwqVSvnhIXl{hw=mXA&qW3uUAL2hKx+oNZt?a1OH6gBpkT8pvaIc|A}=}3NP-d&sk zymi-RQGQXXxFCyW7Y$D+f_{^$Lp~Nd0&9N4p)^C@AS1JAd(rEnFOw#WsSrnJ(v~q+ zF(#A#IA)LdPw&&?V_y?H(#be3e#EA94!KNh>_)9t;UZ{i&Byb=p=)`{`XYzW?eyu3 z5PV@eRgN1X7N^siaSw?XhtkDyY2v=2bZ6X9v2iHbiXRniL#eTNsCdUl`-;=Vi#ECl z(r%+W#WCU*8x68oiVhnswI_&aHrimHE}l=LkL~f|p)~rzK3)IIG@SI!_UI5pc^WOe zKRMqHAh3n^k==zMHvM`qxJ(s-b2pXCD}xF}<{d|cA|XgjqXYL>h$n}TVSKK*bqI|f z-yF%m`Mq{=i0ncBYN#q%r(bqflBm06oESNnhCAX#!(f`^m@e)}rLB%+aa}6C?UKaC~G z50&rV^7?61&VP;iYb>V%RSWN#vP=lkBddU zA@X6m1@i5EB|?hUCN=CfGhaQ)*YS0~^>p;`6Ks!LMfSv|D_%#ecov2eZ67RT< zG3Y`38d?r|;lQQI>Eiw=q2fzZwm7sGb=r$L?L{2FUgB1>K%pqC-0IY4j!!La88oTf zDs~N^#pP8GG^-CDUktd7)GPGnUFjD*>g0DyXez90Q5996x}Vgj8sCrNrdd;?Rdo$b z{28A~bEjE_SXw=8d}KBMNI*m3<%lhG60*Y-n6^^LpoP<8;*aw$0JINOdR3+08|mrk zkL|C>)eGk+Z)Q%UHW`hMq^D-)glSXgq&H@cj?^Zg(GI!}ODzeF7E@kjPFRbYS_?g1 zIXdjH${nURDo2NRsT}I~b!A~>hI-&>w2ty-o|=^tr7f67Tk>iDtPzoq zlqu8H=y-Z+u9eKQ&EYMoq@|3qW*3GB{fEio*@a=+elXJ;vqy(%uWw^10Pf!ZxMa>5 d9j@(+n&~gr52Cs`DUtUOCH9sB`{pbV{uhjEXj}jQ delta 7078 zcmaJ`4O~=Z)}MQsAwb3fVL%a>K|bV50R=>4gwYwCR0J)QEEAJj$uIn>tTn)a-T`u> zPHno|7L~hMKWi~ra<|oRwLr3R-+Z$VE6ubS#DZ26S#{q3xgUt`?|q*i_nznc&&P9~ z^PKzKXD-ccLNorhSGs3wq^43$kjx7pzPS8~WZrMd&2)uU<~tOs+KGVK&aBv(6+1Ht z!qQP%WwaZV)(iK>{9l6%us5^;>KEP#?S5=o*!oF#Tyohm9$)-+-iDAL+cW89A@Z3; zS~@A(gmo0-6E2*T?)`kH5+6TnUxDO8V^(}E0y|2h*EFZd_!lzKOjq!rnKEEf^u4sh z$26*ZvW#w3v`1*E+b6oZJW=LLI9+IWgR=9gT$z7}Q-OBIN5)IyW&Tr{Xx_#ktX~i+ z1JMdTLeZ}>+^qkO;=f$hAE%kGEZ0`Wpd(H;P~#k+2Cb>OHAzNSDDM4~Vf&O>J*I?N zq2MKo*M3F6Qw={@2C|gt2B_0bmGRSxpABGnT7Ah9ez&GYmTQ_6N97?ha9qJ(17!oV zY@j));IAtB&7)-C69s=)!P67=Zq=>!30}6QV*T36ilwX8{%UE}`pPvMsn_pw9Y=c` zedM2Fy$wA-#nvBm1TH-;o~Pm(J&ndF-8Gsp&@s3oa7E&Zrl|odttRwXqAV7AvZv9Y z%FH!m(dSjv;R?XTk4GRbp0MHR+7P{xLd{43M%uF|WC;hN2El`I3imhzvnPFO9G+8+wElZIusFA8iFsSBh@*EqIWEKeAL- zq0;IW?XRiC@e-FO#QL;ukQ_l~L_!k$~9@ zaLIU@C4L6;9D}Du;&Ykje0!=SeiHLMGf%n1Co|8r;wh2%am;i1c?u*xf_a{+Ctc!4 zF^{q=)_BYk5WoNzq9;h=MdrCgJsOE0ECJ8!@9Db^ApU3Oxj;Rqz&o~C`mx`8zNaH2 zZDU{K?i+v~Xf~MYprg^0IvUP8oV^8;n$x z;R0G0A4Z*qDb>Fqa7UBwClH&VU1N2+)9oue0sx(qA%|dfdeZGe*X_$Y9NYBMi=o&U zD%f1cL$Ya`tXCiovu#mqeQww)Mo-B`)r!%0?J%pAik0p^tnQ|rLGjh&Am?C5fEwEU z4DH5X^fJ0#Mt@KUenxPHc86eS&$^7R@Nt1F>qiOG{{V9Eiq?7BU}(2|$;=Ph+8_Gh z(Eo}{e*^&R-#=TNXZ7ElYhM)$d?w(iNLa|CEGUTp$O%TIUZ2 zh>ef3_~3V1YwdSDgw6j%fy;6~KnyYu1Ue;J+@j`#v1fd0b4AUPVPih1_23}#@*P5r zN(X!JjJEbnpC$nU|1XjFC}42p3u0(5)4@+x09$2zV{>I`=t6Kr_1Sqa8_+sW!H52H zW=?BsPfOG7a_Kq&IGT+6Kn(2xFmFds%GR3_r2iAhP_}k3Gdx=^05IPy={_o8eBCDW z_TIV@lI^CN^WDNh{kid+19-BApE_7IsmVahd-^b2OT{4V`XyH!d&^!e8x{=1e47&GIN%&;(>D#G3yh{Ax5?v0j z4A||E-PT>A7GoIIjGh%5hkX*h|0(%?QHm#lz8bw#SVA>pYDbQk#li3Q!{*}t_FrU( zSUzeqc3y-p80rV5P#!O&x`--a#NJC0zY~NaYL46-;A4{q`l=5D87VPpo^ca)I}G%% zVFNuplbWJl72cw>=-QF@%#cQMV>@%F|Adjk=y-IIu^TTAm|YxZcGODQrdI_Y`qET8 za!-L|c8bmFFGyz9<|5JLv-e~3Awif!&y3q#E#SDz>HMMxnYWy?NX}N`u5PJSG4Qg@ z*am_vcmdR!{<1>aP>ufsZDinc-e&8M@-T;nix1ooyZ<&^@a7GHk9$uKt&ZJ1x&!8h zdOjdIn(CQxH1sYxM)%PQ)wWfRjAwh`uIBpA)T%zJ~G+ao9<}XGSIN;qNAbI z?Qm{!qclx0QZsrkLdxh8oDh-Gt}|XQH6}TI@pejIa)^YuunhD6?;uQe@CpbV415O% z$;tPz12Y^nCy$RFK3pY^kXXPVS$hs^znk0~@-R9EQw`#hU&^(;tyGpWA^f$|H$SPo zo#1pqFQhD}uFphY&CerXkU2iwVO=_!HXX&5whEwo7F>89zX`vS@icaA$&;Ma-vzmv zkq>aPMTjQ&!i096;@7q6F&XL&^&4^4a3`AJ;D%%j`;5E^8p+U@)3hn|0bvE5OdX%N z0)_>yOtHzn+u0#B*mrwA0McYX>U7_R+GVk!z0WOD%7iYVoGwlnk9*|AdDZ1CIpF8K zf|Xw_&81$39D?)8F@qF8N>#x`=M}87o%NiS&oV#_^-@9d;m`fsZ=`~J4>-2g7LZ0i zbpDKvi#xwz#37*f0z=%ZRy@lAoVYcB|2EVgk_TG=i<<^ZmIs>#T#2vIA!2Eg*>ymp z!w3Cn?#~twYs#(W=f9R>tqzs!b(hkWV6|+*!Jc763br3TDOf31X_Tz}zzhejxc|a# znx5nIxMqlrGcan_%aUxsy<@lxf}5s#0FNagCI6gk6xkcnvswy!FuC%?W5HqKQ8E`L zb9kZP6)=Gn(ev=hw^J7lme;{^ujFPVvxa*9sfq+#OanF4%ZALzhJ42E)SXSE)#>T; z_X1`IP(LKA2ZNKU*G(s-eC-C_X_pSU&MkGmhHaeJCVQQ;Lv$?fQZiA{n27_Xz9x-+ zOdnhL;4oKGnM{&h-66TEfjwR(HKOXO#@XTbAFjryQE|rDqyU)UU|8G#UogTN4Ng=R zs~;U4xdi9WdS1GTL>cKQ@WUCC#*}e^t2-_;@{aq|S7ey9(0>Jfh~m^+HHy|u>K4N% zQ10YEibbh(dUAwlO{Hs-i^WqZG%qt+>`0+CnTy4W6za~56bnp=bqRi|V@kA0W0%=R4N3$2kRV49Ta~cK=?RhA89=GVQ;XtNe#&zrf zT)H!o=pyt@NfbV1!q|aCUZKO%ws6?<=v8c53#0=1Igyr5`J?DaB;TA8@$z^o%Q1;3 z#?$7Ux5Q1yDQW5}VqF4#G&N#k5ss!fT!{^R$W=}}GnsgJdFU-XWo?dC=(D-BIT$=9 zfsDDa;?;P{&AnTEKAxV>jT6_!)BfB9@%DH+n|q&lHjZwemLTqrqjl5b#OLGad63#T z+CME^EQ_Phrj?3998Jg@D}EnKv-65YilyJ@MTif_(mQ#@+U!`o+Dh_5eRTR*im^mz zUK@v^-_CVp(Lsiye*z57dcQ#6XeyFc1{n&@_y8FShT!Bl+F&UW8^+Q5mUMCPIJ#_U zPW^-A;U6)QhbF1Q>|N5{_=ch0JjC;}`UZ`io+$iCyQhr7{pHDFv~hX}?U?QyIrtHN z2ToLf2a-8|nrJoClKcoU%S@Z|i^bz6>ducA+f3Axzt~)cR~YJ~4BLaf0|j){a3C_s zmh_b?l1n7lL=^>##c!giqrfD76iufKV#Qt2&?-TLjxYKR)>8 zaS;qg(N60^@s%jLYK<1RMp5L9MFmONMlc$e4Mrlt%5uhX+-|a3Ivrmek`4^=mAB*JW&or1+WHxqFUyz0EUL-EUvBeEsIC zjg@QHXf`b0V9w3WHCL{w+*rA6)dGCMTD$s=&1;s=xqtJJu;PA-@eix+eXj0&lk5EJ zZRXzRclYdT1(UDo{X<*No>ub(XN@Fy&UL>Z?`?|bd zKB}oL6dk;IHLbvT`&1j_b8+ng&L1_@#&`v;7U2BxLT!xy8rOE<{C!Pr{6XhgT&(}8 zhCi)YM+QA1&eZ#g9|ztB53JCJtNaKpwnd8t-Sns}p}OotulEz6H?+Hlv?CFx-%+pk z_)YRphU9sWcR`LSx?z8pB-X?Mx<`>q-(A&cd}akf!y4!t#8xAuu$#GF&~3`qHD`kOtvx)tY`gKVYx68}CF%bj>Tl;gP8a+Cb`lAL4N2>B_< zzqm=xb5TRlNHMeF?v#KsrPvJzd{0c?Pny3pp?Dd+dXjV#f?;+$DFP6afz23RlUL!#( zKvO|~4Vnk~Ea+U&-Jq*L4>OM=+V@O5ypQk%P_s(~iMXUPRRQ*hA@S0P$LODs^-}-5heh*}r)$HgrMP_D2P0*z&lGx2 zp}#29*RXf6I9n^YDdWzxV0Bh1Eu?jKrunOL>7&>0oD!_gWQbBfEY)aKI-N2~)BKMq zF&?AJ(kcGE3fD`omre-?Qg$RHw5K#XxJ+SHx}7o>rUm!$Z#y)VnrYp_v{CBHsnncJ zZ!eq}oX+QYG?nV8|E_TITQoW#r%;yU6jJh{?0{ka#d>g2w!c~!e)RgHDgNqL^&s+q hyYX+Zq_QaiYKfE=bAD^e%)vJhd4!g|d&-sy{|j Date: Mon, 31 May 2021 21:35:03 +0200 Subject: [PATCH 10/91] RS refactor & test fix --- .../interfaces/ConstraintsCheckerTest.kt | 7 +- .../maintenance/MaintenancePluginTest.kt | 6 +- .../androidaps/queue/CommandQueueTest.kt | 10 +- .../androidaps/queue/QueueThreadTest.kt | 7 +- .../maintenance/PrefFileListProvider.kt | 10 +- .../androidaps/utils/ui/WeekdayPicker.kt | 2 +- .../danars/comm/DanaRSMessageHashTable.kt | 132 ++++++++---------- .../{DanaRS_Packet.kt => DanaRSPacket.kt} | 4 +- ... DanaRSPacketAPSBasalSetTemporaryBasal.kt} | 9 +- ...nts.kt => DanaRSPacketAPSHistoryEvents.kt} | 8 +- ...y.kt => DanaRSPacketAPSSetEventHistory.kt} | 8 +- ...te.kt => DanaRSPacketBasalGetBasalRate.kt} | 8 +- ...t => DanaRSPacketBasalGetProfileNumber.kt} | 9 +- ...naRSPacketBasalSetCancelTemporaryBasal.kt} | 10 +- ...> DanaRSPacketBasalSetProfileBasalRate.kt} | 9 +- ...t => DanaRSPacketBasalSetProfileNumber.kt} | 11 +- ...f.kt => DanaRSPacketBasalSetSuspendOff.kt} | 9 +- ...On.kt => DanaRSPacketBasalSetSuspendOn.kt} | 9 +- ... => DanaRSPacketBasalSetTemporaryBasal.kt} | 9 +- ...kt => DanaRSPacketBolusGet24CIRCFArray.kt} | 16 +-- ....kt => DanaRSPacketBolusGetBolusOption.kt} | 8 +- ...y.kt => DanaRSPacketBolusGetCIRCFArray.kt} | 8 +- ...RSPacketBolusGetCalculationInformation.kt} | 10 +- ...naRSPacketBolusGetStepBolusInformation.kt} | 8 +- ...kt => DanaRSPacketBolusSet24CIRCFArray.kt} | 9 +- ....kt => DanaRSPacketBolusSetBolusOption.kt} | 9 +- ...t => DanaRSPacketBolusSetExtendedBolus.kt} | 11 +- ...anaRSPacketBolusSetExtendedBolusCancel.kt} | 9 +- ... => DanaRSPacketBolusSetStepBolusStart.kt} | 8 +- ...t => DanaRSPacketBolusSetStepBolusStop.kt} | 9 +- ...on.kt => DanaRSPacketEtcKeepConnection.kt} | 9 +- ...ve.kt => DanaRSPacketEtcSetHistorySave.kt} | 9 +- ....kt => DanaRSPacketGeneralGetPumpCheck.kt} | 10 +- ...aRSPacketGeneralGetShippingInformation.kt} | 8 +- ... DanaRSPacketGeneralGetShippingVersion.kt} | 8 +- ...naRSPacketGeneralGetUserTimeChangeFlag.kt} | 8 +- ...SPacketGeneralInitialScreenInformation.kt} | 10 +- ...anaRSPacketGeneralSetHistoryUploadMode.kt} | 9 +- ...acketGeneralSetUserTimeChangeFlagClear.kt} | 9 +- ...ket_History_.kt => DanaRSPacketHistory.kt} | 4 +- ...y_Alarm.kt => DanaRSPacketHistoryAlarm.kt} | 8 +- ...ry.kt => DanaRSPacketHistoryAllHistory.kt} | 8 +- ...y_Basal.kt => DanaRSPacketHistoryBasal.kt} | 8 +- ....kt => DanaRSPacketHistoryBloodGlucose.kt} | 8 +- ...y_Bolus.kt => DanaRSPacketHistoryBolus.kt} | 8 +- ....kt => DanaRSPacketHistoryCarbohydrate.kt} | 8 +- ...y_Daily.kt => DanaRSPacketHistoryDaily.kt} | 8 +- ...y_Prime.kt => DanaRSPacketHistoryPrime.kt} | 8 +- ...Refill.kt => DanaRSPacketHistoryRefill.kt} | 8 +- ...spend.kt => DanaRSPacketHistorySuspend.kt} | 8 +- ...ary.kt => DanaRSPacketHistoryTemporary.kt} | 8 +- ...fy_Alarm.kt => DanaRSPacketNotifyAlarm.kt} | 8 +- ... => DanaRSPacketNotifyDeliveryComplete.kt} | 8 +- ... DanaRSPacketNotifyDeliveryRateDisplay.kt} | 8 +- ... => DanaRSPacketNotifyMissedBolusAlarm.kt} | 8 +- ...me.kt => DanaRSPacketOptionGetPumpTime.kt} | 8 +- ...anaRSPacketOptionGetPumpUTCAndTimeZone.kt} | 8 +- ....kt => DanaRSPacketOptionGetUserOption.kt} | 8 +- ...me.kt => DanaRSPacketOptionSetPumpTime.kt} | 9 +- ...anaRSPacketOptionSetPumpUTCAndTimeZone.kt} | 9 +- ....kt => DanaRSPacketOptionSetUserOption.kt} | 9 +- ...s_Avg.kt => DanaRSPacketReviewBolusAvg.kt} | 8 +- ...t => DanaRSPacketReviewGetPumpDecRatio.kt} | 8 +- ...aRS_Packet_Basal_Get_Profile_Basal_Rate.kt | 47 ------- ..._Packet_Basal_Get_Temporary_Basal_State.kt | 55 -------- .../DanaRS_Packet_Basal_Set_Basal_Rate.kt | 45 ------ ...et_Carbohydrate_Calculation_Information.kt | 39 ------ .../DanaRS_Packet_Bolus_Get_Dual_Bolus.kt | 37 ----- .../DanaRS_Packet_Bolus_Get_Extended_Bolus.kt | 43 ------ ...S_Packet_Bolus_Get_Extended_Bolus_State.kt | 54 ------- ...et_Bolus_Get_Extended_Menu_Option_State.kt | 35 ----- .../DanaRS_Packet_Bolus_Get_Initial_Bolus.kt | 43 ------ .../DanaRS_Packet_Bolus_Set_CIR_CF_Array.kt | 77 ---------- .../DanaRS_Packet_Bolus_Set_Dual_Bolus.kt | 45 ------ .../DanaRS_Packet_Bolus_Set_Initial_Bolus.kt | 47 ------- .../DanaRS_Packet_General_Delivery_Status.kt | 30 ---- ...aRS_Packet_General_Get_More_Information.kt | 49 ------- .../DanaRS_Packet_General_Get_Password.kt | 36 ----- ...Packet_General_Get_Today_Delivery_Total.kt | 42 ------ .../androidaps/danars/di/DanaRSCommModule.kt | 128 ++++++++--------- .../androidaps/danars/services/BLEComm.kt | 68 +++++---- .../danars/services/DanaRSService.kt | 104 +++++++------- .../androidaps/danars/DanaRSTestBase.kt | 8 +- .../DanaRSPacketBasalSetTemporaryBasalTest.kt | 6 +- .../comm/DanaRSPacketHistoryAlarmTest.kt | 6 +- .../DanaRSPacketNotifyDeliveryCompleteTest.kt | 6 +- .../DanaRSPacketOptionSetUserOptionTest.kt | 6 +- .../danars/comm/DanaRsMessageHashTableTest.kt | 12 +- ...naRsPacketApsBasalSetTemporaryBasalTest.kt | 28 ++-- .../comm/DanaRsPacketApsHistoryEventsTest.kt | 8 +- .../DanaRsPacketApsSetEventHistoryTest.kt | 20 +-- .../comm/DanaRsPacketBasalGetBasalRateTest.kt | 4 +- ...anaRsPacketBasalGetProfileBasalRateTest.kt | 45 ------ .../DanaRsPacketBasalGetProfileNumberTest.kt | 4 +- ...RsPacketBasalGetTemporaryBasalStateTest.kt | 42 ------ .../comm/DanaRsPacketBasalSetBasalRateTest.kt | 36 ----- ...sPacketBasalSetCancelTemporaryBasalTest.kt | 4 +- ...anaRsPacketBasalSetProfileBasalRateTest.kt | 6 +- .../DanaRsPacketBasalSetProfileNumberTest.kt | 6 +- .../DanaRsPacketBasalSetSuspendOffTest.kt | 4 +- .../comm/DanaRsPacketBasalSetSuspendOnTest.kt | 4 +- .../DanaRsPacketBolusGetBolusOptionTest.kt | 7 +- ...acketBolusGetCalculationInformationTest.kt | 6 +- ...tCarbohydrateCalculationInformationTest.kt | 33 ----- .../DanaRsPacketBolusGetCirCfArrayTest.kt | 6 +- .../comm/DanaRsPacketBolusGetDualBolusTest.kt | 40 ------ ...aRsPacketBolusGetExtendedBolusStateTest.kt | 38 ----- .../DanaRsPacketBolusGetExtendedBolusTest.kt | 38 ----- ...cketBolusGetExtendedMenuOptionStateTest.kt | 35 ----- .../DanaRsPacketBolusGetInitialBolusTest.kt | 33 ----- ...sPacketBolusGetStepBolusInformationTest.kt | 6 +- .../DanaRsPacketBolusSetBolusOptionTest.kt | 6 +- .../DanaRsPacketBolusSetCirCfArrayTest.kt | 38 ----- .../comm/DanaRsPacketBolusSetDualBolusTest.kt | 38 ----- ...RsPacketBolusSetExtendedBolusCancelTest.kt | 6 +- .../DanaRsPacketBolusSetExtendedBolusTest.kt | 6 +- .../DanaRsPacketBolusSetInitialBolusTest.kt | 35 ----- .../DanaRsPacketBolusSetStepBolusStartTest.kt | 6 +- .../DanaRsPacketBolusSetStepBolusStopTest.kt | 4 +- .../comm/DanaRsPacketEtcKeepConnectionTest.kt | 6 +- .../comm/DanaRsPacketEtcSetHistorySaveTest.kt | 6 +- .../DanaRsPacketGeneralDeliveryStatusTest.kt | 32 ----- ...naRsPacketGeneralGetMoreInformationTest.kt | 55 -------- .../DanaRsPacketGeneralGetPasswordTest.kt | 35 ----- .../DanaRsPacketGeneralGetPumpCheckTest.kt | 8 +- ...PacketGeneralGetShippingInformationTest.kt | 10 +- ...naRsPacketGeneralGetShippingVerisonTest.kt | 4 +- ...sPacketGeneralGetTodayDeliveryTotalTest.kt | 37 ----- ...sPacketGeneralGetUserTimeChangeFlagTest.kt | 8 +- ...cketGeneralInitialScreenInformationTest.kt | 8 +- ...RsPacketGeneralSetHistoryUploadModeTest.kt | 6 +- ...etGeneralSetUserTimeChangeFlagClearTest.kt | 6 +- .../comm/DanaRsPacketHistoryAllHistoryTest.kt | 6 +- .../comm/DanaRsPacketHistoryBasalTest.kt | 6 +- .../DanaRsPacketHistoryBloodGlucoseTest.kt | 6 +- .../comm/DanaRsPacketHistoryBolusTest.kt | 6 +- .../DanaRsPacketHistoryCarbohydrateTest.kt | 6 +- .../comm/DanaRsPacketHistoryDailyTest.kt | 6 +- .../comm/DanaRsPacketHistoryPrimeTest.kt | 6 +- .../comm/DanaRsPacketHistoryRefillTest.kt | 6 +- .../comm/DanaRsPacketHistorySuspendTest.kt | 6 +- .../comm/DanaRsPacketHistoryTemporaryTest.kt | 6 +- .../comm/DanaRsPacketNotifyAlarmTest.kt | 6 +- ...naRsPacketNotifyDeliveryRateDisplayTest.kt | 8 +- .../DanaRsPacketNotifyMissedBolusAlarmTest.kt | 6 +- .../comm/DanaRsPacketOptionGetPumpTimeTest.kt | 6 +- .../DanaRsPacketOptionGetUserOptionTest.kt | 6 +- .../comm/DanaRsPacketOptionSetPumpTimeTest.kt | 6 +- .../comm/DanaRsPacketReviewBolusAvgTest.kt | 6 +- .../DanaRsPacketReviewGetPumpDecRatioTest.kt | 4 +- 150 files changed, 593 insertions(+), 2049 deletions(-) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet.kt => DanaRSPacket.kt} (97%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_APS_Basal_Set_Temporary_Basal.kt => DanaRSPacketAPSBasalSetTemporaryBasal.kt} (91%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_APS_History_Events.kt => DanaRSPacketAPSHistoryEvents.kt} (99%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_APS_Set_Event_History.kt => DanaRSPacketAPSSetEventHistory.kt} (92%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Get_Basal_Rate.kt => DanaRSPacketBasalGetBasalRate.kt} (93%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Get_Profile_Number.kt => DanaRSPacketBasalGetProfileNumber.kt} (81%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.kt => DanaRSPacketBasalSetCancelTemporaryBasal.kt} (79%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Set_Profile_Basal_Rate.kt => DanaRSPacketBasalSetProfileBasalRate.kt} (87%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Set_Profile_Number.kt => DanaRSPacketBasalSetProfileNumber.kt} (83%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Set_Suspend_Off.kt => DanaRSPacketBasalSetSuspendOff.kt} (80%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Set_Suspend_On.kt => DanaRSPacketBasalSetSuspendOn.kt} (80%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Basal_Set_Temporary_Basal.kt => DanaRSPacketBasalSetTemporaryBasal.kt} (85%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Get_24_CIR_CF_Array.kt => DanaRSPacketBolusGet24CIRCFArray.kt} (76%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Get_Bolus_Option.kt => DanaRSPacketBolusGetBolusOption.kt} (97%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Get_CIR_CF_Array.kt => DanaRSPacketBolusGetCIRCFArray.kt} (96%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Get_Calculation_Information.kt => DanaRSPacketBolusGetCalculationInformation.kt} (91%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt => DanaRSPacketBolusGetStepBolusInformation.kt} (91%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Set_24_CIR_CF_Array.kt => DanaRSPacketBolusSet24CIRCFArray.kt} (91%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Set_Bolus_Option.kt => DanaRSPacketBolusSetBolusOption.kt} (94%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Set_Extended_Bolus.kt => DanaRSPacketBolusSetExtendedBolus.kt} (82%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.kt => DanaRSPacketBolusSetExtendedBolusCancel.kt} (78%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Set_Step_Bolus_Start.kt => DanaRSPacketBolusSetStepBolusStart.kt} (90%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.kt => DanaRSPacketBolusSetStepBolusStop.kt} (90%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Etc_Keep_Connection.kt => DanaRSPacketEtcKeepConnection.kt} (80%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Etc_Set_History_Save.kt => DanaRSPacketEtcSetHistorySave.kt} (90%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Get_Pump_Check.kt => DanaRSPacketGeneralGetPumpCheck.kt} (92%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Get_Shipping_Information.kt => DanaRSPacketGeneralGetShippingInformation.kt} (86%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Get_Shipping_Version.kt => DanaRSPacketGeneralGetShippingVersion.kt} (81%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Get_User_Time_Change_Flag.kt => DanaRSPacketGeneralGetUserTimeChangeFlag.kt} (80%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Initial_Screen_Information.kt => DanaRSPacketGeneralInitialScreenInformation.kt} (92%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Set_History_Upload_Mode.kt => DanaRSPacketGeneralSetHistoryUploadMode.kt} (82%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt => DanaRSPacketGeneralSetUserTimeChangeFlagClear.kt} (77%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_.kt => DanaRSPacketHistory.kt} (99%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Alarm.kt => DanaRSPacketHistoryAlarm.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_All_History.kt => DanaRSPacketHistoryAllHistory.kt} (69%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Basal.kt => DanaRSPacketHistoryBasal.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Blood_Glucose.kt => DanaRSPacketHistoryBloodGlucose.kt} (66%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Bolus.kt => DanaRSPacketHistoryBolus.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Carbohydrate.kt => DanaRSPacketHistoryCarbohydrate.kt} (66%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Daily.kt => DanaRSPacketHistoryDaily.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Prime.kt => DanaRSPacketHistoryPrime.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Refill.kt => DanaRSPacketHistoryRefill.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Suspend.kt => DanaRSPacketHistorySuspend.kt} (67%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_History_Temporary.kt => DanaRSPacketHistoryTemporary.kt} (70%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Notify_Alarm.kt => DanaRSPacketNotifyAlarm.kt} (95%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Notify_Delivery_Complete.kt => DanaRSPacketNotifyDeliveryComplete.kt} (90%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Notify_Delivery_Rate_Display.kt => DanaRSPacketNotifyDeliveryRateDisplay.kt} (90%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Notify_Missed_Bolus_Alarm.kt => DanaRSPacketNotifyMissedBolusAlarm.kt} (89%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Option_Get_Pump_Time.kt => DanaRSPacketOptionGetPumpTime.kt} (89%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone.kt => DanaRSPacketOptionGetPumpUTCAndTimeZone.kt} (88%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Option_Get_User_Option.kt => DanaRSPacketOptionGetUserOption.kt} (95%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Option_Set_Pump_Time.kt => DanaRSPacketOptionSetPumpTime.kt} (88%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone.kt => DanaRSPacketOptionSetPumpUTCAndTimeZone.kt} (88%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Option_Set_User_Option.kt => DanaRSPacketOptionSetUserOption.kt} (94%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Review_Bolus_Avg.kt => DanaRSPacketReviewBolusAvg.kt} (91%) rename danars/src/main/java/info/nightscout/androidaps/danars/comm/{DanaRS_Packet_Review_Get_Pump_Dec_Ratio.kt => DanaRSPacketReviewGetPumpDecRatio.kt} (80%) delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Basal_Rate.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Delivery_Status.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_More_Information.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Password.kt delete mode 100644 danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileBasalRateTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetTemporaryBasalStateTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetBasalRateTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCarbohydrateCalculationInformationTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetDualBolusTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusStateTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedMenuOptionStateTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetInitialBolusTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetCirCfArrayTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetDualBolusTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetInitialBolusTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralDeliveryStatusTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetMoreInformationTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPasswordTest.kt delete mode 100644 danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetTodayDeliveryTotalTest.kt diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt index c560e0a38b..545364ac3f 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -20,6 +20,7 @@ import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugi import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils +import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage @@ -51,7 +52,7 @@ import java.util.* ConstraintChecker::class, SP::class, Context::class, OpenAPSAMAPlugin::class, OpenAPSSMBPlugin::class, VirtualPumpPlugin::class, DetailedBolusInfoStorage::class, TemporaryBasalStorage::class, GlimpPlugin::class, Profiler::class, - UserEntryLogger::class, LoggerUtils::class, AppRepository::class, InsightDatabaseDao::class) + UserEntryLogger::class, PrefFileListProvider::class, AppRepository::class, InsightDatabaseDao::class) class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var activePlugin: ActivePlugin @@ -64,7 +65,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Mock lateinit var sensitivityOref1Plugin: SensitivityOref1Plugin @Mock lateinit var profiler: Profiler @Mock lateinit var uel: UserEntryLogger - @Mock lateinit var loggerUtils: LoggerUtils + @Mock lateinit var fileListProvider: PrefFileListProvider @Mock lateinit var repository: AppRepository @Mock lateinit var pumpSync: PumpSync @Mock lateinit var insightDatabaseDao: InsightDatabaseDao @@ -145,7 +146,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { insightPlugin = LocalInsightPlugin(injector, aapsLogger, rxBus, resourceHelper, sp, commandQueue, profileFunction, context, ConfigImpl(), dateUtil, insightDbHelper, pumpSync) openAPSSMBPlugin = OpenAPSSMBPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, sp, dateUtil, repository, glucoseStatusProvider) openAPSAMAPlugin = OpenAPSAMAPlugin(injector, aapsLogger, rxBus, constraintChecker, resourceHelper, profileFunction, context, activePlugin, iobCobCalculator, hardLimits, profiler, fabricPrivacy, dateUtil, repository, glucoseStatusProvider) - safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(ConfigImpl(), loggerUtils), iobCobCalculator, ConfigImpl(), dateUtil) + safetyPlugin = SafetyPlugin(injector, aapsLogger, resourceHelper, sp, rxBus, constraintChecker, openAPSAMAPlugin, openAPSSMBPlugin, sensitivityOref1Plugin, activePlugin, hardLimits, BuildHelper(ConfigImpl(), fileListProvider), iobCobCalculator, ConfigImpl(), dateUtil) val constraintsPluginsList = ArrayList() constraintsPluginsList.add(safetyPlugin) constraintsPluginsList.add(objectivesPlugin) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt index d0d965961b..c05b26a7a4 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt @@ -19,7 +19,7 @@ import org.powermock.modules.junit4.PowerMockRunner import java.io.File @RunWith(PowerMockRunner::class) -@PrepareForTest(NSSettingsStatus::class, BuildHelper::class, LoggerUtils::class) +@PrepareForTest(NSSettingsStatus::class, BuildHelper::class, LoggerUtils::class, PrefFileListProvider::class) class MaintenancePluginTest : TestBase() { @Mock lateinit var injector: HasAndroidInjector @@ -29,14 +29,16 @@ class MaintenancePluginTest : TestBase() { @Mock lateinit var nsSettingsStatus: NSSettingsStatus @Mock lateinit var buildHelper: BuildHelper @Mock lateinit var loggerUtils: LoggerUtils + @Mock lateinit var fileListProvider: PrefFileListProvider lateinit var sut: MaintenancePlugin @Before fun mock() { - sut = MaintenancePlugin(injector, context, resourceHelper, sp, nsSettingsStatus, aapsLogger, buildHelper, ConfigImpl(), loggerUtils) + sut = MaintenancePlugin(injector, context, resourceHelper, sp, nsSettingsStatus, aapsLogger, buildHelper, ConfigImpl(), fileListProvider, loggerUtils) `when`(loggerUtils.suffix).thenReturn(".log.zip") `when`(loggerUtils.logDirectory).thenReturn("src/test/res/logger") + `when`(fileListProvider.ensureExportDirExists()).thenReturn(File("src/test/res/logger")) } @Test fun logFilesTest() { diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt index ba57bfa9d1..3d64fc8b3a 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.interfaces.PumpSync 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.general.maintenance.LoggerUtils +import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.utils.DateUtil @@ -44,16 +44,16 @@ import java.util.* @RunWith(PowerMockRunner::class) @PrepareForTest( ConstraintChecker::class, VirtualPumpPlugin::class, ToastUtils::class, Context::class, - FabricPrivacy::class, LoggerUtils::class, PowerManager::class, + FabricPrivacy::class, PrefFileListProvider::class, PowerManager::class, AppRepository::class) class CommandQueueTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var sp: SP - @Mock lateinit var loggerUtils: LoggerUtils @Mock lateinit var powerManager: PowerManager @Mock lateinit var repository: AppRepository + @Mock lateinit var fileListProvider: PrefFileListProvider class CommandQueueMocked( injector: HasAndroidInjector, @@ -106,7 +106,7 @@ class CommandQueueTest : TestBaseWithProfile() { @Before fun prepare() { - commandQueue = CommandQueueMocked(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelper(ConfigImpl(), loggerUtils), dateUtil, repository, fabricPrivacy) + commandQueue = CommandQueueMocked(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelper(ConfigImpl(), fileListProvider), dateUtil, repository, fabricPrivacy) testPumpPlugin = TestPumpPlugin(injector) testPumpPlugin.pumpDescription.basalMinimumRate = 0.1 @@ -137,7 +137,7 @@ class CommandQueueTest : TestBaseWithProfile() { @Test fun commandIsPickedUp() { - val commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelper(ConfigImpl(), loggerUtils), dateUtil, repository, fabricPrivacy) + val commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelper(ConfigImpl(), fileListProvider), dateUtil, repository, fabricPrivacy) // start with empty queue Assert.assertEquals(0, commandQueue.size()) diff --git a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt index 5dd203a40d..000d1e9015 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/QueueThreadTest.kt @@ -13,6 +13,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils +import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.queue.commands.CommandTempBasalAbsolute @@ -33,13 +34,13 @@ import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest( ConstraintChecker::class, VirtualPumpPlugin::class, ToastUtils::class, Context::class, - FabricPrivacy::class, LoggerUtils::class, PowerManager::class) + FabricPrivacy::class, PrefFileListProvider::class, PowerManager::class) class QueueThreadTest : TestBaseWithProfile() { @Mock lateinit var constraintChecker: ConstraintChecker @Mock lateinit var activePlugin: ActivePlugin @Mock lateinit var sp: SP - @Mock lateinit var loggerUtils: LoggerUtils + @Mock lateinit var fileListProvider: PrefFileListProvider @Mock lateinit var powerManager: PowerManager @Mock lateinit var repository: AppRepository @@ -62,7 +63,7 @@ class QueueThreadTest : TestBaseWithProfile() { @Before fun prepare() { pumpPlugin = TestPumpPlugin(injector) - commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelper(ConfigImpl(), loggerUtils), dateUtil, repository, fabricPrivacy) + commandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, BuildHelper(ConfigImpl(), fileListProvider), dateUtil, repository, fabricPrivacy) val pumpDescription = PumpDescription() pumpDescription.basalMinimumRate = 0.1 diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt index a89dc204e1..1aedd1dfcb 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt @@ -17,6 +17,7 @@ import javax.inject.Inject import javax.inject.Singleton import kotlin.math.abs +@Suppress("SpellCheckingInspection") @Singleton class PrefFileListProvider @Inject constructor( private val resourceHelper: ResourceHelper, @@ -27,12 +28,13 @@ class PrefFileListProvider @Inject constructor( private val versionCheckerUtils: VersionCheckerUtils ) { + private val path = File(Environment.getExternalStorageDirectory().toString()) + private val aapsPath = File(path, "AAPS" + File.separator + "preferences") + private val exportsPath = File(path, "AAPS" + File.separator + "exports") + private val extraPath = File(path, "AAPS" + File.separator + "extra") + companion object { - private val path = File(Environment.getExternalStorageDirectory().toString()) - private val aapsPath = File(path, "AAPS" + File.separator + "preferences") - private val exportsPath = File(path, "AAPS" + File.separator + "exports") - private val extraPath = File(path, "AAPS" + File.separator + "extra") private const val IMPORT_AGE_NOT_YET_OLD_DAYS = 60 } diff --git a/core/src/main/java/info/nightscout/androidaps/utils/ui/WeekdayPicker.kt b/core/src/main/java/info/nightscout/androidaps/utils/ui/WeekdayPicker.kt index e76dc1b2e1..b623b7514b 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/ui/WeekdayPicker.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/ui/WeekdayPicker.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.core.databinding.WeekdayPickerBinding import info.nightscout.androidaps.extensions.toVisibility import java.util.* -class WeekdayPicker @JvmOverloads constructor( +class WeekdayPicker constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : ConstraintLayout(context, attrs, defStyleAttr) { diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSMessageHashTable.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSMessageHashTable.kt index 7c7466d9e6..4c7eb50294 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSMessageHashTable.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSMessageHashTable.kt @@ -10,89 +10,73 @@ class DanaRSMessageHashTable @Inject constructor( val injector: HasAndroidInjector ) { - var messages: HashMap = HashMap() + var messages: HashMap = HashMap() - fun put(message: DanaRS_Packet) { + fun put(message: DanaRSPacket) { messages[message.command] = message } - fun findMessage(command: Int): DanaRS_Packet { - return messages[command] ?: DanaRS_Packet(injector) + fun findMessage(command: Int): DanaRSPacket { + return messages[command] ?: DanaRSPacket(injector) } init { - put(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) - put(DanaRS_Packet_Basal_Get_Basal_Rate(injector)) - put(DanaRS_Packet_Basal_Get_Profile_Basal_Rate(injector)) - put(DanaRS_Packet_Basal_Get_Profile_Number(injector)) - put(DanaRS_Packet_Basal_Set_Basal_Rate(injector, arrayOf())) - put(DanaRS_Packet_Basal_Set_Profile_Basal_Rate(injector, 0, arrayOf())) - put(DanaRS_Packet_Basal_Set_Profile_Number(injector)) - put(DanaRS_Packet_Basal_Set_Suspend_Off(injector)) - put(DanaRS_Packet_Basal_Set_Suspend_On(injector)) - put(DanaRS_Packet_Basal_Set_Temporary_Basal(injector)) - put(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector)) - put(DanaRS_Packet_Bolus_Get_Bolus_Option(injector)) - put(DanaRS_Packet_Bolus_Get_Initial_Bolus(injector)) - put(DanaRS_Packet_Bolus_Get_Calculation_Information(injector)) - put(DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(injector)) - put(DanaRS_Packet_Bolus_Get_CIR_CF_Array(injector)) - put(DanaRS_Packet_Bolus_Get_24_CIR_CF_Array(injector)) - put(DanaRS_Packet_Bolus_Get_Dual_Bolus(injector)) - put(DanaRS_Packet_Bolus_Get_Extended_Bolus(injector)) - put(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector)) - put(DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(injector)) - put(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) - put(DanaRS_Packet_Bolus_Set_Bolus_Option(injector)) - put(DanaRS_Packet_Bolus_Set_Initial_Bolus(injector)) - put(DanaRS_Packet_Bolus_Set_CIR_CF_Array(injector)) - put(DanaRS_Packet_Bolus_Set_24_CIR_CF_Array(injector, null)) - put(DanaRS_Packet_Bolus_Set_Dual_Bolus(injector)) - put(DanaRS_Packet_Bolus_Set_Extended_Bolus(injector)) - put(DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(injector)) - put(DanaRS_Packet_Bolus_Set_Step_Bolus_Start(injector)) - put(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(injector)) - put(DanaRS_Packet_Etc_Keep_Connection(injector)) - put(DanaRS_Packet_Etc_Set_History_Save(injector)) - put(DanaRS_Packet_General_Delivery_Status(injector)) - put(DanaRS_Packet_General_Get_Password(injector)) - put(DanaRS_Packet_General_Initial_Screen_Information(injector)) - put(DanaRS_Packet_Notify_Alarm(injector)) - put(DanaRS_Packet_Notify_Delivery_Complete(injector)) - put(DanaRS_Packet_Notify_Delivery_Rate_Display(injector)) - put(DanaRS_Packet_Notify_Missed_Bolus_Alarm(injector)) - put(DanaRS_Packet_Option_Get_Pump_Time(injector)) - put(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector)) - put(DanaRS_Packet_Option_Get_User_Option(injector)) - put(DanaRS_Packet_Option_Set_Pump_Time(injector)) - put(DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(injector)) - put(DanaRS_Packet_Option_Set_User_Option(injector)) + put(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) + put(DanaRSPacketBasalGetBasalRate(injector)) + put(DanaRSPacketBasalGetProfileNumber(injector)) + put(DanaRSPacketBasalSetProfileBasalRate(injector, 0, arrayOf())) + put(DanaRSPacketBasalSetProfileNumber(injector)) + put(DanaRSPacketBasalSetSuspendOff(injector)) + put(DanaRSPacketBasalSetSuspendOn(injector)) + put(DanaRSPacketBasalSetTemporaryBasal(injector)) + put(DanaRSPacketBolusGetBolusOption(injector)) + put(DanaRSPacketBolusGetCalculationInformation(injector)) + put(DanaRSPacketBolusGetCIRCFArray(injector)) + put(DanaRSPacketBolusGetStepBolusInformation(injector)) + put(DanaRSPacketBolusSetBolusOption(injector)) + put(DanaRSPacketBolusSet24CIRCFArray(injector, null)) + put(DanaRSPacketBolusGet24CIRCFArray(injector)) + put(DanaRSPacketBolusSetExtendedBolus(injector)) + put(DanaRSPacketBolusSetExtendedBolusCancel(injector)) + put(DanaRSPacketBolusSetStepBolusStart(injector)) + put(DanaRSPacketBolusSetStepBolusStop(injector)) + put(DanaRSPacketEtcKeepConnection(injector)) + put(DanaRSPacketEtcSetHistorySave(injector)) + put(DanaRSPacketGeneralInitialScreenInformation(injector)) + put(DanaRSPacketNotifyAlarm(injector)) + put(DanaRSPacketNotifyDeliveryComplete(injector)) + put(DanaRSPacketNotifyDeliveryRateDisplay(injector)) + put(DanaRSPacketNotifyMissedBolusAlarm(injector)) + put(DanaRSPacketOptionGetPumpTime(injector)) + put(DanaRSPacketOptionGetPumpUTCAndTimeZone(injector)) + put(DanaRSPacketOptionGetUserOption(injector)) + put(DanaRSPacketOptionSetPumpTime(injector)) + put(DanaRSPacketOptionSetPumpUTCAndTimeZone(injector)) + put(DanaRSPacketOptionSetUserOption(injector)) //put(new DanaRS_Packet_History_(injector)); - put(DanaRS_Packet_History_Alarm(injector)) - put(DanaRS_Packet_History_All_History(injector)) - put(DanaRS_Packet_History_Basal(injector)) - put(DanaRS_Packet_History_Blood_Glucose(injector)) - put(DanaRS_Packet_History_Bolus(injector)) - put(DanaRS_Packet_Review_Bolus_Avg(injector)) - put(DanaRS_Packet_History_Carbohydrate(injector)) - put(DanaRS_Packet_History_Daily(injector)) - put(DanaRS_Packet_General_Get_More_Information(injector)) - put(DanaRS_Packet_General_Get_Pump_Check(injector)) - put(DanaRS_Packet_General_Get_Shipping_Information(injector)) - put(DanaRS_Packet_General_Get_Today_Delivery_Total(injector)) - put(DanaRS_Packet_General_Get_User_Time_Change_Flag(injector)) - put(DanaRS_Packet_History_Prime(injector)) - put(DanaRS_Packet_History_Refill(injector)) - put(DanaRS_Packet_General_Set_History_Upload_Mode(injector)) - put(DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(injector)) - put(DanaRS_Packet_History_Suspend(injector)) - put(DanaRS_Packet_History_Temporary(injector)) + put(DanaRSPacketHistoryAlarm(injector)) + put(DanaRSPacketHistoryAllHistory(injector)) + put(DanaRSPacketHistoryBasal(injector)) + put(DanaRSPacketHistoryBloodGlucose(injector)) + put(DanaRSPacketHistoryBolus(injector)) + put(DanaRSPacketReviewBolusAvg(injector)) + put(DanaRSPacketHistoryCarbohydrate(injector)) + put(DanaRSPacketHistoryDaily(injector)) + put(DanaRSPacketHistoryPrime(injector)) + put(DanaRSPacketHistoryRefill(injector)) + put(DanaRSPacketHistorySuspend(injector)) + put(DanaRSPacketHistoryTemporary(injector)) + put(DanaRSPacketGeneralGetPumpCheck(injector)) + put(DanaRSPacketGeneralGetShippingInformation(injector)) + put(DanaRSPacketGeneralGetUserTimeChangeFlag(injector)) + put(DanaRSPacketGeneralSetHistoryUploadMode(injector)) + put(DanaRSPacketGeneralSetUserTimeChangeFlagClear(injector)) // APS - put(DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, 0)) - put(DanaRS_Packet_APS_History_Events(injector, 0)) - put(DanaRS_Packet_APS_Set_Event_History(injector, 0, 0, 0, 0)) + put(DanaRSPacketAPSBasalSetTemporaryBasal(injector, 0)) + put(DanaRSPacketAPSHistoryEvents(injector, 0)) + put(DanaRSPacketAPSSetEventHistory(injector, 0, 0, 0, 0)) // v3 - put(DanaRS_Packet_General_Get_Shipping_Version(injector)) - put(DanaRS_Packet_Review_Get_Pump_Dec_Ratio(injector)) + put(DanaRSPacketGeneralGetShippingVersion(injector)) + put(DanaRSPacketReviewGetPumpDecRatio(injector)) } } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacket.kt similarity index 97% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacket.kt index ba0e31ebb9..918bb78207 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacket.kt @@ -8,7 +8,7 @@ import org.joda.time.DateTime import java.nio.charset.StandardCharsets import javax.inject.Inject -open class DanaRS_Packet(protected var injector: HasAndroidInjector) { +open class DanaRSPacket(protected var injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var dateUtil: DateUtil @@ -43,7 +43,7 @@ open class DanaRS_Packet(protected var injector: HasAndroidInjector) { failed = true } - open fun getFriendlyName(): String = "UNKNOWN_PACKET" + open val friendlyName: String = "UNKNOWN_PACKET" protected fun getBytes(data: ByteArray, srcStart: Int, srcLength: Int): ByteArray { val ret = ByteArray(srcLength) diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSBasalSetTemporaryBasal.kt similarity index 91% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSBasalSetTemporaryBasal.kt index ab1649f380..bf490138a2 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSBasalSetTemporaryBasal.kt @@ -4,10 +4,10 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_APS_Basal_Set_Temporary_Basal( +class DanaRSPacketAPSBasalSetTemporaryBasal( injector: HasAndroidInjector, private var percent: Int -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { var temporaryBasalRatio = 0 var temporaryBasalDuration = 0 @@ -48,11 +48,10 @@ class DanaRS_Packet_APS_Basal_Set_Temporary_Basal( } } - override fun getFriendlyName(): String { - return "BASAL__APS_SET_TEMPORARY_BASAL" - } + override val friendlyName: String = "BASAL__APS_SET_TEMPORARY_BASAL" companion object { + const val PARAM30MIN = 160 const val PARAM15MIN = 150 } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt similarity index 99% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt index 12d20835fa..ddf8e3b606 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_History_Events.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt @@ -19,10 +19,10 @@ import org.joda.time.DateTime import org.joda.time.DateTimeZone import javax.inject.Inject -open class DanaRS_Packet_APS_History_Events( +open class DanaRSPacketAPSHistoryEvents( injector: HasAndroidInjector, private var from: Long -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -300,7 +300,5 @@ open class DanaRS_Packet_APS_History_Events( rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status)) } - override fun getFriendlyName(): String { - return "APS_HISTORY_EVENTS" - } + override val friendlyName: String = "APS_HISTORY_EVENTS" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Set_Event_History.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSSetEventHistory.kt similarity index 92% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Set_Event_History.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSSetEventHistory.kt index 802eb09b56..cfa51a9d5e 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_APS_Set_Event_History.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSSetEventHistory.kt @@ -8,13 +8,13 @@ import org.joda.time.DateTime import org.joda.time.DateTimeZone import javax.inject.Inject -class DanaRS_Packet_APS_Set_Event_History( +class DanaRSPacketAPSSetEventHistory( injector: HasAndroidInjector, private var packetType: Int, private var time: Long, private var param1: Int, private var param2: Int -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -54,7 +54,5 @@ class DanaRS_Packet_APS_Set_Event_History( } } - override fun getFriendlyName(): String { - return "APS_SET_EVENT_HISTORY" - } + override val friendlyName: String = "APS_SET_EVENT_HISTORY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Basal_Rate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt similarity index 93% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Basal_Rate.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt index 64a91766bd..ae9b5a95c9 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Basal_Rate.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt @@ -13,9 +13,9 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject -class DanaRS_Packet_Basal_Get_Basal_Rate( +class DanaRSPacketBasalGetBasalRate( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -55,7 +55,5 @@ class DanaRS_Packet_Basal_Get_Basal_Rate( } } - override fun getFriendlyName(): String { - return "BASAL__GET_BASAL_RATE" - } + override val friendlyName: String = "BASAL__GET_BASAL_RATE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetProfileNumber.kt similarity index 81% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetProfileNumber.kt index 399555e09d..5c0bed60a0 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetProfileNumber.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Basal_Get_Profile_Number( +class DanaRSPacketBasalGetProfileNumber( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -22,8 +22,5 @@ class DanaRS_Packet_Basal_Get_Profile_Number( aapsLogger.debug(LTag.PUMPCOMM, "Active profile: " + danaPump.activeProfile) } - override fun getFriendlyName(): String { - return "BASAL__GET_PROFILE_NUMBER" - } - + override val friendlyName: String = "BASAL__GET_PROFILE_NUMBER" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetCancelTemporaryBasal.kt similarity index 79% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetCancelTemporaryBasal.kt index e20f2ba80e..e36b027ecb 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetCancelTemporaryBasal.kt @@ -1,12 +1,12 @@ package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption +import info.nightscout.androidaps.logging.LTag -class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal( +class DanaRSPacketBasalSetCancelTemporaryBasal( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL @@ -24,7 +24,5 @@ class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal( } } - override fun getFriendlyName(): String { - return "BASAL__CANCEL_TEMPORARY_BASAL" - } + override val friendlyName: String = "BASAL__CANCEL_TEMPORARY_BASAL" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetProfileBasalRate.kt similarity index 87% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetProfileBasalRate.kt index 6d397ca86f..d047e76588 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetProfileBasalRate.kt @@ -4,11 +4,11 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Basal_Set_Profile_Basal_Rate( +class DanaRSPacketBasalSetProfileBasalRate( injector: HasAndroidInjector, private var profileNumber: Int, private var profileBasalRate: Array -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_BASAL_RATE @@ -31,6 +31,7 @@ class DanaRS_Packet_Basal_Set_Profile_Basal_Rate( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -40,7 +41,5 @@ class DanaRS_Packet_Basal_Set_Profile_Basal_Rate( } } - override fun getFriendlyName(): String { - return "BASAL__SET_PROFILE_BASAL_RATE" - } + override val friendlyName: String = "BASAL__SET_PROFILE_BASAL_RATE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Profile_Number.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetProfileNumber.kt similarity index 83% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Profile_Number.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetProfileNumber.kt index 2f88623296..f22b90aee9 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Profile_Number.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetProfileNumber.kt @@ -1,13 +1,13 @@ package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption +import info.nightscout.androidaps.logging.LTag -class DanaRS_Packet_Basal_Set_Profile_Number( +class DanaRSPacketBasalSetProfileNumber( injector: HasAndroidInjector, private var profileNumber: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_NUMBER @@ -22,6 +22,7 @@ class DanaRS_Packet_Basal_Set_Profile_Number( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -31,7 +32,5 @@ class DanaRS_Packet_Basal_Set_Profile_Number( } } - override fun getFriendlyName(): String { - return "BASAL__SET_PROFILE_NUMBER" - } + override val friendlyName: String = "BASAL__SET_PROFILE_NUMBER" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_Off.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetSuspendOff.kt similarity index 80% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_Off.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetSuspendOff.kt index cdd3b83f2c..644728e2ac 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_Off.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetSuspendOff.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Basal_Set_Suspend_Off( +class DanaRSPacketBasalSetSuspendOff( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF @@ -15,6 +15,7 @@ class DanaRS_Packet_Basal_Set_Suspend_Off( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -24,7 +25,5 @@ class DanaRS_Packet_Basal_Set_Suspend_Off( } } - override fun getFriendlyName(): String { - return "BASAL__SET_SUSPEND_OFF" - } + override val friendlyName: String = "BASAL__SET_SUSPEND_OFF" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_On.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetSuspendOn.kt similarity index 80% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_On.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetSuspendOn.kt index 6d0cb88052..a0d1b41f0d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Suspend_On.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetSuspendOn.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Basal_Set_Suspend_On( +class DanaRSPacketBasalSetSuspendOn( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_ON @@ -15,6 +15,7 @@ class DanaRS_Packet_Basal_Set_Suspend_On( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -24,7 +25,5 @@ class DanaRS_Packet_Basal_Set_Suspend_On( } } - override fun getFriendlyName(): String { - return "BASAL__SET_SUSPEND_ON" - } + override val friendlyName: String = "BASAL__SET_SUSPEND_ON" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasal.kt similarity index 85% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasal.kt index 3e5725694f..63399a195d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasal.kt @@ -4,11 +4,11 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -open class DanaRS_Packet_Basal_Set_Temporary_Basal( +open class DanaRSPacketBasalSetTemporaryBasal( injector: HasAndroidInjector, private var temporaryBasalRatio: Int = 0, private var temporaryBasalDuration: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_TEMPORARY_BASAL @@ -24,6 +24,7 @@ open class DanaRS_Packet_Basal_Set_Temporary_Basal( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -33,7 +34,5 @@ open class DanaRS_Packet_Basal_Set_Temporary_Basal( } } - override fun getFriendlyName(): String { - return "BASAL__SET_TEMPORARY_BASAL" - } + override val friendlyName: String = "BASAL__SET_TEMPORARY_BASAL" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_24_CIR_CF_Array.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGet24CIRCFArray.kt similarity index 76% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_24_CIR_CF_Array.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGet24CIRCFArray.kt index 1d9b752cf9..3f0e2488ba 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_24_CIR_CF_Array.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGet24CIRCFArray.kt @@ -1,14 +1,14 @@ package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption +import info.nightscout.androidaps.logging.LTag import javax.inject.Inject -class DanaRS_Packet_Bolus_Get_24_CIR_CF_Array( +class DanaRSPacketBolusGet24CIRCFArray( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -19,9 +19,9 @@ class DanaRS_Packet_Bolus_Get_24_CIR_CF_Array( override fun handleMessage(data: ByteArray) { danaPump.units = byteArrayToInt(getBytes(data, DATA_START, 1)) - for (i in 0 .. 23) { - val cir = byteArrayToInt(getBytes(data, DATA_START + 1 + 2 * i, 2)).toDouble() - val cf = if (danaPump.units == DanaPump.UNITS_MGDL) + for (i in 0..23) { + val cir = byteArrayToInt(getBytes(data, DATA_START + 1 + 2 * i, 2)).toDouble() + val cf = if (danaPump.units == DanaPump.UNITS_MGDL) byteArrayToInt(getBytes(data, DATA_START + 1 + 48 + 2 * i, 2)).toDouble() else byteArrayToInt(getBytes(data, DATA_START + 1 + 48 + 2 * i, 2)) / 100.0 @@ -33,7 +33,5 @@ class DanaRS_Packet_Bolus_Get_24_CIR_CF_Array( aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaPump.units == DanaPump.UNITS_MGDL) "MGDL" else "MMOL") } - override fun getFriendlyName(): String { - return "BOLUS__GET_24_ CIR_CF_ARRAY" - } + override val friendlyName = "BOLUS__GET_24_ CIR_CF_ARRAY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt similarity index 97% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt index 433f782730..9b87c11a19 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt @@ -12,9 +12,9 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject -class DanaRS_Packet_Bolus_Get_Bolus_Option( +class DanaRSPacketBolusGetBolusOption( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -110,7 +110,5 @@ class DanaRS_Packet_Bolus_Get_Bolus_Option( aapsLogger.debug(LTag.PUMPCOMM, "missedBolus04EndMin: $missedBolus04EndMin") } - override fun getFriendlyName(): String { - return "BOLUS__GET_BOLUS_OPTION" - } + override val friendlyName: String = "BOLUS__GET_BOLUS_OPTION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCIRCFArray.kt similarity index 96% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCIRCFArray.kt index d476115d63..59af61aa30 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCIRCFArray.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Bolus_Get_CIR_CF_Array( +class DanaRSPacketBolusGetCIRCFArray( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -112,7 +112,5 @@ class DanaRS_Packet_Bolus_Get_CIR_CF_Array( aapsLogger.debug(LTag.PUMPCOMM, "cf06: $cf06") } - override fun getFriendlyName(): String { - return "BOLUS__GET_CIR_CF_ARRAY" - } + override val friendlyName: String = "BOLUS__GET_CIR_CF_ARRAY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCalculationInformation.kt similarity index 91% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCalculationInformation.kt index fff895b239..58d6d95eb8 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetCalculationInformation.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Bolus_Get_Calculation_Information( +class DanaRSPacketBolusGetCalculationInformation( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -45,7 +45,7 @@ class DanaRS_Packet_Bolus_Get_Calculation_Information( if (danaPump.units == DanaPump.UNITS_MMOL) { danaPump.currentCF = danaPump.currentCF / 100.0 danaPump.currentTarget = danaPump.currentTarget / 100.0 - currentBG = currentBG / 100.0 + currentBG /= 100.0 } if (error != 0) failed = true aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") @@ -58,7 +58,5 @@ class DanaRS_Packet_Bolus_Get_Calculation_Information( aapsLogger.debug(LTag.PUMPCOMM, "Pump IOB: " + danaPump.iob) } - override fun getFriendlyName(): String { - return "BOLUS__GET_CALCULATION_INFORMATION" - } + override val friendlyName: String = "BOLUS__GET_CALCULATION_INFORMATION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetStepBolusInformation.kt similarity index 91% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetStepBolusInformation.kt index 7cc2d3aa65..992dc7bd40 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetStepBolusInformation.kt @@ -8,9 +8,9 @@ import org.joda.time.DateTime import org.joda.time.DateTimeZone import javax.inject.Inject -class DanaRS_Packet_Bolus_Get_Step_Bolus_Information( +class DanaRSPacketBolusGetStepBolusInformation( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -40,7 +40,5 @@ class DanaRS_Packet_Bolus_Get_Step_Bolus_Information( aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaPump.bolusStep + " U") } - override fun getFriendlyName(): String { - return "BOLUS__GET_STEP_BOLUS_INFORMATION" - } + override val friendlyName: String = "BOLUS__GET_STEP_BOLUS_INFORMATION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_24_CIR_CF_Array.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt similarity index 91% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_24_CIR_CF_Array.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt index a7a4d573cc..febd8479c7 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_24_CIR_CF_Array.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSet24CIRCFArray.kt @@ -9,10 +9,10 @@ import info.nightscout.androidaps.logging.LTag import javax.inject.Inject import kotlin.math.round -class DanaRS_Packet_Bolus_Set_24_CIR_CF_Array( +class DanaRSPacketBolusSet24CIRCFArray( injector: HasAndroidInjector, private val profile: Profile? -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -42,6 +42,7 @@ class DanaRS_Packet_Bolus_Set_24_CIR_CF_Array( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -51,7 +52,5 @@ class DanaRS_Packet_Bolus_Set_24_CIR_CF_Array( } } - override fun getFriendlyName(): String { - return "BOLUS__SET_24_CIR_CF_ARRAY" - } + override val friendlyName: String = "BOLUS__SET_24_CIR_CF_ARRAY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetBolusOption.kt similarity index 94% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetBolusOption.kt index ac40d4ef56..cee5a745de 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetBolusOption.kt @@ -4,7 +4,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Bolus_Set_Bolus_Option( +class DanaRSPacketBolusSetBolusOption( injector: HasAndroidInjector, private var extendedBolusOptionOnOff: Int = 0, private var bolusCalculationOption: Int = 0, @@ -26,7 +26,7 @@ class DanaRS_Packet_Bolus_Set_Bolus_Option( private var missedBolus04EndHour: Int = 0, private var missedBolus04EndMin: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_OPTION @@ -59,6 +59,7 @@ class DanaRS_Packet_Bolus_Set_Bolus_Option( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -68,7 +69,5 @@ class DanaRS_Packet_Bolus_Set_Bolus_Option( } } - override fun getFriendlyName(): String { - return "BOLUS__SET_BOLUS_OPTION" - } + override val friendlyName: String = "BOLUS__SET_BOLUS_OPTION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolus.kt similarity index 82% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolus.kt index 749b72206c..0afe2df2e0 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolus.kt @@ -4,15 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Bolus_Set_Extended_Bolus( +class DanaRSPacketBolusSetExtendedBolus( injector: HasAndroidInjector, private var extendedAmount: Double = 0.0, private var extendedBolusDurationInHalfHours: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus start : $extendedAmount U halfhours: $extendedBolusDurationInHalfHours") + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus start : $extendedAmount U half-hours: $extendedBolusDurationInHalfHours") } override fun getRequestParams(): ByteArray { @@ -26,6 +26,7 @@ class DanaRS_Packet_Bolus_Set_Extended_Bolus( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -35,7 +36,5 @@ class DanaRS_Packet_Bolus_Set_Extended_Bolus( } } - override fun getFriendlyName(): String { - return "BOLUS__SET_EXTENDED_BOLUS" - } + override val friendlyName: String = "BOLUS__SET_EXTENDED_BOLUS" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolusCancel.kt similarity index 78% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolusCancel.kt index 7bc1cea154..4f0afeb0a0 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetExtendedBolusCancel.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel( +class DanaRSPacketBolusSetExtendedBolusCancel( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL @@ -15,6 +15,7 @@ class DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -24,7 +25,5 @@ class DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel( } } - override fun getFriendlyName(): String { - return "BOLUS__SET_EXTENDED_BOLUS_CANCEL" - } + override val friendlyName: String = "BOLUS__SET_EXTENDED_BOLUS_CANCEL" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt similarity index 90% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt index 319e294895..0f4afcac1f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStart.kt @@ -8,11 +8,11 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Bolus_Set_Step_Bolus_Start( +class DanaRSPacketBolusSetStepBolusStart( injector: HasAndroidInjector, private var amount: Double = 0.0, private var speed: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @Inject lateinit var constraintChecker: ConstraintChecker @@ -45,7 +45,5 @@ class DanaRS_Packet_Bolus_Set_Step_Bolus_Start( } } - override fun getFriendlyName(): String { - return "BOLUS__SET_STEP_BOLUS_START" - } + override val friendlyName: String = "BOLUS__SET_STEP_BOLUS_START" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt similarity index 90% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt index a8f1bc0084..2262a2acde 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt @@ -10,9 +10,9 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject -open class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop( +open class DanaRSPacketBolusSetStepBolusStop( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -24,6 +24,7 @@ open class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -44,7 +45,5 @@ open class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop( rxBus.send(bolusingEvent) } - override fun getFriendlyName(): String { - return "BOLUS__SET_STEP_BOLUS_STOP" - } + override val friendlyName: String = "BOLUS__SET_STEP_BOLUS_STOP" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Etc_Keep_Connection.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketEtcKeepConnection.kt similarity index 80% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Etc_Keep_Connection.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketEtcKeepConnection.kt index 0a5f5f10b4..310a9adcc8 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Etc_Keep_Connection.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketEtcKeepConnection.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Etc_Keep_Connection( +class DanaRSPacketEtcKeepConnection( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_ETC__KEEP_CONNECTION @@ -15,6 +15,7 @@ class DanaRS_Packet_Etc_Keep_Connection( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -24,7 +25,5 @@ class DanaRS_Packet_Etc_Keep_Connection( } } - override fun getFriendlyName(): String { - return "ETC__KEEP_CONNECTION" - } + override val friendlyName: String = "ETC__KEEP_CONNECTION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Etc_Set_History_Save.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketEtcSetHistorySave.kt similarity index 90% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Etc_Set_History_Save.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketEtcSetHistorySave.kt index aa812ca588..a464c2d70d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Etc_Set_History_Save.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketEtcSetHistorySave.kt @@ -4,7 +4,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Etc_Set_History_Save( +class DanaRSPacketEtcSetHistorySave( injector: HasAndroidInjector, private var historyType: Int = 0, private var historyYear: Int = 0, @@ -15,7 +15,7 @@ class DanaRS_Packet_Etc_Set_History_Save( private var historySecond: Int = 0, private var historyCode: Int = 0, private var historyValue: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_ETC__SET_HISTORY_SAVE @@ -39,6 +39,7 @@ class DanaRS_Packet_Etc_Set_History_Save( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -48,7 +49,5 @@ class DanaRS_Packet_Etc_Set_History_Save( } } - override fun getFriendlyName(): String { - return "ETC__SET_HISTORY_SAVE" - } + override val friendlyName: String = "ETC__SET_HISTORY_SAVE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Pump_Check.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt similarity index 92% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Pump_Check.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt index 6c55bcee19..8085f4163a 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Pump_Check.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt @@ -11,9 +11,9 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject -class DanaRS_Packet_General_Get_Pump_Check( +class DanaRSPacketGeneralGetPumpCheck( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -47,7 +47,5 @@ class DanaRS_Packet_General_Get_Pump_Check( } } - override fun getFriendlyName(): String { - return "REVIEW__GET_PUMP_CHECK" - } -} \ No newline at end of file + override val friendlyName: String = "REVIEW__GET_PUMP_CHECK" + } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Shipping_Information.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetShippingInformation.kt similarity index 86% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Shipping_Information.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetShippingInformation.kt index edcb565f6c..c557fcc5c0 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Shipping_Information.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetShippingInformation.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_General_Get_Shipping_Information( +class DanaRSPacketGeneralGetShippingInformation( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -30,7 +30,5 @@ class DanaRS_Packet_General_Get_Shipping_Information( aapsLogger.debug(LTag.PUMPCOMM, "Shipping country: " + danaPump.shippingCountry) } - override fun getFriendlyName(): String { - return "REVIEW__GET_SHIPPING_INFORMATION" - } + override val friendlyName: String = "REVIEW__GET_SHIPPING_INFORMATION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Shipping_Version.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetShippingVersion.kt similarity index 81% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Shipping_Version.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetShippingVersion.kt index 4a83192d39..f69b920458 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Shipping_Version.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetShippingVersion.kt @@ -7,9 +7,9 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import java.nio.charset.Charset import javax.inject.Inject -class DanaRS_Packet_General_Get_Shipping_Version( +class DanaRSPacketGeneralGetShippingVersion( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -24,7 +24,5 @@ class DanaRS_Packet_General_Get_Shipping_Version( aapsLogger.debug(LTag.PUMPCOMM, "BLE Model: " + danaPump.bleModel) } - override fun getFriendlyName(): String { - return "GENERAL__GET_SHIPPING_VERSION" - } + override val friendlyName: String = "GENERAL__GET_SHIPPING_VERSION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetUserTimeChangeFlag.kt similarity index 80% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetUserTimeChangeFlag.kt index eaaecf7f03..4e4db0238c 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetUserTimeChangeFlag.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_General_Get_User_Time_Change_Flag( +class DanaRSPacketGeneralGetUserTimeChangeFlag( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG @@ -24,7 +24,5 @@ class DanaRS_Packet_General_Get_User_Time_Change_Flag( aapsLogger.debug(LTag.PUMPCOMM, "UserTimeChangeFlag: $userTimeChangeFlag") } - override fun getFriendlyName(): String { - return "REVIEW__GET_USER_TIME_CHANGE_FLAG" - } + override val friendlyName: String = "REVIEW__GET_USER_TIME_CHANGE_FLAG" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Initial_Screen_Information.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralInitialScreenInformation.kt similarity index 92% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Initial_Screen_Information.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralInitialScreenInformation.kt index 35a0e35487..3c7de5873d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Initial_Screen_Information.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralInitialScreenInformation.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_General_Initial_Screen_Information( +class DanaRSPacketGeneralInitialScreenInformation( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -70,11 +70,9 @@ class DanaRS_Packet_General_Initial_Screen_Information( aapsLogger.debug(LTag.PUMPCOMM, "Reservoir remaining units: " + danaPump.reservoirRemainingUnits) aapsLogger.debug(LTag.PUMPCOMM, "Battery: " + danaPump.batteryRemaining) aapsLogger.debug(LTag.PUMPCOMM, "Current basal: " + danaPump.currentBasal) - aapsLogger.debug(LTag.PUMPCOMM, "Temp basal percent: " + tempBasalPercent) + aapsLogger.debug(LTag.PUMPCOMM, "Temp basal percent: $tempBasalPercent") aapsLogger.debug(LTag.PUMPCOMM, "Extended absolute rate: $extendedBolusAbsoluteRate") } - override fun getFriendlyName(): String { - return "REVIEW__INITIAL_SCREEN_INFORMATION" - } + override val friendlyName: String = "REVIEW__INITIAL_SCREEN_INFORMATION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_History_Upload_Mode.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetHistoryUploadMode.kt similarity index 82% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_History_Upload_Mode.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetHistoryUploadMode.kt index c695632177..c51ce79577 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_History_Upload_Mode.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetHistoryUploadMode.kt @@ -4,10 +4,10 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_General_Set_History_Upload_Mode( +class DanaRSPacketGeneralSetHistoryUploadMode( injector: HasAndroidInjector, private var mode: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SET_HISTORY_UPLOAD_MODE @@ -22,6 +22,7 @@ class DanaRS_Packet_General_Set_History_Upload_Mode( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -31,7 +32,5 @@ class DanaRS_Packet_General_Set_History_Upload_Mode( } } - override fun getFriendlyName(): String { - return "REVIEW__SET_HISTORY_UPLOAD_MODE" - } + override val friendlyName: String = "REVIEW__SET_HISTORY_UPLOAD_MODE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetUserTimeChangeFlagClear.kt similarity index 77% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetUserTimeChangeFlagClear.kt index 45a5d01962..bac9212f24 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetUserTimeChangeFlagClear.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear( +class DanaRSPacketGeneralSetUserTimeChangeFlagClear( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR @@ -15,6 +15,7 @@ class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -24,7 +25,5 @@ class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear( } } - override fun getFriendlyName(): String { - return "REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR" - } + override val friendlyName: String = "REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt similarity index 99% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt index 63f0882acf..351e8a413a 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistory.kt @@ -15,10 +15,10 @@ import org.joda.time.DateTime import java.util.* import javax.inject.Inject -abstract class DanaRS_Packet_History_( +abstract class DanaRSPacketHistory( injector: HasAndroidInjector, protected val from: Long -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var danaHistoryRecordDao: DanaHistoryRecordDao diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Alarm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarm.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Alarm.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarm.kt index 23430fab80..b206792378 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Alarm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarm.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Alarm @JvmOverloads constructor( +class DanaRSPacketHistoryAlarm constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__ALARM aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__ALARM" - } + override val friendlyName: String = "REVIEW__ALARM" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_All_History.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAllHistory.kt similarity index 69% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_All_History.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAllHistory.kt index c8cbc8e39e..a6c44abce4 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_All_History.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAllHistory.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_All_History( +class DanaRSPacketHistoryAllHistory( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__ALL_HISTORY" - } + override val friendlyName: String = "REVIEW__ALL_HISTORY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Basal.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBasal.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Basal.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBasal.kt index 5166d9de0c..7c8a521b88 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Basal.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBasal.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Basal @JvmOverloads constructor( +class DanaRSPacketHistoryBasal @JvmOverloads constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BASAL aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__BASAL" - } + override val friendlyName: String = "REVIEW__BASAL" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Blood_Glucose.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBloodGlucose.kt similarity index 66% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Blood_Glucose.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBloodGlucose.kt index 237006ef4a..e11e7de3e5 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Blood_Glucose.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBloodGlucose.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Blood_Glucose @JvmOverloads constructor( +class DanaRSPacketHistoryBloodGlucose constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__BLOOD_GLUCOSE" - } + override val friendlyName: String = "REVIEW__BLOOD_GLUCOSE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBolus.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Bolus.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBolus.kt index 3b8cec0a6f..55b7d7cf43 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Bolus.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryBolus.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Bolus @JvmOverloads constructor( +class DanaRSPacketHistoryBolus constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BOLUS aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__BOLUS" - } + override val friendlyName: String = "REVIEW__BOLUS" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Carbohydrate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryCarbohydrate.kt similarity index 66% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Carbohydrate.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryCarbohydrate.kt index 6ac0f18b17..2f599ed452 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Carbohydrate.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryCarbohydrate.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Carbohydrate @JvmOverloads constructor( +class DanaRSPacketHistoryCarbohydrate constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__CARBOHYDRATE" - } + override val friendlyName: String = "REVIEW__CARBOHYDRATE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Daily.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryDaily.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Daily.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryDaily.kt index d0b3625e6a..20956e6304 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Daily.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryDaily.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Daily @JvmOverloads constructor( +class DanaRSPacketHistoryDaily constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__DAILY aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__DAILY" - } + override val friendlyName: String = "REVIEW__DAILY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Prime.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryPrime.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Prime.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryPrime.kt index 4069f9be0b..b87611ee9b 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Prime.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryPrime.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Prime @JvmOverloads constructor( +class DanaRSPacketHistoryPrime @JvmOverloads constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__PRIME aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__PRIME" - } + override val friendlyName: String = "REVIEW__PRIME" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Refill.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryRefill.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Refill.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryRefill.kt index ba83640f5b..ca59c45876 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Refill.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryRefill.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Refill @JvmOverloads constructor( +class DanaRSPacketHistoryRefill constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__REFILL aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__REFILL" - } + override val friendlyName: String = "REVIEW__REFILL" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Suspend.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistorySuspend.kt similarity index 67% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Suspend.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistorySuspend.kt index fdc4bb7086..ab920b8e5c 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Suspend.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistorySuspend.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Suspend @JvmOverloads constructor( +class DanaRSPacketHistorySuspend constructor( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SUSPEND aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__SUSPEND" - } + override val friendlyName: String = "REVIEW__SUSPEND" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Temporary.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryTemporary.kt similarity index 70% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Temporary.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryTemporary.kt index 534a0f0667..c7c909bf71 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_History_Temporary.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryTemporary.kt @@ -4,17 +4,15 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_History_Temporary( +class DanaRSPacketHistoryTemporary( injector: HasAndroidInjector, from: Long = 0 -) : DanaRS_Packet_History_(injector, from) { +) : DanaRSPacketHistory(injector, from) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY aapsLogger.debug(LTag.PUMPCOMM, "New message") } - override fun getFriendlyName(): String { - return "REVIEW__TEMPORARY" - } + override val friendlyName: String = "REVIEW__TEMPORARY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Alarm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt similarity index 95% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Alarm.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt index f49f25010a..f46b5581f4 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Alarm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt @@ -12,9 +12,9 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject -class DanaRS_Packet_Notify_Alarm( +class DanaRSPacketNotifyAlarm( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -69,7 +69,5 @@ class DanaRS_Packet_Notify_Alarm( pumpSync.insertAnnouncement(errorString, null, danaPump.pumpType(), danaPump.serialNumber) } - override fun getFriendlyName(): String { - return "NOTIFY__ALARM" - } + override val friendlyName: String = "NOTIFY__ALARM" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Complete.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt similarity index 90% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Complete.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt index fd245226d3..c6b55b2e96 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Complete.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt @@ -11,9 +11,9 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import kotlin.math.min -class DanaRS_Packet_Notify_Delivery_Complete( +class DanaRSPacketNotifyDeliveryComplete( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -37,7 +37,5 @@ class DanaRS_Packet_Notify_Delivery_Complete( aapsLogger.debug(LTag.PUMPCOMM, "Delivered insulin: $deliveredInsulin") } - override fun getFriendlyName(): String { - return "NOTIFY__DELIVERY_COMPLETE" - } + override val friendlyName: String = "NOTIFY__DELIVERY_COMPLETE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt similarity index 90% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt index 8c54865d4a..e1a18ddd40 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt @@ -11,9 +11,9 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import kotlin.math.min -class DanaRS_Packet_Notify_Delivery_Rate_Display( +class DanaRSPacketNotifyDeliveryRateDisplay( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @@ -37,7 +37,5 @@ class DanaRS_Packet_Notify_Delivery_Rate_Display( aapsLogger.debug(LTag.PUMPCOMM, "Delivered insulin so far: $deliveredInsulin") } - override fun getFriendlyName(): String { - return "NOTIFY__DELIVERY_RATE_DISPLAY" - } + override val friendlyName: String = "NOTIFY__DELIVERY_RATE_DISPLAY" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyMissedBolusAlarm.kt similarity index 89% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyMissedBolusAlarm.kt index 1fea0135ab..e8799c34e0 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyMissedBolusAlarm.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Notify_Missed_Bolus_Alarm( +class DanaRSPacketNotifyMissedBolusAlarm( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { type = BleEncryption.DANAR_PACKET__TYPE_NOTIFY @@ -38,7 +38,5 @@ class DanaRS_Packet_Notify_Missed_Bolus_Alarm( aapsLogger.debug(LTag.PUMPCOMM, "End min: $endMin") } - override fun getFriendlyName(): String { - return "NOTIFY__MISSED_BOLUS_ALARM" - } + override val friendlyName: String = "NOTIFY__MISSED_BOLUS_ALARM" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_Time.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetPumpTime.kt similarity index 89% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_Time.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetPumpTime.kt index ded5b89540..c726b6c8f1 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_Time.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetPumpTime.kt @@ -7,9 +7,9 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import org.joda.time.DateTime import javax.inject.Inject -class DanaRS_Packet_Option_Get_Pump_Time( +class DanaRSPacketOptionGetPumpTime( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -35,7 +35,5 @@ class DanaRS_Packet_Option_Get_Pump_Time( danaPump.resetPumpTime() } - override fun getFriendlyName(): String { - return "OPTION__GET_PUMP_TIME" - } + override val friendlyName: String = "OPTION__GET_PUMP_TIME" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetPumpUTCAndTimeZone.kt similarity index 88% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetPumpUTCAndTimeZone.kt index 61040521ea..c0015e505d 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetPumpUTCAndTimeZone.kt @@ -7,9 +7,9 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import org.joda.time.DateTime import javax.inject.Inject -class DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone( +class DanaRSPacketOptionGetPumpUTCAndTimeZone( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -36,7 +36,5 @@ class DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone( danaPump.resetPumpTime() } - override fun getFriendlyName(): String { - return "OPTION__GET_PUMP_UTC_AND_TIMEZONE" - } + override val friendlyName: String = "OPTION__GET_PUMP_UTC_AND_TIMEZONE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_User_Option.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetUserOption.kt similarity index 95% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_User_Option.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetUserOption.kt index 7c2a9fa16d..f6b88ca139 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Get_User_Option.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionGetUserOption.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Option_Get_User_Option( +class DanaRSPacketOptionGetUserOption( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -57,7 +57,5 @@ class DanaRS_Packet_Option_Get_User_Option( aapsLogger.debug(LTag.PUMPCOMM, "target: ${if (danaPump.units == DanaPump.UNITS_MGDL) danaPump.target else danaPump.target / 100}") } - override fun getFriendlyName(): String { - return "OPTION__GET_USER_OPTION" - } + override val friendlyName: String = "OPTION__GET_USER_OPTION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_Time.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpTime.kt similarity index 88% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_Time.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpTime.kt index dc4b6b0efe..e27646403a 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_Time.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpTime.kt @@ -5,10 +5,10 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption import org.joda.time.DateTime -class DanaRS_Packet_Option_Set_Pump_Time( +class DanaRSPacketOptionSetPumpTime( injector: HasAndroidInjector, private var time: Long = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { var error = 0 @@ -31,6 +31,7 @@ class DanaRS_Packet_Option_Set_Pump_Time( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -40,7 +41,5 @@ class DanaRS_Packet_Option_Set_Pump_Time( } } - override fun getFriendlyName(): String { - return "OPTION__SET_PUMP_TIME" - } + override val friendlyName: String = "OPTION__SET_PUMP_TIME" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpUTCAndTimeZone.kt similarity index 88% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpUTCAndTimeZone.kt index 3fbf79a388..afdaba9b5f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetPumpUTCAndTimeZone.kt @@ -6,11 +6,11 @@ import info.nightscout.androidaps.danars.encryption.BleEncryption import org.joda.time.DateTime import org.joda.time.DateTimeZone -class DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone( +class DanaRSPacketOptionSetPumpUTCAndTimeZone( injector: HasAndroidInjector, private var time: Long = 0, private var zoneOffset: Int = 0 -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { var error = 0 @@ -34,6 +34,7 @@ class DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -43,7 +44,5 @@ class DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone( } } - override fun getFriendlyName(): String { - return "OPTION__SET_PUMP_UTC_AND_TIMEZONE" - } + override val friendlyName: String = "OPTION__SET_PUMP_UTC_AND_TIMEZONE" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_User_Option.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOption.kt similarity index 94% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_User_Option.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOption.kt index ae2e0c03ef..e88969ab4f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Option_Set_User_Option.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOption.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Option_Set_User_Option( +class DanaRSPacketOptionSetUserOption( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -54,6 +54,7 @@ class DanaRS_Packet_Option_Set_User_Option( override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) + @Suppress("LiftReturnOrAssignment") if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false @@ -63,7 +64,5 @@ class DanaRS_Packet_Option_Set_User_Option( } } - override fun getFriendlyName(): String { - return "OPTION__SET_USER_OPTION" - } + override val friendlyName: String = "OPTION__SET_USER_OPTION" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Bolus_Avg.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewBolusAvg.kt similarity index 91% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Bolus_Avg.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewBolusAvg.kt index 6e0af1260f..5a1577f208 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Bolus_Avg.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewBolusAvg.kt @@ -4,9 +4,9 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption -class DanaRS_Packet_Review_Bolus_Avg( +class DanaRSPacketReviewBolusAvg( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG @@ -38,7 +38,5 @@ class DanaRS_Packet_Review_Bolus_Avg( aapsLogger.debug(LTag.PUMPCOMM, "Bolus average 28d: $bolusAvg28 U") } - override fun getFriendlyName(): String { - return "REVIEW__BOLUS_AVG" - } + override val friendlyName: String = "REVIEW__BOLUS_AVG" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Get_Pump_Dec_Ratio.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewGetPumpDecRatio.kt similarity index 80% rename from danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Get_Pump_Dec_Ratio.kt rename to danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewGetPumpDecRatio.kt index 990ffce54c..eafc4837d4 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Review_Get_Pump_Dec_Ratio.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketReviewGetPumpDecRatio.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption import javax.inject.Inject -class DanaRS_Packet_Review_Get_Pump_Dec_Ratio( +class DanaRSPacketReviewGetPumpDecRatio( injector: HasAndroidInjector -) : DanaRS_Packet(injector) { +) : DanaRSPacket(injector) { @Inject lateinit var danaPump: DanaPump @@ -23,7 +23,5 @@ class DanaRS_Packet_Review_Get_Pump_Dec_Ratio( aapsLogger.debug(LTag.PUMPCOMM, "Dec ratio: ${danaPump.decRatio}%") } - override fun getFriendlyName(): String { - return "REVIEW__GET_PUMP_DEC_RATIO" - } + override val friendlyName: String = "REVIEW__GET_PUMP_DEC_RATIO" } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.kt deleted file mode 100644 index 721479198c..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.kt +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import java.util.* -import javax.inject.Inject - -open class DanaRS_Packet_Basal_Get_Profile_Basal_Rate( - injector: HasAndroidInjector, - private val profileNumber: Int = 0 -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_BASAL_RATE - aapsLogger.debug(LTag.PUMPCOMM, "Requesting basal rates for profile $profileNumber") - } - - override fun getRequestParams(): ByteArray { - val request = ByteArray(1) - request[0] = (profileNumber and 0xff).toByte() - return request - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 2 - danaPump.pumpProfiles = Array(4) { Array(48) { 0.0 } } - var i = 0 - val size = 24 - while (i < size) { - danaPump.pumpProfiles!![profileNumber][i] = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - i++ - } - for (index in 0..23) - aapsLogger.debug(LTag.PUMPCOMM, "Basal " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaPump.pumpProfiles!![profileNumber][index]) - } - - override fun getFriendlyName(): String { - return "BASAL__GET_PROFILE_BASAL_RATE" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt deleted file mode 100644 index f8f475f759..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt +++ /dev/null @@ -1,55 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject -import kotlin.math.abs -import kotlin.math.ceil - -class DanaRS_Packet_Basal_Get_Temporary_Basal_State( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE - aapsLogger.debug(LTag.PUMPCOMM, "Requesting temporary basal status") - } - - var isTempBasalInProgress: Boolean = false - var tempBasalTotalSec: Int = 0 - var tempBasalPercent: Int = 0 - - override fun handleMessage(data: ByteArray) { - val error = byteArrayToInt(getBytes(data, DATA_START, 1)) - isTempBasalInProgress = byteArrayToInt(getBytes(data, DATA_START + 1, 1)) == 0x01 - val isAPSTempBasalInProgress = byteArrayToInt(getBytes(data, DATA_START + 1, 1)) == 0x02 - tempBasalPercent = byteArrayToInt(getBytes(data, DATA_START + 2, 1)) - if (tempBasalPercent > 200) tempBasalPercent = (tempBasalPercent - 200) * 10 - val durationHour = byteArrayToInt(getBytes(data, DATA_START + 3, 1)) - tempBasalTotalSec = if (durationHour == 150) 15 * 60 else if (durationHour == 160) 30 * 60 else durationHour * 60 * 60 - val runningMin = byteArrayToInt(getBytes(data, DATA_START + 4, 2)) - if (error != 0) failed = true - val tempBasalRemainingMin = (danaPump.tempBasalTotalSec - runningMin * 60) / 60 - val tempBasalStart = if (isTempBasalInProgress) getDateFromTempBasalSecAgo(runningMin * 60) else 0 - if (!isTempBasalInProgress) danaPump.isTempBasalInProgress = false - aapsLogger.debug(LTag.PUMPCOMM, "Error code: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Is temp basal running: $isTempBasalInProgress") - aapsLogger.debug(LTag.PUMPCOMM, "Is APS temp basal running: $isAPSTempBasalInProgress") - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal percent: $tempBasalPercent") - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal remaining min: $tempBasalRemainingMin") - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal total sec: $tempBasalTotalSec") - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal start: " + dateUtil.dateAndTimeString(tempBasalStart)) - } - - override fun getFriendlyName(): String { - return "BASAL__TEMPORARY_BASAL_STATE" - } - - private fun getDateFromTempBasalSecAgo(tempBasalAgoSecs: Int): Long { - return (ceil(System.currentTimeMillis() / 1000.0) - tempBasalAgoSecs).toLong() * 1000 - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Basal_Rate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Basal_Rate.kt deleted file mode 100644 index de96fb2c4d..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Basal_Set_Basal_Rate.kt +++ /dev/null @@ -1,45 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.danars.encryption.BleEncryption - -class DanaRS_Packet_Basal_Set_Basal_Rate( - injector: HasAndroidInjector, - private var profileBasalRate: Array -) : DanaRS_Packet(injector) { - - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__SET_BASAL_RATE - aapsLogger.debug(LTag.PUMPCOMM, "Setting new basal rates") - } - - override fun getRequestParams(): ByteArray { - val request = ByteArray(48) - var i = 0 - val size = 24 - while (i < size) { - val rate = (profileBasalRate[i] * 100.0).toInt() - request[0 + i * 2] = (rate and 0xff).toByte() - request[1 + i * 2] = (rate ushr 8 and 0xff).toByte() - i++ - } - 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 "BASAL__SET_BASAL_RATE" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.kt deleted file mode 100644 index e51a25967d..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.kt +++ /dev/null @@ -1,39 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject - -class DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_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 = 2 - val carbs = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaPump.currentCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - if (error != 0) failed = true - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Carbs: $carbs") - aapsLogger.debug(LTag.PUMPCOMM, "Current CIR: " + danaPump.currentCIR) - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt deleted file mode 100644 index 309f3ed561..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt +++ /dev/null @@ -1,37 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject - -class DanaRS_Packet_Bolus_Get_Dual_Bolus( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.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)) - danaPump.bolusStep = byteArrayToInt(getBytes(data, DATA_START + 1, 2)) / 100.0 - val extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, DATA_START + 3, 2)) / 100.0 - danaPump.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: ${danaPump.bolusStep} U") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: $extendedBolusAbsoluteRate U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaPump.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/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt deleted file mode 100644 index 623e1f8361..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt +++ /dev/null @@ -1,43 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject - -class DanaRS_Packet_Bolus_Get_Extended_Bolus( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.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 - val extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: $extendedBolusAbsoluteRate U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaPump.bolusStep + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_BOLUS" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt deleted file mode 100644 index e3e6cb9e45..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt +++ /dev/null @@ -1,54 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.T -import javax.inject.Inject - -class DanaRS_Packet_Bolus_Get_Extended_Bolus_State( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - var isExtendedInProgress: Boolean = false - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01 - dataIndex += dataSize - dataSize = 1 - val extendedBolusDuration = T.mins(byteArrayToInt(getBytes(data, dataIndex, dataSize)) * 30L).msecs() - dataIndex += dataSize - dataSize = 2 - val extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 // duration must be set first for recalculation to amount - dataIndex += dataSize - dataSize = 2 - val extendedBolusSoFarInMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - val 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: $isExtendedInProgress") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: $extendedBolusAbsoluteRate U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus duration: " + T.msecs(extendedBolusDuration).mins() + " min") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far: $extendedBolusSoFarInMinutes min") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus delivered so far: $extendedBolusDeliveredSoFar U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_BOLUS_STATE" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.kt deleted file mode 100644 index 9f4a26da6f..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject - -class DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_MENU_OPTION_STATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - var isExtendedInProgress: Boolean = false - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val extendedMenuOption = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01 - aapsLogger.debug(LTag.PUMPCOMM, "extendedMenuOption: $extendedMenuOption") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_MENU_OPTION_STATE" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.kt deleted file mode 100644 index 3c58bc5175..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.kt +++ /dev/null @@ -1,43 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.danars.encryption.BleEncryption - -class DanaRS_Packet_Bolus_Get_Initial_Bolus( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_RATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - val initialBolusValue01: Double - val initialBolusValue02: Double - val initialBolusValue03: Double - val initialBolusValue04: Double - var dataIndex = DATA_START - var dataSize = 2 - initialBolusValue01 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - initialBolusValue02 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - initialBolusValue03 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - initialBolusValue04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = initialBolusValue01 == 0.0 && initialBolusValue02 == 0.0 && initialBolusValue03 == 0.0 && initialBolusValue04 == 0.0 - aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount 01: $initialBolusValue01") - aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount 02: $initialBolusValue02") - aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount 03: $initialBolusValue03") - aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount 04: $initialBolusValue04") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_BOLUS_RATE" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.kt deleted file mode 100644 index 783b874f4a..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.kt +++ /dev/null @@ -1,77 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.danars.encryption.BleEncryption - -class DanaRS_Packet_Bolus_Set_CIR_CF_Array( - injector: HasAndroidInjector, - private var cir01: Int = 0, - private var cir02: Int = 0, - private var cir03: Int = 0, - private var cir04: Int = 0, - private var cir05: Int = 0, - private var cir06: Int = 0, - private var cir07: Int = 0, - private var cf01: Int = 0, - private var cf02: Int = 0, - private var cf03: Int = 0, - private var cf04: Int = 0, - private var cf05: Int = 0, - private var cf06: Int = 0, - private var cf07: Int = 0 -) : DanaRS_Packet(injector) { - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_CIR_CF_ARRAY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getRequestParams(): ByteArray { - val request = ByteArray(28) - request[0] = (cir01 and 0xff).toByte() - request[1] = (cir01 ushr 8 and 0xff).toByte() - request[2] = (cir02 and 0xff).toByte() - request[3] = (cir02 ushr 8 and 0xff).toByte() - request[4] = (cir03 and 0xff).toByte() - request[5] = (cir03 ushr 8 and 0xff).toByte() - request[6] = (cir04 and 0xff).toByte() - request[7] = (cir04 ushr 8 and 0xff).toByte() - request[8] = (cir05 and 0xff).toByte() - request[9] = (cir05 ushr 8 and 0xff).toByte() - request[10] = (cir06 and 0xff).toByte() - request[11] = (cir06 ushr 8 and 0xff).toByte() - request[12] = (cir07 and 0xff).toByte() - request[13] = (cir07 ushr 8 and 0xff).toByte() - request[14] = (cf01 and 0xff).toByte() - request[15] = (cf01 ushr 8 and 0xff).toByte() - request[16] = (cf02 and 0xff).toByte() - request[17] = (cf02 ushr 8 and 0xff).toByte() - request[18] = (cf03 and 0xff).toByte() - request[19] = (cf03 ushr 8 and 0xff).toByte() - request[20] = (cf04 and 0xff).toByte() - request[21] = (cf04 ushr 8 and 0xff).toByte() - request[22] = (cf05 and 0xff).toByte() - request[23] = (cf05 ushr 8 and 0xff).toByte() - request[24] = (cf06 and 0xff).toByte() - request[25] = (cf06 ushr 8 and 0xff).toByte() - request[26] = (cf07 and 0xff).toByte() - request[27] = (cf07 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 "BOLUS__SET_CIR_CF_ARRAY" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.kt deleted file mode 100644 index 0f93dbf349..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.kt +++ /dev/null @@ -1,45 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.danars.encryption.BleEncryption - -class DanaRS_Packet_Bolus_Set_Dual_Bolus( - injector: HasAndroidInjector, - private var amount: Double = 0.0, - private var extendedAmount: Double = 0.0, - private var extendedBolusDurationInHalfHours: Int = 0 -) : DanaRS_Packet(injector) { - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_DUAL_BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "Dual bolus start : $amount U extended: $extendedAmount U halfhours: $extendedBolusDurationInHalfHours") - } - - override fun getRequestParams(): ByteArray { - val stepBolusRate = (amount / 100.0).toInt() - val extendedBolusRate = (extendedAmount / 100.0).toInt() - val request = ByteArray(5) - request[0] = (stepBolusRate and 0xff).toByte() - request[1] = (stepBolusRate ushr 8 and 0xff).toByte() - request[2] = (extendedBolusRate and 0xff).toByte() - request[3] = (extendedBolusRate ushr 8 and 0xff).toByte() - request[4] = (extendedBolusDurationInHalfHours 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 "BOLUS__SET_DUAL_BOLUS" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.kt deleted file mode 100644 index 6b8278ac29..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.kt +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.danars.encryption.BleEncryption - -class DanaRS_Packet_Bolus_Set_Initial_Bolus( - injector: HasAndroidInjector, - private var bolusRate01: Int = 0, - private var bolusRate02: Int = 0, - private var bolusRate03: Int = 0, - private var bolusRate04: Int = 0 -) : DanaRS_Packet(injector) { - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_BOLUS_RATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getRequestParams(): ByteArray { - val request = ByteArray(8) - request[0] = (bolusRate01 and 0xff).toByte() - request[1] = (bolusRate01 ushr 8 and 0xff).toByte() - request[2] = (bolusRate02 and 0xff).toByte() - request[3] = (bolusRate02 ushr 8 and 0xff).toByte() - request[4] = (bolusRate03 and 0xff).toByte() - request[5] = (bolusRate03 ushr 8 and 0xff).toByte() - request[6] = (bolusRate04 and 0xff).toByte() - request[7] = (bolusRate04 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 "BOLUS__SET_BOLUS_RATE" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Delivery_Status.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Delivery_Status.kt deleted file mode 100644 index 9ff3884a57..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Delivery_Status.kt +++ /dev/null @@ -1,30 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.danars.encryption.BleEncryption - -class DanaRS_Packet_General_Delivery_Status( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - 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 "REVIEW__DELIVERY_STATUS" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_More_Information.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_More_Information.kt deleted file mode 100644 index 4659e91dae..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_More_Information.kt +++ /dev/null @@ -1,49 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import org.joda.time.DateTime -import org.joda.time.DateTimeZone -import javax.inject.Inject - -class DanaRS_Packet_General_Get_More_Information( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.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 - } - danaPump.iob = intFromBuff(data, 0, 2) / 100.0 - danaPump.dailyTotalUnits = intFromBuff(data, 2, 2) / 100.0 - val isExtendedInProgress = intFromBuff(data, 4, 1) == 0x01 - val extendedBolusRemainingMinutes = intFromBuff(data, 5, 2) - // val remainRate = intFromBuff(data, 7, 2) / 100.0 - val hours = intFromBuff(data, 9, 1) - val minutes = intFromBuff(data, 10, 1) - if (danaPump.usingUTC) danaPump.lastBolusTime = DateTime.now().withZone(DateTimeZone.UTC).withHourOfDay(hours).withMinuteOfHour(minutes).millis - else danaPump.lastBolusTime = DateTime.now().withHourOfDay(hours).withMinuteOfHour(minutes).millis - danaPump.lastBolusAmount = intFromBuff(data, 11, 2) / 100.0 - // On DanaRS DailyUnits can't be more than 160 - if (danaPump.dailyTotalUnits > 160) failed = true - aapsLogger.debug(LTag.PUMPCOMM, "Daily total units: " + danaPump.dailyTotalUnits.toString() + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Is extended in progress: $isExtendedInProgress") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus remaining minutes: $extendedBolusRemainingMinutes") - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + dateUtil.dateAndTimeAndSecondsString(danaPump.lastBolusTime)) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaPump.lastBolusAmount) - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_MORE_INFORMATION" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Password.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Password.kt deleted file mode 100644 index 34d9ce1238..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Password.kt +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject - -class DanaRS_Packet_General_Get_Password( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__GET_PASSWORD - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 2) { // returned data size is too small - failed = true - return - } else { - failed = false - } - var pass: Int = (data[DATA_START + 1].toInt() and 0x000000FF shl 8) + (data[DATA_START + 0].toInt() and 0x000000FF) - pass = pass xor 3463 - danaPump.rsPassword = Integer.toHexString(pass) - aapsLogger.debug(LTag.PUMPCOMM, "Pump password: " + danaPump.rsPassword) - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_PASSWORD" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt deleted file mode 100644 index 4eece3e5fe..0000000000 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt +++ /dev/null @@ -1,42 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.encryption.BleEncryption -import javax.inject.Inject - -class DanaRS_Packet_General_Get_Today_Delivery_Total( - injector: HasAndroidInjector -) : DanaRS_Packet(injector) { - - @Inject lateinit var danaPump: DanaPump - - init { - opCode = BleEncryption.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 - danaPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaPump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaPump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaPump.dailyTotalUnits + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Daily total bolus: " + danaPump.dailyTotalBolusUnits + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Daily total basal: " + danaPump.dailyTotalBasalUnits + " U") - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_TODAY_DELIVERY_TOTAL" - } -} \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/di/DanaRSCommModule.kt b/danars/src/main/java/info/nightscout/androidaps/danars/di/DanaRSCommModule.kt index f239525f85..cef12e716c 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/di/DanaRSCommModule.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/di/DanaRSCommModule.kt @@ -8,76 +8,60 @@ import info.nightscout.androidaps.danars.comm.* @Suppress("unused") abstract class DanaRSCommModule { - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet(): DanaRS_Packet - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(): DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Basal_Rate(): DanaRS_Packet_Basal_Get_Basal_Rate - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Profile_Basal_Rate(): DanaRS_Packet_Basal_Get_Profile_Basal_Rate - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Profile_Number(): DanaRS_Packet_Basal_Get_Profile_Number - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Basal_Rate(): DanaRS_Packet_Basal_Set_Basal_Rate - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Profile_Basal_Rate(): DanaRS_Packet_Basal_Set_Profile_Basal_Rate - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Profile_Number(): DanaRS_Packet_Basal_Set_Profile_Number - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Suspend_Off(): DanaRS_Packet_Basal_Set_Suspend_Off - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Suspend_On(): DanaRS_Packet_Basal_Set_Suspend_On - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Set_Temporary_Basal(): DanaRS_Packet_Basal_Set_Temporary_Basal - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Basal_Get_Temporary_Basal_State(): DanaRS_Packet_Basal_Get_Temporary_Basal_State - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Bolus_Option(): DanaRS_Packet_Bolus_Get_Bolus_Option - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Initial_Bolus(): DanaRS_Packet_Bolus_Get_Initial_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Calculation_Information(): DanaRS_Packet_Bolus_Get_Calculation_Information - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(): DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_CIR_CF_Array(): DanaRS_Packet_Bolus_Get_CIR_CF_Array - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_24_CIR_CF_Array(): DanaRS_Packet_Bolus_Get_24_CIR_CF_Array - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Dual_Bolus(): DanaRS_Packet_Bolus_Get_Dual_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Extended_Bolus(): DanaRS_Packet_Bolus_Get_Extended_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Extended_Bolus_State(): DanaRS_Packet_Bolus_Get_Extended_Bolus_State - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(): DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Get_Step_Bolus_Information(): DanaRS_Packet_Bolus_Get_Step_Bolus_Information - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Bolus_Option(): DanaRS_Packet_Bolus_Set_Bolus_Option - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Initial_Bolus(): DanaRS_Packet_Bolus_Set_Initial_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_CIR_CF_Array(): DanaRS_Packet_Bolus_Set_CIR_CF_Array - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_24_CIR_CF_Array(): DanaRS_Packet_Bolus_Set_24_CIR_CF_Array - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Dual_Bolus(): DanaRS_Packet_Bolus_Set_Dual_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Extended_Bolus(): DanaRS_Packet_Bolus_Set_Extended_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(): DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Step_Bolus_Start(): DanaRS_Packet_Bolus_Set_Step_Bolus_Start - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Bolus_Set_Step_Bolus_Stop(): DanaRS_Packet_Bolus_Set_Step_Bolus_Stop - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Etc_Keep_Connection(): DanaRS_Packet_Etc_Keep_Connection - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Etc_Set_History_Save(): DanaRS_Packet_Etc_Set_History_Save - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Delivery_Status(): DanaRS_Packet_General_Delivery_Status - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Password(): DanaRS_Packet_General_Get_Password - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Initial_Screen_Information(): DanaRS_Packet_General_Initial_Screen_Information - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Alarm(): DanaRS_Packet_Notify_Alarm - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Delivery_Complete(): DanaRS_Packet_Notify_Delivery_Complete - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Delivery_Rate_Display(): DanaRS_Packet_Notify_Delivery_Rate_Display - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Notify_Missed_Bolus_Alarm(): DanaRS_Packet_Notify_Missed_Bolus_Alarm - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Get_Pump_Time(): DanaRS_Packet_Option_Get_Pump_Time - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Get_User_Option(): DanaRS_Packet_Option_Get_User_Option - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Set_Pump_Time(): DanaRS_Packet_Option_Set_Pump_Time - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Set_User_Option(): DanaRS_Packet_Option_Set_User_Option - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_(): DanaRS_Packet_History_ - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Alarm(): DanaRS_Packet_History_Alarm - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_All_History(): DanaRS_Packet_History_All_History - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Basal(): DanaRS_Packet_History_Basal - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Blood_Glucose(): DanaRS_Packet_History_Blood_Glucose - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Bolus(): DanaRS_Packet_History_Bolus - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Review_Bolus_Avg(): DanaRS_Packet_Review_Bolus_Avg - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Carbohydrate(): DanaRS_Packet_History_Carbohydrate - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Daily(): DanaRS_Packet_History_Daily - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_More_Information(): DanaRS_Packet_General_Get_More_Information - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Pump_Check(): DanaRS_Packet_General_Get_Pump_Check - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Shipping_Information(): DanaRS_Packet_General_Get_Shipping_Information - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Today_Delivery_Total(): DanaRS_Packet_General_Get_Today_Delivery_Total - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_User_Time_Change_Flag(): DanaRS_Packet_General_Get_User_Time_Change_Flag - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Prime(): DanaRS_Packet_History_Prime - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Refill(): DanaRS_Packet_History_Refill - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Set_History_Upload_Mode(): DanaRS_Packet_General_Set_History_Upload_Mode - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(): DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Suspend(): DanaRS_Packet_History_Suspend - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_History_Temporary(): DanaRS_Packet_History_Temporary - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_APS_Basal_Set_Temporary_Basal(): DanaRS_Packet_APS_Basal_Set_Temporary_Basal - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_APS_History_Events(): DanaRS_Packet_APS_History_Events - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_APS_Set_Event_History(): DanaRS_Packet_APS_Set_Event_History - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_General_Get_Shipping_Version(): DanaRS_Packet_General_Get_Shipping_Version - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Review_Get_Pump_Dec_Ratio(): DanaRS_Packet_Review_Get_Pump_Dec_Ratio - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(): DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone - @ContributesAndroidInjector abstract fun contributesDanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(): DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone + @ContributesAndroidInjector abstract fun contributesDanaRSPacket(): DanaRSPacket + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalSetCancelTemporaryBasal(): DanaRSPacketBasalSetCancelTemporaryBasal + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalGetBasalRate(): DanaRSPacketBasalGetBasalRate + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalGetProfileNumber(): DanaRSPacketBasalGetProfileNumber + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalSetProfileBasalRate(): DanaRSPacketBasalSetProfileBasalRate + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalSetProfileNumber(): DanaRSPacketBasalSetProfileNumber + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalSetSuspendOff(): DanaRSPacketBasalSetSuspendOff + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalSetSuspendOn(): DanaRSPacketBasalSetSuspendOn + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBasalSetTemporaryBasal(): DanaRSPacketBasalSetTemporaryBasal + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusGetBolusOption(): DanaRSPacketBolusGetBolusOption + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusGetCalculationInformation(): DanaRSPacketBolusGetCalculationInformation + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusGetCIRCFArray(): DanaRSPacketBolusGetCIRCFArray + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusGetStepBolusInformation(): DanaRSPacketBolusGetStepBolusInformation + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusSetBolusOption(): DanaRSPacketBolusSetBolusOption + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusGet24CIRCFArray(): DanaRSPacketBolusGet24CIRCFArray + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusSet24CIRCFArray(): DanaRSPacketBolusSet24CIRCFArray + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusSetExtendedBolus(): DanaRSPacketBolusSetExtendedBolus + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusSetExtendedBolusCancel(): DanaRSPacketBolusSetExtendedBolusCancel + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusSetStepBolusStart(): DanaRSPacketBolusSetStepBolusStart + @ContributesAndroidInjector abstract fun contributesDanaRSPacketBolusSetStepBolusStop(): DanaRSPacketBolusSetStepBolusStop + @ContributesAndroidInjector abstract fun contributesDanaRSPacketEtcKeepConnection(): DanaRSPacketEtcKeepConnection + @ContributesAndroidInjector abstract fun contributesDanaRSPacketEtcSetHistorySave(): DanaRSPacketEtcSetHistorySave + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralInitialScreenInformation(): DanaRSPacketGeneralInitialScreenInformation + @ContributesAndroidInjector abstract fun contributesDanaRSPacketNotifyDeliveryRateDisplay(): DanaRSPacketNotifyDeliveryRateDisplay + @ContributesAndroidInjector abstract fun contributesDanaRSPacketNotifyAlarm(): DanaRSPacketNotifyAlarm + @ContributesAndroidInjector abstract fun contributesDanaRSPacketNotifyDeliveryComplete(): DanaRSPacketNotifyDeliveryComplete + @ContributesAndroidInjector abstract fun contributesDanaRSPacketNotifyMissedBolusAlarm(): DanaRSPacketNotifyMissedBolusAlarm + @ContributesAndroidInjector abstract fun contributesDanaRSPacketOptionGetPumpTime(): DanaRSPacketOptionGetPumpTime + @ContributesAndroidInjector abstract fun contributesDanaRSPacketOptionGetUserOption(): DanaRSPacketOptionGetUserOption + @ContributesAndroidInjector abstract fun contributesDanaRSPacketOptionSetPumpTime(): DanaRSPacketOptionSetPumpTime + @ContributesAndroidInjector abstract fun contributesDanaRSPacketOptionSetUserOption(): DanaRSPacketOptionSetUserOption + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistory(): DanaRSPacketHistory + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryAlarm(): DanaRSPacketHistoryAlarm + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryAllHistory(): DanaRSPacketHistoryAllHistory + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryBasal(): DanaRSPacketHistoryBasal + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryBloodGlucose(): DanaRSPacketHistoryBloodGlucose + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryBolus(): DanaRSPacketHistoryBolus + @ContributesAndroidInjector abstract fun contributesDanaRSPacketReviewBolusAvg(): DanaRSPacketReviewBolusAvg + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryCarbohydrate(): DanaRSPacketHistoryCarbohydrate + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryDaily(): DanaRSPacketHistoryDaily + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralGetPumpCheck(): DanaRSPacketGeneralGetPumpCheck + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralGetShippingInformation(): DanaRSPacketGeneralGetShippingInformation + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralGetUserTimeChangeFlag(): DanaRSPacketGeneralGetUserTimeChangeFlag + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryPrime(): DanaRSPacketHistoryPrime + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryRefill(): DanaRSPacketHistoryRefill + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralSetHistoryUploadMode(): DanaRSPacketGeneralSetHistoryUploadMode + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralSetUserTimeChangeFlagClear(): DanaRSPacketGeneralSetUserTimeChangeFlagClear + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistorySuspend(): DanaRSPacketHistorySuspend + @ContributesAndroidInjector abstract fun contributesDanaRSPacketHistoryTemporary(): DanaRSPacketHistoryTemporary + @ContributesAndroidInjector abstract fun contributesDanaRSPacketAPSBasalSetTemporaryBasal(): DanaRSPacketAPSBasalSetTemporaryBasal + @ContributesAndroidInjector abstract fun contributesDanaRSPacketAPSHistoryEvents(): DanaRSPacketAPSHistoryEvents + @ContributesAndroidInjector abstract fun contributesDanaRSPacketAPSSetEventHistory(): DanaRSPacketAPSSetEventHistory + @ContributesAndroidInjector abstract fun contributesDanaRSPacketGeneralGetShippingVersion(): DanaRSPacketGeneralGetShippingVersion + @ContributesAndroidInjector abstract fun contributesDanaRSPacketReviewGetPumpDecRatio(): DanaRSPacketReviewGetPumpDecRatio + @ContributesAndroidInjector abstract fun contributesDanaRSPacketOptionGetPumpUTCAndTimeZone(): DanaRSPacketOptionGetPumpUTCAndTimeZone + @ContributesAndroidInjector abstract fun contributesDanaRSPacketOptionSetPumpUTCAndTimeZone(): DanaRSPacketOptionSetPumpUTCAndTimeZone } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt index 866eee6251..241720a19e 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt @@ -12,8 +12,8 @@ import info.nightscout.androidaps.danars.R import info.nightscout.androidaps.danars.activities.EnterPinActivity import info.nightscout.androidaps.danars.activities.PairingHelperActivity import info.nightscout.androidaps.danars.comm.DanaRSMessageHashTable -import info.nightscout.androidaps.danars.comm.DanaRS_Packet -import info.nightscout.androidaps.danars.comm.DanaRS_Packet_Etc_Keep_Connection +import info.nightscout.androidaps.danars.comm.DanaRSPacket +import info.nightscout.androidaps.danars.comm.DanaRSPacketEtcKeepConnection import info.nightscout.androidaps.danars.encryption.BleEncryption import info.nightscout.androidaps.danars.encryption.EncryptionType import info.nightscout.androidaps.danars.events.EventDanaRSPairingSuccess @@ -67,7 +67,7 @@ class BLEComm @Inject internal constructor( } private var scheduledDisconnection: ScheduledFuture<*>? = null - private var processedMessage: DanaRS_Packet? = null + private var processedMessage: DanaRSPacket? = null private val mSendQueue = ArrayList() private var bluetoothManager: BluetoothManager? = null private var bluetoothAdapter: BluetoothAdapter? = null @@ -408,10 +408,8 @@ class BLEComm @Inject internal constructor( bufferLength -= length + 7 // now we have encrypted packet in inputBuffer - val decrypted = bleEncryption.getDecryptedPacket(inputBuffer) - //aapsLogger.debug(LTag.PUMPBTCOMM, "XXXXXX <<<<< PROCESSING: " + DanaRS_Packet.toHexString(inputBuffer)) - //aapsLogger.debug(LTag.PUMPBTCOMM, "XXXXXY <<<<< PROCESSING: " + DanaRS_Packet.toHexString(decrypted)) // decrypt the packet + val decrypted = bleEncryption.getDecryptedPacket(inputBuffer) decrypted?.let { decryptedBuffer -> if (decryptedBuffer[0] == BleEncryption.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE.toByte()) { when (decryptedBuffer[1]) { @@ -470,7 +468,7 @@ class BLEComm @Inject internal constructor( return } val bytes = bleEncryption.getEncryptedPacket(BleEncryption.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, deviceName) - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRSPacket.toHexString(bytes)) writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) } @@ -479,7 +477,7 @@ class BLEComm @Inject internal constructor( private fun processConnectResponse(decryptedBuffer: ByteArray) { // response OK v1 if (decryptedBuffer.size == 4 && decryptedBuffer[2] == 'O'.code.toByte() && decryptedBuffer[3] == 'K'.code.toByte()) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) encryption = EncryptionType.ENCRYPTION_DEFAULT danaPump.ignoreUserPassword = false // Grab pairing key from preferences if exists @@ -502,11 +500,11 @@ class BLEComm @Inject internal constructor( sp.putString(resourceHelper.gs(R.string.key_danars_v3_randomsynckey) + danaRSPlugin.mDeviceName, String.format("%02x", decryptedBuffer[decryptedBuffer.size - 1])) if (danaPump.hwModel == 0x05) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK V3 (OK)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK V3 (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) // Dana RS Pump sendV3PairingInformation() } else if (danaPump.hwModel == 0x06) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK V3 EASY (OK)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK V3 EASY (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) // Dana RS Easy sendEasyMenuCheck() } @@ -517,17 +515,17 @@ class BLEComm @Inject internal constructor( danaPump.ignoreUserPassword = true danaPump.hwModel = decryptedBuffer[5].toInt() danaPump.protocol = decryptedBuffer[7].toInt() - val pairingKey = DanaRS_Packet.asciiStringFromBuff(decryptedBuffer, 8, 6) // used while bonding + val pairingKey = DanaRSPacket.asciiStringFromBuff(decryptedBuffer, 8, 6) // used while bonding if (danaPump.hwModel == 0x09) { bleEncryption.setBle5Key(pairingKey.encodeToByteArray()) - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK BLE5 (OK)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK BLE5 (OK)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) // Dana-i BLE5 Pump sendBLE5PairingInformation() } // response PUMP : error status } else if (decryptedBuffer.size == 6 && decryptedBuffer[2] == 'P'.code.toByte() && decryptedBuffer[3] == 'U'.code.toByte() && decryptedBuffer[4] == 'M'.code.toByte() && decryptedBuffer[5] == 'P'.code.toByte()) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) mSendQueue.clear() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.pumperror))) pumpSync.insertAnnouncement(resourceHelper.gs(R.string.pumperror), null, danaPump.pumpType(), danaPump.serialNumber) @@ -535,12 +533,12 @@ class BLEComm @Inject internal constructor( rxBus.send(EventNewNotification(n)) // response BUSY: error status } else if (decryptedBuffer.size == 6 && decryptedBuffer[2] == 'B'.code.toByte() && decryptedBuffer[3] == 'U'.code.toByte() && decryptedBuffer[4] == 'S'.code.toByte() && decryptedBuffer[5] == 'Y'.code.toByte()) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) mSendQueue.clear() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.pumpbusy))) } else { // ERROR in response, wrong serial number - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRSPacket.toHexString(decryptedBuffer)) mSendQueue.clear() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, resourceHelper.gs(R.string.connectionerror))) danaRSPlugin.clearPairing() @@ -551,15 +549,15 @@ class BLEComm @Inject internal constructor( // 2nd packet v1 check passkey private fun sendPasskeyCheck(pairingKey: String) { - val encodedPairingKey = DanaRS_Packet.hexToBytes(pairingKey) + val encodedPairingKey = DanaRSPacket.hexToBytes(pairingKey) val bytes = bleEncryption.getEncryptedPacket(BleEncryption.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY, encodedPairingKey, null) - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRSPacket.toHexString(bytes)) writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) } // 2nd packet v1 response private fun processPasskeyCheck(decryptedBuffer: ByteArray) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRSPacket.toHexString(decryptedBuffer)) // Paring is not requested, sending time info if (decryptedBuffer[2] == 0x00.toByte()) sendTimeInfo() // Pairing on pump is requested @@ -590,20 +588,20 @@ class BLEComm @Inject internal constructor( private fun sendBLE5PairingInformation() { val params = ByteArray(4) { 0.toByte() } val bytes: ByteArray = bleEncryption.getEncryptedPacket(BleEncryption.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, params, null) - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__TIME_INFORMATION BLE5" + " " + DanaRS_Packet.toHexString(bytes)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__TIME_INFORMATION BLE5" + " " + DanaRSPacket.toHexString(bytes)) writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) } private fun sendV3PairingInformation(requestNewPairing: Int) { val params = byteArrayOf(requestNewPairing.toByte()) val bytes: ByteArray = bleEncryption.getEncryptedPacket(BleEncryption.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, params, null) - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRSPacket.toHexString(bytes)) writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) } // 2nd packet response private fun processEncryptionResponse(decryptedBuffer: ByteArray) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__TIME_INFORMATION " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__TIME_INFORMATION " + DanaRSPacket.toHexString(decryptedBuffer)) if (encryption == EncryptionType.ENCRYPTION_BLE5) { isConnected = true isConnecting = false @@ -651,7 +649,7 @@ class BLEComm @Inject internal constructor( // 3rd packet v1 existing pairing private fun sendTimeInfo() { val bytes = bleEncryption.getEncryptedPacket(BleEncryption.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, null, null) - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRSPacket.toHexString(bytes)) writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) } @@ -661,7 +659,7 @@ class BLEComm @Inject internal constructor( // On pump pairing request is displayed and is waiting for conformation context.startActivity(Intent(context, PairingHelperActivity::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) val bytes = bleEncryption.getEncryptedPacket(BleEncryption.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null) - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRSPacket.toHexString(bytes)) writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) } @@ -680,7 +678,7 @@ class BLEComm @Inject internal constructor( // 2nd or 3rd packet v1 response private fun processPairingRequest(decryptedBuffer: ByteArray) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRSPacket.toHexString(decryptedBuffer)) if (decryptedBuffer[2] != 0x00.toByte()) { disconnect("passkey request failed") } @@ -688,14 +686,14 @@ class BLEComm @Inject internal constructor( // 2nd or 3rd packet v1 response private fun processPairingRequest2(decryptedBuffer: ByteArray) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRSPacket.toHexString(decryptedBuffer)) // Paring is successful, sending time info rxBus.send(EventDanaRSPairingSuccess()) sendTimeInfo() val pairingKey = byteArrayOf(decryptedBuffer[2], decryptedBuffer[3]) // store pairing key to preferences - sp.putString(resourceHelper.gs(R.string.key_danars_pairingkey) + danaRSPlugin.mDeviceName, DanaRS_Packet.bytesToHex(pairingKey)) - aapsLogger.debug(LTag.PUMPBTCOMM, "Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey)) + sp.putString(resourceHelper.gs(R.string.key_danars_pairingkey) + danaRSPlugin.mDeviceName, DanaRSPacket.bytesToHex(pairingKey)) + aapsLogger.debug(LTag.PUMPBTCOMM, "Got pairing key: " + DanaRSPacket.bytesToHex(pairingKey)) } // 3rd packet Easy menu pump @@ -715,12 +713,12 @@ class BLEComm @Inject internal constructor( } // the rest of packets - fun sendMessage(message: DanaRS_Packet) { + fun sendMessage(message: DanaRSPacket) { encryptedCommandSent = true processedMessage = message val command = byteArrayOf(message.type.toByte(), message.opCode.toByte()) val params = message.getRequestParams() - aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)) + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.friendlyName + " " + DanaRSPacket.toHexString(command) + " " + DanaRSPacket.toHexString(params)) var bytes = bleEncryption.getEncryptedPacket(message.opCode, params, null) // aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + DanaRS_Packet.toHexString(bytes)) if (encryption != EncryptionType.ENCRYPTION_DEFAULT) @@ -780,19 +778,19 @@ class BLEComm @Inject internal constructor( //SystemClock.sleep(200); if (!message.isReceived) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Reply not received " + message.getFriendlyName()) + aapsLogger.warn(LTag.PUMPBTCOMM, "Reply not received " + message.friendlyName) message.handleMessageNotReceived() } // verify encryption for v3 - if (message is DanaRS_Packet_Etc_Keep_Connection) + if (message is DanaRSPacketEtcKeepConnection) if (!message.isReceived) disconnect("KeepAlive not received") } // process common packet response private fun processMessage(decryptedBuffer: ByteArray) { val originalCommand = processedMessage?.command ?: 0xFFFF - val receivedCommand = DanaRS_Packet(injector).getCommand(decryptedBuffer) - val message: DanaRS_Packet? = if (originalCommand == receivedCommand) { + val receivedCommand = DanaRSPacket(injector).getCommand(decryptedBuffer) + val message: DanaRSPacket? = if (originalCommand == receivedCommand) { // it's response to last message processedMessage } else { @@ -800,7 +798,7 @@ class BLEComm @Inject internal constructor( danaRSMessageHashTable.findMessage(receivedCommand) } if (message != null) { - aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(decryptedBuffer)) + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + message.friendlyName + " " + DanaRSPacket.toHexString(decryptedBuffer)) // process received data message.handleMessage(decryptedBuffer) message.setReceived() @@ -808,7 +806,7 @@ class BLEComm @Inject internal constructor( // notify to sendMessage message.notify() } - } else aapsLogger.error("Unknown message received " + DanaRS_Packet.toHexString(decryptedBuffer)) + } else aapsLogger.error("Unknown message received " + DanaRSPacket.toHexString(decryptedBuffer)) } } \ No newline at end of file diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt index 43b3b8fa9d..b541f1096f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt @@ -110,7 +110,7 @@ class DanaRSService : DaggerService() { bleComm.disconnect(from) } - fun sendMessage(message: DanaRS_Packet) { + fun sendMessage(message: DanaRSPacket) { bleComm.sendMessage(message) } @@ -118,20 +118,20 @@ class DanaRSService : DaggerService() { try { val pump = activePlugin.activePump rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) - sendMessage(DanaRS_Packet_Etc_Keep_Connection(injector)) // test encryption for v3 - sendMessage(DanaRS_Packet_General_Get_Shipping_Information(injector)) // serial no - sendMessage(DanaRS_Packet_General_Get_Pump_Check(injector)) // firmware - sendMessage(DanaRS_Packet_Basal_Get_Profile_Number(injector)) - sendMessage(DanaRS_Packet_Bolus_Get_Bolus_Option(injector)) // isExtendedEnabled - sendMessage(DanaRS_Packet_Basal_Get_Basal_Rate(injector)) // basal profile, basalStep, maxBasal - sendMessage(DanaRS_Packet_Bolus_Get_Calculation_Information(injector)) // target - if (danaPump.profile24) sendMessage(DanaRS_Packet_Bolus_Get_24_CIR_CF_Array(injector)) - else sendMessage(DanaRS_Packet_Bolus_Get_CIR_CF_Array(injector)) - sendMessage(DanaRS_Packet_Option_Get_User_Option(injector)) // Getting user options + sendMessage(DanaRSPacketEtcKeepConnection(injector)) // test encryption for v3 + sendMessage(DanaRSPacketGeneralGetShippingInformation(injector)) // serial no + sendMessage(DanaRSPacketGeneralGetPumpCheck(injector)) // firmware + sendMessage(DanaRSPacketBasalGetProfileNumber(injector)) + sendMessage(DanaRSPacketBolusGetBolusOption(injector)) // isExtendedEnabled + sendMessage(DanaRSPacketBasalGetBasalRate(injector)) // basal profile, basalStep, maxBasal + sendMessage(DanaRSPacketBolusGetCalculationInformation(injector)) // target + if (danaPump.profile24) sendMessage(DanaRSPacketBolusGet24CIRCFArray(injector)) + else sendMessage(DanaRSPacketBolusGetCIRCFArray(injector)) + sendMessage(DanaRSPacketOptionGetUserOption(injector)) // Getting user options rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))) - sendMessage(DanaRS_Packet_General_Initial_Screen_Information(injector)) + sendMessage(DanaRSPacketGeneralInitialScreenInformation(injector)) rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) - sendMessage(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) // last bolus, bolusStep, maxBolus + sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus, bolusStep, maxBolus danaPump.lastConnection = System.currentTimeMillis() val profile = profileFunction.getProfile() if (profile != null && abs(danaPump.currentBasal - profile.getBasal()) >= pump.pumpDescription.basalStep) { @@ -141,8 +141,8 @@ class DanaRSService : DaggerService() { } } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))) - if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector)) - else sendMessage(DanaRS_Packet_Option_Get_Pump_Time(injector)) + if (danaPump.usingUTC) sendMessage(DanaRSPacketOptionGetPumpUTCAndTimeZone(injector)) + else sendMessage(DanaRSPacketOptionGetPumpTime(injector)) var timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L if (danaPump.getPumpTime() == 0L) { // initial handshake was not successful @@ -172,21 +172,21 @@ class DanaRSService : DaggerService() { } else { when { danaPump.usingUTC -> { - sendMessage(DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(injector, dateUtil.now(), offset)) + sendMessage(DanaRSPacketOptionSetPumpUTCAndTimeZone(injector, dateUtil.now(), offset)) } danaPump.protocol >= 6 -> { // can set seconds - sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, dateUtil.now())) + sendMessage(DanaRSPacketOptionSetPumpTime(injector, dateUtil.now())) } else -> { waitForWholeMinute() // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cut off anyway) - sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, dateUtil.now() + T.secs(10).msecs())) + sendMessage(DanaRSPacketOptionSetPumpTime(injector, dateUtil.now() + T.secs(10).msecs())) } } - if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector)) - else sendMessage(DanaRS_Packet_Option_Get_Pump_Time(injector)) + if (danaPump.usingUTC) sendMessage(DanaRSPacketOptionGetPumpUTCAndTimeZone(injector)) + else sendMessage(DanaRSPacketOptionGetPumpTime(injector)) timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds") } @@ -221,12 +221,12 @@ class DanaRSService : DaggerService() { return result } SystemClock.sleep(1000) - val msg: DanaRS_Packet_APS_History_Events + val msg: DanaRSPacketAPSHistoryEvents if (danaPump.lastHistoryFetched == 0L) { - msg = DanaRS_Packet_APS_History_Events(injector, 0) + msg = DanaRSPacketAPSHistoryEvents(injector, 0) aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history") } else { - msg = DanaRS_Packet_APS_History_Events(injector, danaPump.lastHistoryFetched) + msg = DanaRSPacketAPSHistoryEvents(injector, danaPump.lastHistoryFetched) aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(danaPump.lastHistoryFetched)) } sendMessage(msg) @@ -240,7 +240,7 @@ class DanaRSService : DaggerService() { } fun setUserSettings(): PumpEnactResult { - val message = DanaRS_Packet_Option_Set_User_Option(injector) + val message = DanaRSPacketOptionSetUserOption(injector) sendMessage(message) return PumpEnactResult(injector).success(message.success()) } @@ -256,11 +256,11 @@ class DanaRSService : DaggerService() { danaPump.bolusStopped = false danaPump.bolusStopForced = false danaPump.bolusProgressLastTimeStamp = dateUtil.now() - val start = DanaRS_Packet_Bolus_Set_Step_Bolus_Start(injector, insulin, preferencesSpeed) + val start = DanaRSPacketBolusSetStepBolusStart(injector, insulin, preferencesSpeed) if (carbs > 0) { // MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbTime, carbs); #### // sendMessage(msg); - val msgSetHistoryEntryV2 = DanaRS_Packet_APS_Set_Event_History(injector, DanaPump.CARBS, carbTime, carbs, 0) + val msgSetHistoryEntryV2 = DanaRSPacketAPSSetEventHistory(injector, DanaPump.CARBS, carbTime, carbs, 0) sendMessage(msgSetHistoryEntryV2) danaPump.lastHistoryFetched = min(danaPump.lastHistoryFetched, carbTime - T.mins(1).msecs()) } @@ -305,7 +305,7 @@ class DanaRSService : DaggerService() { override fun run() { // reread bolus status rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) - sendMessage(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) // last bolus + sendMessage(DanaRSPacketBolusGetStepBolusInformation(injector)) // last bolus bolusingEvent.percent = 100 rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))) } @@ -315,7 +315,7 @@ class DanaRSService : DaggerService() { fun bolusStop() { aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + if (danaPump.bolusingTreatment == null) "" else danaPump.bolusingTreatment?.insulin) - val stop = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(injector) + val stop = DanaRSPacketBolusSetStepBolusStop(injector) danaPump.bolusStopForced = true if (isConnected) { sendMessage(stop) @@ -332,11 +332,11 @@ class DanaRSService : DaggerService() { if (!isConnected) return false if (danaPump.isTempBasalInProgress) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) - sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) + sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) SystemClock.sleep(500) } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) - val msgTBR = DanaRS_Packet_Basal_Set_Temporary_Basal(injector, percent, durationInHours) + val msgTBR = DanaRSPacketBasalSetTemporaryBasal(injector, percent, durationInHours) sendMessage(msgTBR) SystemClock.sleep(200) loadEvents() @@ -349,11 +349,11 @@ class DanaRSService : DaggerService() { fun highTempBasal(percent: Int): Boolean { if (danaPump.isTempBasalInProgress) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) - sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) + sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) SystemClock.sleep(500) } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) - val msgTBR = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, percent) + val msgTBR = DanaRSPacketAPSBasalSetTemporaryBasal(injector, percent) sendMessage(msgTBR) loadEvents() val tbr = pumpSync.expectedPumpState().temporaryBasal @@ -369,11 +369,11 @@ class DanaRSService : DaggerService() { } if (danaPump.isTempBasalInProgress) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) - sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) + sendMessage(DanaRSPacketBasalSetCancelTemporaryBasal(injector)) SystemClock.sleep(500) } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) - val msgTBR = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, percent) + val msgTBR = DanaRSPacketAPSBasalSetTemporaryBasal(injector, percent) sendMessage(msgTBR) loadEvents() val tbr = pumpSync.expectedPumpState().temporaryBasal @@ -385,7 +385,7 @@ class DanaRSService : DaggerService() { fun tempBasalStop(): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) - val msgCancel = DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector) + val msgCancel = DanaRSPacketBasalSetCancelTemporaryBasal(injector) sendMessage(msgCancel) loadEvents() val tbr = pumpSync.expectedPumpState().temporaryBasal @@ -397,7 +397,7 @@ class DanaRSService : DaggerService() { fun extendedBolus(insulin: Double, durationInHalfHours: Int): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))) - val msgExtended = DanaRS_Packet_Bolus_Set_Extended_Bolus(injector, insulin, durationInHalfHours) + val msgExtended = DanaRSPacketBolusSetExtendedBolus(injector, insulin, durationInHalfHours) sendMessage(msgExtended) SystemClock.sleep(200) loadEvents() @@ -410,7 +410,7 @@ class DanaRSService : DaggerService() { fun extendedBolusStop(): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))) - val msgStop = DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(injector) + val msgStop = DanaRSPacketBolusSetExtendedBolusCancel(injector) sendMessage(msgStop) loadEvents() val eb = pumpSync.expectedPumpState().extendedBolus @@ -423,12 +423,12 @@ class DanaRSService : DaggerService() { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))) val basal = danaPump.buildDanaRProfileRecord(profile) - val msgSet = DanaRS_Packet_Basal_Set_Profile_Basal_Rate(injector, 0, basal) + val msgSet = DanaRSPacketBasalSetProfileBasalRate(injector, 0, basal) sendMessage(msgSet) - val msgActivate = DanaRS_Packet_Basal_Set_Profile_Number(injector, 0) + val msgActivate = DanaRSPacketBasalSetProfileNumber(injector, 0) sendMessage(msgActivate) if (danaPump.profile24) { - val msgProfile = DanaRS_Packet_Bolus_Set_24_CIR_CF_Array(injector, profile) + val msgProfile = DanaRSPacketBolusSet24CIRCFArray(injector, profile) sendMessage(msgProfile) } readPumpStatus() @@ -439,27 +439,27 @@ class DanaRSService : DaggerService() { fun loadHistory(type: Byte): PumpEnactResult { val result = PumpEnactResult(injector) if (!isConnected) return result - var msg: DanaRS_Packet_History_? = null + var msg: DanaRSPacketHistory? = null when (type) { - RecordTypes.RECORD_TYPE_ALARM -> msg = DanaRS_Packet_History_Alarm(injector) - RecordTypes.RECORD_TYPE_PRIME -> msg = DanaRS_Packet_History_Prime(injector) - RecordTypes.RECORD_TYPE_BASALHOUR -> msg = DanaRS_Packet_History_Basal(injector) - RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRS_Packet_History_Bolus(injector) - RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRS_Packet_History_Carbohydrate(injector) - RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRS_Packet_History_Daily(injector) - RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRS_Packet_History_Blood_Glucose(injector) - RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRS_Packet_History_Refill(injector) - RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRS_Packet_History_Suspend(injector) + RecordTypes.RECORD_TYPE_ALARM -> msg = DanaRSPacketHistoryAlarm(injector) + RecordTypes.RECORD_TYPE_PRIME -> msg = DanaRSPacketHistoryPrime(injector) + RecordTypes.RECORD_TYPE_BASALHOUR -> msg = DanaRSPacketHistoryBasal(injector) + RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRSPacketHistoryBolus(injector) + RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRSPacketHistoryCarbohydrate(injector) + RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRSPacketHistoryDaily(injector) + RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRSPacketHistoryBloodGlucose(injector) + RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRSPacketHistoryRefill(injector) + RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRSPacketHistorySuspend(injector) } if (msg != null) { - sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 1)) + sendMessage(DanaRSPacketGeneralSetHistoryUploadMode(injector, 1)) SystemClock.sleep(200) sendMessage(msg) while (!msg.done && isConnected) { SystemClock.sleep(100) } SystemClock.sleep(200) - sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 0)) + sendMessage(DanaRSPacketGeneralSetHistoryUploadMode(injector, 0)) } result.success = msg?.success() ?: false return result diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt b/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt index 05b06d4fca..b7a6c6a25d 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/DanaRSTestBase.kt @@ -4,7 +4,7 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danars.comm.DanaRS_Packet +import info.nightscout.androidaps.danars.comm.DanaRSPacket import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Before import org.mockito.ArgumentMatchers @@ -42,13 +42,13 @@ open class DanaRSTestBase : TestBaseWithProfile() { @Suppress("unused") fun putIntToArray(array: ByteArray, position: Int, value: Int): ByteArray { - array[DanaRS_Packet.DATA_START + position] = (value and 0xFF).toByte() - array[DanaRS_Packet.DATA_START + position + 1] = ((value and 0xFF00) shr 8).toByte() + array[DanaRSPacket.DATA_START + position] = (value and 0xFF).toByte() + array[DanaRSPacket.DATA_START + position + 1] = ((value and 0xFF00) shr 8).toByte() return array } fun putByteToArray(array: ByteArray, position: Int, value: Byte): ByteArray { - array[DanaRS_Packet.DATA_START + position] = value + array[DanaRSPacket.DATA_START + position] = value return array } diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasalTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasalTest.kt index 4932678f8b..47f894bc6d 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasalTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalSetTemporaryBasalTest.kt @@ -13,16 +13,16 @@ class DanaRSPacketBasalSetTemporaryBasalTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Temporary_Basal) { + if (it is DanaRSPacketBasalSetTemporaryBasal) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val testPacket = DanaRS_Packet_Basal_Set_Temporary_Basal(packetInjector, 50, 20) + val testPacket = DanaRSPacketBasalSetTemporaryBasal(packetInjector, 50, 20) // params - val params = testPacket.requestParams + val params = testPacket.getRequestParams() // is ratio 50 Assert.assertEquals(50.toByte(), params[0]) // is duration 20 diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarmTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarmTest.kt index 5993ed2535..953e851d3d 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarmTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketHistoryAlarmTest.kt @@ -19,11 +19,11 @@ class DanaRSPacketHistoryAlarmTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Alarm) { + if (it is DanaRSPacketHistoryAlarm) { it.rxBus = rxBus it.danaHistoryRecordDao = danaHistoryRecordDao } @@ -33,7 +33,7 @@ class DanaRSPacketHistoryAlarmTest : DanaRSTestBase() { @Test @kotlin.ExperimentalStdlibApi fun runTest() { - val packet = DanaRS_Packet_History_Alarm(packetInjector, 0) + val packet = DanaRSPacketHistoryAlarm(packetInjector, 0) val array = createArray(12, 0.toByte()) // 10 + 2 putByteToArray(array, 0, 0x0A) // record code alarm diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt index 7bbeef73b6..5d30bd101b 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryCompleteTest.kt @@ -25,7 +25,7 @@ class DanaRSPacketNotifyDeliveryCompleteTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Notify_Delivery_Complete) { + if (it is DanaRSPacketNotifyDeliveryComplete) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -38,9 +38,9 @@ class DanaRSPacketNotifyDeliveryCompleteTest : DanaRSTestBase() { `when`(resourceHelper.gs(anyInt(), anyDouble())).thenReturn("SomeString") danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) - val packet = DanaRS_Packet_Notify_Delivery_Complete(packetInjector) + val packet = DanaRSPacketNotifyDeliveryComplete(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(17, 0.toByte())) Assert.assertEquals(true, danaPump.bolusDone) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOptionTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOptionTest.kt index dfea5dee2f..101c8e8750 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOptionTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRSPacketOptionSetUserOptionTest.kt @@ -13,7 +13,7 @@ class DanaRSPacketOptionSetUserOptionTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Option_Set_User_Option) { + if (it is DanaRSPacketOptionSetUserOption) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,9 +21,9 @@ class DanaRSPacketOptionSetUserOptionTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Option_Set_User_Option(packetInjector) + val packet = DanaRSPacketOptionSetUserOption(packetInjector) // test params - val params = packet.requestParams + val params = packet.getRequestParams() Assert.assertEquals((danaPump.lcdOnTimeSec and 0xff).toByte(), params[3]) // test message decoding packet.handleMessage(createArray(3, 0.toByte())) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsMessageHashTableTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsMessageHashTableTest.kt index 46e6a328e3..d8388ad435 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsMessageHashTableTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsMessageHashTableTest.kt @@ -26,17 +26,17 @@ class DanaRsMessageHashTableTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_Bolus_Set_Step_Bolus_Start) { + if (it is DanaRSPacketBolusSetStepBolusStart) { it.constraintChecker = constraintChecker } - if (it is DanaRS_Packet_Bolus_Set_Step_Bolus_Start) { + if (it is DanaRSPacketBolusSetStepBolusStart) { it.danaPump = danaPump } - if (it is DanaRS_Packet_APS_History_Events) { + if (it is DanaRSPacketAPSHistoryEvents) { it.danaPump = danaPump } } @@ -47,8 +47,8 @@ class DanaRsMessageHashTableTest : DanaRSTestBase() { `when`(constraintChecker.applyBolusConstraints(anyObject())).thenReturn(Constraint(0.0)) val danaRSMessageHashTable = DanaRSMessageHashTable(packetInjector) - val forTesting: DanaRS_Packet = DanaRS_Packet_APS_Set_Event_History(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, 0, 0, 0) - val testPacket: DanaRS_Packet = danaRSMessageHashTable.findMessage(forTesting.command) + val forTesting: DanaRSPacket = DanaRSPacketAPSSetEventHistory(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, 0, 0, 0) + val testPacket: DanaRSPacket = danaRSMessageHashTable.findMessage(forTesting.command) Assert.assertEquals(BleEncryption.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY.toLong(), testPacket.opCode.toLong()) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsBasalSetTemporaryBasalTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsBasalSetTemporaryBasalTest.kt index d7c9afa3fd..8386456660 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsBasalSetTemporaryBasalTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsBasalSetTemporaryBasalTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketApsBasalSetTemporaryBasalTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_APS_Basal_Set_Temporary_Basal) { + if (it is DanaRSPacketAPSBasalSetTemporaryBasal) { it.aapsLogger = aapsLogger } } @@ -23,32 +23,32 @@ class DanaRsPacketApsBasalSetTemporaryBasalTest : DanaRSTestBase() { @Test fun runTest() { // under 100% should last 30 min - var packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(packetInjector, 0) + var packet = DanaRSPacketAPSBasalSetTemporaryBasal(packetInjector, 0) Assert.assertEquals(0, packet.temporaryBasalRatio) - Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM30MIN, packet.temporaryBasalDuration) + Assert.assertEquals(DanaRSPacketAPSBasalSetTemporaryBasal.PARAM30MIN, packet.temporaryBasalDuration) //constructor with param - packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(packetInjector, 10) + packet = DanaRSPacketAPSBasalSetTemporaryBasal(packetInjector, 10) Assert.assertEquals(10, packet.temporaryBasalRatio) - Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM30MIN, packet.temporaryBasalDuration) + Assert.assertEquals(DanaRSPacketAPSBasalSetTemporaryBasal.PARAM30MIN, packet.temporaryBasalDuration) // over 100% should last 15 min - packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(packetInjector, 150) + packet = DanaRSPacketAPSBasalSetTemporaryBasal(packetInjector, 150) Assert.assertEquals(150, packet.temporaryBasalRatio) - Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM15MIN, packet.temporaryBasalDuration) + Assert.assertEquals(DanaRSPacketAPSBasalSetTemporaryBasal.PARAM15MIN, packet.temporaryBasalDuration) // test low hard limit - packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(packetInjector, -1) + packet = DanaRSPacketAPSBasalSetTemporaryBasal(packetInjector, -1) Assert.assertEquals(0, packet.temporaryBasalRatio) - Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM30MIN, packet.temporaryBasalDuration) + Assert.assertEquals(DanaRSPacketAPSBasalSetTemporaryBasal.PARAM30MIN, packet.temporaryBasalDuration) // test high hard limit - packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(packetInjector, 550) + packet = DanaRSPacketAPSBasalSetTemporaryBasal(packetInjector, 550) Assert.assertEquals(500, packet.temporaryBasalRatio) - Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM15MIN, packet.temporaryBasalDuration) + Assert.assertEquals(DanaRSPacketAPSBasalSetTemporaryBasal.PARAM15MIN, packet.temporaryBasalDuration) // test message generation - packet = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(packetInjector, 260) - val generatedCode = packet.requestParams + packet = DanaRSPacketAPSBasalSetTemporaryBasal(packetInjector, 260) + val generatedCode = packet.getRequestParams() Assert.assertEquals(3, generatedCode.size.toLong()) Assert.assertEquals(4.toByte(), generatedCode[0]) Assert.assertEquals(1.toByte(), generatedCode[1]) - Assert.assertEquals(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.PARAM15MIN.toUByte(), generatedCode[2].toUByte()) + Assert.assertEquals(DanaRSPacketAPSBasalSetTemporaryBasal.PARAM15MIN.toUByte(), generatedCode[2].toUByte()) // test message decoding packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt index 093adb3fe3..2a473adec7 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsHistoryEventsTest.kt @@ -30,11 +30,11 @@ class DanaRsPacketApsHistoryEventsTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_APS_History_Events) { + if (it is DanaRSPacketAPSHistoryEvents) { it.rxBus = rxBus it.resourceHelper = resourceHelper it.pumpSync = pumpSync @@ -49,9 +49,9 @@ class DanaRsPacketApsHistoryEventsTest : DanaRSTestBase() { @Test fun runTest() { val now = dateUtil.now() - val testPacket = DanaRS_Packet_APS_History_Events(packetInjector, now) + val testPacket = DanaRSPacketAPSHistoryEvents(packetInjector, now) // test getRequestedParams - val returnedValues = testPacket.requestParams + val returnedValues = testPacket.getRequestParams() val expectedValues = getCalender(now) //year Assert.assertEquals(expectedValues[0], returnedValues[0]) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt index 07809e9dc5..9c686a0cc6 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketApsSetEventHistoryTest.kt @@ -13,11 +13,11 @@ class DanaRsPacketApsSetEventHistoryTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_APS_Set_Event_History) { + if (it is DanaRSPacketAPSSetEventHistory) { it.danaPump = danaPump } } @@ -25,20 +25,20 @@ class DanaRsPacketApsSetEventHistoryTest : DanaRSTestBase() { @Test fun runTest() { // test for negative carbs val now = dateUtil.now() - var historyTest = DanaRS_Packet_APS_Set_Event_History(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, -1, 0) - var testParams = historyTest.requestParams + var historyTest = DanaRSPacketAPSSetEventHistory(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, -1, 0) + var testParams = historyTest.getRequestParams() Assert.assertEquals(0.toByte(), testParams[8]) // 5g carbs - historyTest = DanaRS_Packet_APS_Set_Event_History(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, 5, 0) - testParams = historyTest.requestParams + historyTest = DanaRSPacketAPSSetEventHistory(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, 5, 0) + testParams = historyTest.getRequestParams() Assert.assertEquals(5.toByte(), testParams[8]) // 150g carbs - historyTest = DanaRS_Packet_APS_Set_Event_History(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, 150, 0) - testParams = historyTest.requestParams + historyTest = DanaRSPacketAPSSetEventHistory(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, 150, 0) + testParams = historyTest.getRequestParams() Assert.assertEquals(150.toByte(), testParams[8]) // test message generation - historyTest = DanaRS_Packet_APS_Set_Event_History(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, 5, 0) - testParams = historyTest.requestParams + historyTest = DanaRSPacketAPSSetEventHistory(packetInjector, info.nightscout.androidaps.dana.DanaPump.CARBS, now, 5, 0) + testParams = historyTest.getRequestParams() Assert.assertEquals(5.toByte(), testParams[8]) Assert.assertEquals(11, testParams.size) Assert.assertEquals(info.nightscout.androidaps.dana.DanaPump.CARBS.toByte(), testParams[0]) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt index 938e716ba7..8e8df0b82c 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetBasalRateTest.kt @@ -16,7 +16,7 @@ class DanaRsPacketBasalGetBasalRateTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Get_Basal_Rate) { + if (it is DanaRSPacketBasalGetBasalRate) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -26,7 +26,7 @@ class DanaRsPacketBasalGetBasalRateTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Get_Basal_Rate(packetInjector) + val packet = DanaRSPacketBasalGetBasalRate(packetInjector) // test message decoding // rate is 0.01 val array = ByteArray(100) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileBasalRateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileBasalRateTest.kt deleted file mode 100644 index c1cfd49dcd..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileBasalRateTest.kt +++ /dev/null @@ -1,45 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert.assertEquals -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBasalGetProfileBasalRateTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Basal_Get_Profile_Basal_Rate) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val testPacket = DanaRS_Packet_Basal_Get_Profile_Basal_Rate(packetInjector, 1) - // test if pumpProfile array is set right - val basal01 = DanaRS_Packet.byteArrayToInt(DanaRS_Packet(packetInjector).getBytes(createArray(50, 1.toByte()), 2, 2)) / 100.0 - val basal05 = DanaRS_Packet.byteArrayToInt(DanaRS_Packet(packetInjector).getBytes(createArray(50, 5.toByte()), 2, 2)) / 100.0 - val basal12 = DanaRS_Packet.byteArrayToInt(DanaRS_Packet(packetInjector).getBytes(createArray(50, 12.toByte()), 2, 2)) / 100.0 - // basal rate > 1U/hr - val basal120 = DanaRS_Packet.byteArrayToInt(DanaRS_Packet(packetInjector).getBytes(createArray(50, 120.toByte()), 2, 2)) / 100.0 - val params = testPacket.requestParams - assertEquals(1.toByte(), params[0]) - testPacket.handleMessage(createArray(50, 0.toByte())) - assertEquals(0.0, danaPump.pumpProfiles!![1][1], 0.0) - testPacket.handleMessage(createArray(50, 1.toByte())) - assertEquals(basal01, danaPump.pumpProfiles!![1][2], 0.0) - testPacket.handleMessage(createArray(50, 5.toByte())) - assertEquals(basal05, danaPump.pumpProfiles!![1][1], 0.0) - testPacket.handleMessage(createArray(50, 12.toByte())) - assertEquals(basal12, danaPump.pumpProfiles!![1][1], 0.0) - testPacket.handleMessage(createArray(50, 120.toByte())) - assertEquals(basal120, danaPump.pumpProfiles!![1][1], 0.0) - assertEquals("BASAL__GET_PROFILE_BASAL_RATE", testPacket.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileNumberTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileNumberTest.kt index 9847d2f75c..0b2d34b2bc 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileNumberTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetProfileNumberTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketBasalGetProfileNumberTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Get_Profile_Number) { + if (it is DanaRSPacketBasalGetProfileNumber) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,7 +21,7 @@ class DanaRsPacketBasalGetProfileNumberTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Get_Profile_Number(packetInjector) + val packet = DanaRSPacketBasalGetProfileNumber(packetInjector) val array = ByteArray(100) putByteToArray(array, 0, 1.toByte()) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetTemporaryBasalStateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetTemporaryBasalStateTest.kt deleted file mode 100644 index e29ed61b41..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalGetTemporaryBasalStateTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBasalGetTemporaryBasalStateTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet) { - it.aapsLogger = aapsLogger - it.dateUtil = dateUtil - } - if (it is DanaRS_Packet_Basal_Get_Temporary_Basal_State) { - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Get_Temporary_Basal_State(packetInjector) - // test message decoding - val array = ByteArray(100) - putByteToArray(array, 0, 1.toByte()) - putByteToArray(array, 1, 1.toByte()) - putByteToArray(array, 2, 230.toByte()) - putByteToArray(array, 3, 150.toByte()) - putIntToArray(array, 4, 1) - packet.handleMessage(array) - Assert.assertTrue(packet.failed) - Assert.assertTrue(packet.isTempBasalInProgress) - Assert.assertEquals(300, packet.tempBasalPercent) - Assert.assertEquals(15 * 60, packet.tempBasalTotalSec) - Assert.assertEquals("BASAL__TEMPORARY_BASAL_STATE", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetBasalRateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetBasalRateTest.kt deleted file mode 100644 index 765b2f462a..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetBasalRateTest.kt +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBasalSetBasalRateTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Basal_Rate) { - it.aapsLogger = aapsLogger - } - } - } - - @Test fun runTest() { - // test message decoding - val packet = DanaRS_Packet_Basal_Set_Basal_Rate(packetInjector, createArray(24, 5.0)) - val requested = packet.requestParams - var lookingFor = (5 * 100 and 0xff).toByte() - Assert.assertEquals(lookingFor, requested[24]) - lookingFor = (500 ushr 8 and 0xff).toByte() - Assert.assertEquals(lookingFor, requested[25]) - packet.handleMessage(createArray(3, 0.toByte())) - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(3, 1.toByte())) - Assert.assertEquals(true, packet.failed) - Assert.assertEquals("BASAL__SET_BASAL_RATE", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetCancelTemporaryBasalTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetCancelTemporaryBasalTest.kt index 442fed73cf..1f62adaf8a 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetCancelTemporaryBasalTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetCancelTemporaryBasalTest.kt @@ -13,14 +13,14 @@ class DanaRsPacketBasalSetCancelTemporaryBasalTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal) { + if (it is DanaRSPacketBasalSetCancelTemporaryBasal) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(packetInjector) + val packet = DanaRSPacketBasalSetCancelTemporaryBasal(packetInjector) // test message decoding packet.handleMessage(createArray(3, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileBasalRateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileBasalRateTest.kt index 8c45544aa1..a0d67b3212 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileBasalRateTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileBasalRateTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketBasalSetProfileBasalRateTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Profile_Basal_Rate) { + if (it is DanaRSPacketBasalSetProfileBasalRate) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Set_Profile_Basal_Rate(packetInjector, 1, createArray(24, 1.0)) + val packet = DanaRSPacketBasalSetProfileBasalRate(packetInjector, 1, createArray(24, 1.0)) // test params - val testParams = packet.requestParams + val testParams = packet.getRequestParams() // is profile 1 Assert.assertEquals(1.toByte(), testParams[0]) // is value 100 diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileNumberTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileNumberTest.kt index d7f1135fb7..45137998b8 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileNumberTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetProfileNumberTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketBasalSetProfileNumberTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Profile_Number) { + if (it is DanaRSPacketBasalSetProfileNumber) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Set_Profile_Number(packetInjector, 1) + val packet = DanaRSPacketBasalSetProfileNumber(packetInjector, 1) // test params - val testParams = packet.requestParams + val testParams = packet.getRequestParams() // is profile 1 Assert.assertEquals(1.toByte(), testParams[0]) // test message decoding diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOffTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOffTest.kt index 2ebd63d093..4e956beabf 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOffTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOffTest.kt @@ -13,14 +13,14 @@ class DanaRsPacketBasalSetSuspendOffTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Suspend_Off) { + if (it is DanaRSPacketBasalSetSuspendOff) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Set_Suspend_Off(packetInjector) + val packet = DanaRSPacketBasalSetSuspendOff(packetInjector) // test message decoding packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOnTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOnTest.kt index 7b31bbbd85..af501c62d1 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOnTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBasalSetSuspendOnTest.kt @@ -13,14 +13,14 @@ class DanaRsPacketBasalSetSuspendOnTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Basal_Set_Suspend_On) { + if (it is DanaRSPacketBasalSetSuspendOn) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Basal_Set_Suspend_On(packetInjector) + val packet = DanaRSPacketBasalSetSuspendOn(packetInjector) // test message decoding packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt index a28bfaa32e..369ab8fb3f 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetBolusOptionTest.kt @@ -5,11 +5,8 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.danars.DanaRSTestBase import org.junit.Assert -import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.ArgumentMatchers.anyInt -import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @@ -19,7 +16,7 @@ class DanaRsPacketBolusGetBolusOptionTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Bolus_Option) { + if (it is DanaRSPacketBolusGetBolusOption) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -29,7 +26,7 @@ class DanaRsPacketBolusGetBolusOptionTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Bolus_Option(packetInjector) + val packet = DanaRSPacketBolusGetBolusOption(packetInjector) // test message decoding //if dataArray is 1 pump.isExtendedBolusEnabled should be true packet.handleMessage(createArray(21, 1.toByte())) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCalculationInformationTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCalculationInformationTest.kt index a8b887ba45..ce75f1f60d 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCalculationInformationTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCalculationInformationTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketBolusGetCalculationInformationTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Calculation_Information) { + if (it is DanaRSPacketBolusGetCalculationInformation) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,8 +21,8 @@ class DanaRsPacketBolusGetCalculationInformationTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Calculation_Information(packetInjector) - Assert.assertEquals(null, packet.requestParams) + val packet = DanaRSPacketBolusGetCalculationInformation(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(24, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCarbohydrateCalculationInformationTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCarbohydrateCalculationInformationTest.kt deleted file mode 100644 index 9a5627c42c..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCarbohydrateCalculationInformationTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusGetCarbohydrateCalculationInformationTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(packetInjector) - Assert.assertEquals(null, packet.requestParams) - // test message decoding - packet.handleMessage(createArray(24, 0.toByte())) - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(24, 1.toByte())) - Assert.assertEquals(true, packet.failed) - Assert.assertEquals("BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCirCfArrayTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCirCfArrayTest.kt index b56e1a5426..49ef077121 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCirCfArrayTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetCirCfArrayTest.kt @@ -14,7 +14,7 @@ class DanaRsPacketBolusGetCirCfArrayTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_CIR_CF_Array) { + if (it is DanaRSPacketBolusGetCIRCFArray) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -22,9 +22,9 @@ class DanaRsPacketBolusGetCirCfArrayTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_CIR_CF_Array(packetInjector) + val packet = DanaRSPacketBolusGetCIRCFArray(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(34, 0.toByte())) // are pump units MG/DL ??? diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetDualBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetDualBolusTest.kt deleted file mode 100644 index 9de5e53cb8..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetDualBolusTest.kt +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusGetDualBolusTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Dual_Bolus) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Dual_Bolus(packetInjector) - // test params - Assert.assertEquals(null, packet.requestParams) - - val array = ByteArray(20) - putByteToArray(array, 0, 1) - putIntToArray(array, 1, (1.0 * 100).toInt()) - putIntToArray(array, 3, (0.55 * 100).toInt()) - putIntToArray(array, 5, (40.0 * 100).toInt()) - packet.handleMessage(array) - Assert.assertTrue(packet.failed) - Assert.assertEquals(1.0, danaPump.bolusStep, 0.0) - Assert.assertEquals(40.0, danaPump.maxBolus, 0.0) - - Assert.assertEquals("BOLUS__GET_DUAL_BOLUS", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusStateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusStateTest.kt deleted file mode 100644 index 759b35e527..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusStateTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusGetExtendedBolusStateTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Extended_Bolus_State) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Extended_Bolus_State(packetInjector) - // test params - Assert.assertEquals(null, packet.requestParams) - // test message decoding - var testValue = 0.0 - packet.handleMessage(createArray(11, testValue.toInt().toByte())) - Assert.assertEquals(testValue != 0.0, packet.failed) - testValue = 1.0 - packet.handleMessage(createArray(11, testValue.toInt().toByte())) - // is extended bolus in progress - Assert.assertEquals(testValue == 1.0, packet.isExtendedInProgress) - Assert.assertEquals(testValue != 0.0, packet.failed) - Assert.assertEquals("BOLUS__GET_EXTENDED_BOLUS_STATE", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusTest.kt deleted file mode 100644 index 4da5e4ea6c..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedBolusTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusGetExtendedBolusTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Extended_Bolus) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Extended_Bolus(packetInjector) - // test params - Assert.assertEquals(null, packet.requestParams) - // test message decoding - var testValue = 0.0 - packet.handleMessage(createArray(10, testValue.toInt().toByte())) - Assert.assertEquals(testValue != 0.0, packet.failed) - testValue = 1.0 - packet.handleMessage(createArray(10, testValue.toInt().toByte())) - // is pump.bolusStep set to 1 - Assert.assertEquals(testValue / 100.0, danaPump.bolusStep, 0.0) - Assert.assertEquals(testValue != 0.0, packet.failed) - Assert.assertEquals("BOLUS__GET_EXTENDED_BOLUS", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedMenuOptionStateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedMenuOptionStateTest.kt deleted file mode 100644 index 50921c5ea5..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetExtendedMenuOptionStateTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusGetExtendedMenuOptionStateTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(packetInjector) - Assert.assertEquals(null, packet.requestParams) - // test message decoding - packet.handleMessage(createArray(34, 0.toByte())) - // isExtendedInProgress should be false - Assert.assertEquals(false, packet.isExtendedInProgress) - // assertEquals(false, packet.failed); - packet.handleMessage(createArray(34, 1.toByte())) - Assert.assertEquals(true, packet.isExtendedInProgress) - Assert.assertEquals("BOLUS__GET_EXTENDED_MENU_OPTION_STATE", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetInitialBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetInitialBolusTest.kt deleted file mode 100644 index 883205431c..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetInitialBolusTest.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusGetInitialBolusTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Get_Initial_Bolus) { - it.aapsLogger = aapsLogger - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Initial_Bolus(packetInjector) - Assert.assertEquals(null, packet.requestParams) - // test message decoding - packet.handleMessage(createArray(34, 0.toByte())) - // should fail only if all the initial boluses are 0 - Assert.assertEquals(false, !packet.failed) - packet.handleMessage(createArray(34, 1.toByte())) - Assert.assertEquals(true, !packet.failed) - Assert.assertEquals("BOLUS__GET_BOLUS_RATE", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetStepBolusInformationTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetStepBolusInformationTest.kt index b1e4721db8..3af2adbc60 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetStepBolusInformationTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusGetStepBolusInformationTest.kt @@ -14,18 +14,18 @@ class DanaRsPacketBolusGetStepBolusInformationTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_Bolus_Get_Step_Bolus_Information) { + if (it is DanaRSPacketBolusGetStepBolusInformation) { it.danaPump = danaPump } } } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Get_Step_Bolus_Information(packetInjector) + val packet = DanaRSPacketBolusGetStepBolusInformation(packetInjector) val array = createArray(13, 0.toByte()) // 11 + 2 putByteToArray(array, 0, 2) // error 2 diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetBolusOptionTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetBolusOptionTest.kt index 450e0d17f8..1086d4eba2 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetBolusOptionTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetBolusOptionTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketBolusSetBolusOptionTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Bolus_Option) { + if (it is DanaRSPacketBolusSetBolusOption) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_Bolus_Option(packetInjector, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + val packet = DanaRSPacketBolusSetBolusOption(packetInjector, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) // test params - val testParams = packet.requestParams + val testParams = packet.getRequestParams() Assert.assertEquals(0.toByte(), testParams[0]) Assert.assertEquals(0.toByte(), testParams[18]) // test message decoding diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetCirCfArrayTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetCirCfArrayTest.kt deleted file mode 100644 index 2987a11fb0..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetCirCfArrayTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusSetCirCfArrayTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_CIR_CF_Array) { - it.aapsLogger = aapsLogger - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_CIR_CF_Array(packetInjector, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - // test params - val testParams = packet.requestParams - Assert.assertEquals(0.toByte(), testParams[0]) - Assert.assertEquals(0.toByte(), testParams[18]) - // test message decoding - packet.handleMessage(createArray(34, 0.toByte())) - // DanaRPump testPump = DanaRPump.getInstance(); - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(34, 1.toByte())) - // int valueRequested = (((byte) 1 & 0x000000FF) << 8) + (((byte) 1) & 0x000000FF); -// assertEquals(valueRequested /100d, testPump.lastBolusAmount, 0); - Assert.assertEquals(true, packet.failed) - Assert.assertEquals("BOLUS__SET_CIR_CF_ARRAY", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetDualBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetDualBolusTest.kt deleted file mode 100644 index bd15873509..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetDualBolusTest.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusSetDualBolusTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Dual_Bolus) { - it.aapsLogger = aapsLogger - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_Dual_Bolus(packetInjector, 0.0, 0.0, 1) - // test params - val testParams = packet.requestParams - Assert.assertEquals(0.toByte(), testParams[0]) - Assert.assertEquals(1.toByte(), testParams[4]) - // test message decoding - packet.handleMessage(createArray(34, 0.toByte())) - // DanaRPump testPump = DanaRPump.getInstance(); - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(34, 1.toByte())) - // int valueRequested = (((byte) 1 & 0x000000FF) << 8) + (((byte) 1) & 0x000000FF); -// assertEquals(valueRequested /100d, testPump.lastBolusAmount, 0); - Assert.assertEquals(true, packet.failed) - Assert.assertEquals("BOLUS__SET_DUAL_BOLUS", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusCancelTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusCancelTest.kt index 02893dc262..67832e9ef1 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusCancelTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusCancelTest.kt @@ -13,15 +13,15 @@ class DanaRsPacketBolusSetExtendedBolusCancelTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel) { + if (it is DanaRSPacketBolusSetExtendedBolusCancel) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(packetInjector) - Assert.assertEquals(null, packet.requestParams) + val packet = DanaRSPacketBolusSetExtendedBolusCancel(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(34, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusTest.kt index 055bbf3582..2bb83c2395 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetExtendedBolusTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketBolusSetExtendedBolusTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Extended_Bolus) { + if (it is DanaRSPacketBolusSetExtendedBolus) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_Extended_Bolus(packetInjector, 1.0, 1) + val packet = DanaRSPacketBolusSetExtendedBolus(packetInjector, 1.0, 1) // test params - val testparams = packet.requestParams + val testparams = packet.getRequestParams() Assert.assertEquals(100.toByte(), testparams[0]) Assert.assertEquals(1.toByte(), testparams[2]) // test message decoding diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetInitialBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetInitialBolusTest.kt deleted file mode 100644 index f3510221ff..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetInitialBolusTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketBolusSetInitialBolusTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Initial_Bolus) { - it.aapsLogger = aapsLogger - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_Initial_Bolus(packetInjector, 0, 0, 0, 100) - // test params - val testParams = packet.requestParams - Assert.assertEquals(0.toByte(), testParams[0]) - Assert.assertEquals(100.toByte(), testParams[6]) - // test message decoding - packet.handleMessage(createArray(34, 0.toByte())) - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(34, 1.toByte())) - Assert.assertEquals(true, packet.failed) - Assert.assertEquals("BOLUS__SET_BOLUS_RATE", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt index 224dd6fee2..a8d70ec52f 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStartTest.kt @@ -35,7 +35,7 @@ class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Step_Bolus_Start) { + if (it is DanaRSPacketBolusSetStepBolusStart) { it.aapsLogger = aapsLogger it.danaPump = danaPump it.constraintChecker = constraintChecker @@ -44,9 +44,9 @@ class DanaRsPacketBolusSetStepBolusStartTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Bolus_Set_Step_Bolus_Start(packetInjector) + val packet = DanaRSPacketBolusSetStepBolusStart(packetInjector) // test params - val testParams = packet.requestParams + val testParams = packet.getRequestParams() Assert.assertEquals(0.toByte(), testParams[0]) Assert.assertEquals(0.toByte(), testParams[2]) // test message decoding diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt index 840f9c6b42..cb5f396ecd 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketBolusSetStepBolusStopTest.kt @@ -24,7 +24,7 @@ class DanaRsPacketBolusSetStepBolusStopTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Bolus_Set_Step_Bolus_Stop) { + if (it is DanaRSPacketBolusSetStepBolusStop) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -37,7 +37,7 @@ class DanaRsPacketBolusSetStepBolusStopTest : DanaRSTestBase() { `when`(resourceHelper.gs(Mockito.anyInt())).thenReturn("SomeString") danaPump.bolusingTreatment = EventOverviewBolusProgress.Treatment(0.0, 0, true) - val testPacket = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(packetInjector) + val testPacket = DanaRSPacketBolusSetStepBolusStop(packetInjector) // test message decoding testPacket.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, testPacket.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcKeepConnectionTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcKeepConnectionTest.kt index ecc02cc85b..d4f49b7392 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcKeepConnectionTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcKeepConnectionTest.kt @@ -13,15 +13,15 @@ class DanaRsPacketEtcKeepConnectionTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Etc_Keep_Connection) { + if (it is DanaRSPacketEtcKeepConnection) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Etc_Keep_Connection(packetInjector) - Assert.assertEquals(null, packet.requestParams) + val packet = DanaRSPacketEtcKeepConnection(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(byteArrayOf(0.toByte(), 0.toByte(), 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcSetHistorySaveTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcSetHistorySaveTest.kt index a239281ad3..509f484180 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcSetHistorySaveTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketEtcSetHistorySaveTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketEtcSetHistorySaveTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Etc_Set_History_Save) { + if (it is DanaRSPacketEtcSetHistorySave) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Etc_Set_History_Save(packetInjector, 0, 0, 0, 0, 0, 0, 0, 0, 2) + val packet = DanaRSPacketEtcSetHistorySave(packetInjector, 0, 0, 0, 0, 0, 0, 0, 0, 2) // test params - val testParams = packet.requestParams + val testParams = packet.getRequestParams() Assert.assertEquals(2.toByte(), testParams[8]) Assert.assertEquals((2 ushr 8).toByte(), testParams[9]) // test message decoding diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralDeliveryStatusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralDeliveryStatusTest.kt deleted file mode 100644 index c1a758daee..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralDeliveryStatusTest.kt +++ /dev/null @@ -1,32 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketGeneralDeliveryStatusTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_General_Delivery_Status) { - it.aapsLogger = aapsLogger - } - } - } - - @Test fun runTest() { - val packet = DanaRS_Packet_General_Delivery_Status(packetInjector) - Assert.assertEquals(null, packet.requestParams) - // test message decoding - packet.handleMessage(createArray(15, 0.toByte())) - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(15, 161.toByte())) - Assert.assertEquals(true, packet.failed) - Assert.assertEquals("REVIEW__DELIVERY_STATUS", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetMoreInformationTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetMoreInformationTest.kt deleted file mode 100644 index 957553475f..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetMoreInformationTest.kt +++ /dev/null @@ -1,55 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner -import java.util.* - -@RunWith(PowerMockRunner::class) -class DanaRsPacketGeneralGetMoreInformationTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet) { - it.aapsLogger = aapsLogger - it.dateUtil = dateUtil - } - if (it is DanaRS_Packet_General_Get_More_Information) { - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - var packet = DanaRS_Packet_General_Get_More_Information(packetInjector) - - packet.handleMessage(createArray(14, 0.toByte())) - Assert.assertTrue(packet.failed) - - packet = DanaRS_Packet_General_Get_More_Information(packetInjector) - val array = createArray(15, 0.toByte()) // 13 + 2 - putIntToArray(array, 0, 600) // iob 6 - putIntToArray(array, 2, 1250) // daily units 12.5 - putByteToArray(array, 4, 1) // is extended in progress - putIntToArray(array, 5, 150) // extended remaining minutes 150 - putByteToArray(array, 9, 15) // hours 15 - putByteToArray(array, 10, 25) // minutes 25 - putIntToArray(array, 11, 170) // last bolus amount 1.70 - - packet.handleMessage(array) - Assert.assertFalse(packet.failed) - Assert.assertEquals(6.0, danaPump.iob, 0.01) - Assert.assertEquals(12.5, danaPump.dailyTotalUnits, 0.01) - val lastBolus = Calendar.getInstance() - lastBolus.timeInMillis = danaPump.lastBolusTime - Assert.assertEquals(15, lastBolus.get(Calendar.HOUR_OF_DAY)) - Assert.assertEquals(25, lastBolus.get(Calendar.MINUTE)) - Assert.assertEquals(1.7, danaPump.lastBolusAmount, 0.01) - - Assert.assertEquals("REVIEW__GET_MORE_INFORMATION", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPasswordTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPasswordTest.kt deleted file mode 100644 index 9fe3e2a8ec..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPasswordTest.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketGeneralGetPasswordTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_General_Get_Password) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - var packet = DanaRS_Packet_General_Get_Password(packetInjector) - Assert.assertEquals(null, packet.requestParams) - // test message decoding - // test for the length message - packet.handleMessage(createArray(1, 0.toByte())) - Assert.assertEquals(true, packet.failed) - packet = DanaRS_Packet_General_Get_Password(packetInjector) - packet.handleMessage(createArray(15, 0.toByte())) - Assert.assertEquals(false, packet.failed) - Assert.assertEquals("REVIEW__GET_PASSWORD", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt index b3c7b5df8f..40a0d0bad4 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetPumpCheckTest.kt @@ -16,7 +16,7 @@ class DanaRsPacketGeneralGetPumpCheckTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_General_Get_Pump_Check) { + if (it is DanaRSPacketGeneralGetPumpCheck) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -26,13 +26,13 @@ class DanaRsPacketGeneralGetPumpCheckTest : DanaRSTestBase() { } @Test fun runTest() { - var packet = DanaRS_Packet_General_Get_Pump_Check(packetInjector) - Assert.assertEquals(null, packet.requestParams) + var packet = DanaRSPacketGeneralGetPumpCheck(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding // test for the length message packet.handleMessage(createArray(1, 0.toByte())) Assert.assertEquals(true, packet.failed) - packet = DanaRS_Packet_General_Get_Pump_Check(packetInjector) + packet = DanaRSPacketGeneralGetPumpCheck(packetInjector) packet.handleMessage(createArray(15, 0.toByte())) Assert.assertEquals(false, packet.failed) Assert.assertEquals("REVIEW__GET_PUMP_CHECK", packet.friendlyName) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingInformationTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingInformationTest.kt index 07201595db..299fa6c8fb 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingInformationTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingInformationTest.kt @@ -13,25 +13,25 @@ class DanaRsPacketGeneralGetShippingInformationTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_General_Get_Shipping_Information) { + if (it is DanaRSPacketGeneralGetShippingInformation) { it.danaPump = danaPump } } } @Test fun runTest() { - var packet = DanaRS_Packet_General_Get_Shipping_Information(packetInjector) - Assert.assertEquals(null, packet.requestParams) + var packet = DanaRSPacketGeneralGetShippingInformation(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding // test for the length message packet.handleMessage(createArray(1, 0.toByte())) Assert.assertEquals(true, packet.failed) // everything ok :) - packet = DanaRS_Packet_General_Get_Shipping_Information(packetInjector) + packet = DanaRSPacketGeneralGetShippingInformation(packetInjector) Assert.assertEquals("REVIEW__GET_SHIPPING_INFORMATION", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingVerisonTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingVerisonTest.kt index 3a63508855..f09dbaa108 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingVerisonTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetShippingVerisonTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketGeneralGetShippingVerisonTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_General_Get_Shipping_Version) { + if (it is DanaRSPacketGeneralGetShippingVersion) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,7 +21,7 @@ class DanaRsPacketGeneralGetShippingVerisonTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_General_Get_Shipping_Version(packetInjector) + val packet = DanaRSPacketGeneralGetShippingVersion(packetInjector) // test message decoding val ver = byteArrayOf((-78).toByte(), (-127).toByte(), (66).toByte(), (80).toByte(), (78).toByte(), (45).toByte(), (51).toByte(), (46).toByte(), (48).toByte(), (46).toByte(), (48).toByte()) packet.handleMessage(ver) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetTodayDeliveryTotalTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetTodayDeliveryTotalTest.kt deleted file mode 100644 index 4497e3dc90..0000000000 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetTodayDeliveryTotalTest.kt +++ /dev/null @@ -1,37 +0,0 @@ -package info.nightscout.androidaps.danars.comm - -import dagger.android.AndroidInjector -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.danars.DanaRSTestBase -import org.junit.Assert -import org.junit.Test -import org.junit.runner.RunWith -import org.powermock.modules.junit4.PowerMockRunner - -@RunWith(PowerMockRunner::class) -class DanaRsPacketGeneralGetTodayDeliveryTotalTest : DanaRSTestBase() { - - private val packetInjector = HasAndroidInjector { - AndroidInjector { - if (it is DanaRS_Packet_General_Get_Today_Delivery_Total) { - it.aapsLogger = aapsLogger - it.danaPump = danaPump - } - } - } - - @Test fun runTest() { - var packet = DanaRS_Packet_General_Get_Today_Delivery_Total(packetInjector) - Assert.assertEquals(null, packet.requestParams) - // test message decoding - // test for the length message - packet.handleMessage(createArray(1, 0.toByte())) - Assert.assertEquals(true, packet.failed) - packet = DanaRS_Packet_General_Get_Today_Delivery_Total(packetInjector) - packet.handleMessage(createArray(18, 0.toByte())) - Assert.assertEquals(false, packet.failed) - packet.handleMessage(createArray(15, 1.toByte())) - Assert.assertEquals(((1 and 0x000000FF shl 8) + (1 and 0x000000FF)) / 100.0, danaPump.dailyTotalUnits, 0.0) - Assert.assertEquals("REVIEW__GET_TODAY_DELIVERY_TOTAL", packet.friendlyName) - } -} \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetUserTimeChangeFlagTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetUserTimeChangeFlagTest.kt index 0f901ca6e8..09c68d6a6e 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetUserTimeChangeFlagTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralGetUserTimeChangeFlagTest.kt @@ -13,20 +13,20 @@ class DanaRsPacketGeneralGetUserTimeChangeFlagTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_General_Get_User_Time_Change_Flag) { + if (it is DanaRSPacketGeneralGetUserTimeChangeFlag) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - var packet = DanaRS_Packet_General_Get_User_Time_Change_Flag(packetInjector) - Assert.assertEquals(null, packet.requestParams) + var packet = DanaRSPacketGeneralGetUserTimeChangeFlag(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding // test for the length message packet.handleMessage(createArray(1, 0.toByte())) Assert.assertEquals(true, packet.failed) - packet = DanaRS_Packet_General_Get_User_Time_Change_Flag(packetInjector) + packet = DanaRSPacketGeneralGetUserTimeChangeFlag(packetInjector) packet.handleMessage(createArray(18, 0.toByte())) Assert.assertEquals(false, packet.failed) Assert.assertEquals("REVIEW__GET_USER_TIME_CHANGE_FLAG", packet.friendlyName) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralInitialScreenInformationTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralInitialScreenInformationTest.kt index a67535ea5e..14d6efad46 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralInitialScreenInformationTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralInitialScreenInformationTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketGeneralInitialScreenInformationTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_General_Initial_Screen_Information) { + if (it is DanaRSPacketGeneralInitialScreenInformation) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,13 +21,13 @@ class DanaRsPacketGeneralInitialScreenInformationTest : DanaRSTestBase() { } @Test fun runTest() { - var packet = DanaRS_Packet_General_Initial_Screen_Information(packetInjector) - Assert.assertEquals(null, packet.requestParams) + var packet = DanaRSPacketGeneralInitialScreenInformation(packetInjector) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding // test for the length message packet.handleMessage(createArray(1, 0.toByte())) Assert.assertEquals(true, packet.failed) - packet = DanaRS_Packet_General_Initial_Screen_Information(packetInjector) + packet = DanaRSPacketGeneralInitialScreenInformation(packetInjector) packet.handleMessage(createArray(17, 1.toByte())) Assert.assertEquals(false, packet.failed) Assert.assertEquals(true, danaPump.pumpSuspended) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetHistoryUploadModeTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetHistoryUploadModeTest.kt index 4a2061bce1..c179f63c0d 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetHistoryUploadModeTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetHistoryUploadModeTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketGeneralSetHistoryUploadModeTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_General_Set_History_Upload_Mode) { + if (it is DanaRSPacketGeneralSetHistoryUploadMode) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_General_Set_History_Upload_Mode(packetInjector, 1) + val packet = DanaRSPacketGeneralSetHistoryUploadMode(packetInjector, 1) // test params - Assert.assertEquals(1.toByte(), packet.requestParams[0]) + Assert.assertEquals(1.toByte(), packet.getRequestParams()[0]) // test message decoding packet.handleMessage(createArray(3, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetUserTimeChangeFlagClearTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetUserTimeChangeFlagClearTest.kt index 2e6e170be5..d29722bf71 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetUserTimeChangeFlagClearTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketGeneralSetUserTimeChangeFlagClearTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketGeneralSetUserTimeChangeFlagClearTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear) { + if (it is DanaRSPacketGeneralSetUserTimeChangeFlagClear) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(packetInjector) + val packet = DanaRSPacketGeneralSetUserTimeChangeFlagClear(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(3, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryAllHistoryTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryAllHistoryTest.kt index 8135997298..62e2f42646 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryAllHistoryTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryAllHistoryTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryAllHistoryTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_All_History) { + if (it is DanaRSPacketHistoryAllHistory) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_All_History(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryAllHistory(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__ALL_HISTORY", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBasalTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBasalTest.kt index 1d0f7f978d..bfda87308b 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBasalTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBasalTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryBasalTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Basal) { + if (it is DanaRSPacketHistoryBasal) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Basal(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryBasal(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__BASAL", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBloodGlucoseTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBloodGlucoseTest.kt index 683298ff8b..88245a085a 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBloodGlucoseTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBloodGlucoseTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryBloodGlucoseTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Blood_Glucose) { + if (it is DanaRSPacketHistoryBloodGlucose) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Blood_Glucose(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryBloodGlucose(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__BLOOD_GLUCOSE", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBolusTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBolusTest.kt index 94b8f19777..aa642a645e 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBolusTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryBolusTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryBolusTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Bolus) { + if (it is DanaRSPacketHistoryBolus) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Bolus(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryBolus(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__BOLUS", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryCarbohydrateTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryCarbohydrateTest.kt index cfa447fa89..cb77a3078b 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryCarbohydrateTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryCarbohydrateTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryCarbohydrateTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Carbohydrate) { + if (it is DanaRSPacketHistoryCarbohydrate) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Carbohydrate(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryCarbohydrate(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__CARBOHYDRATE", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryDailyTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryDailyTest.kt index a98894c6e7..eb1c1331ec 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryDailyTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryDailyTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryDailyTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Daily) { + if (it is DanaRSPacketHistoryDaily) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Daily(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryDaily(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__DAILY", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryPrimeTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryPrimeTest.kt index a651910802..bd050f9048 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryPrimeTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryPrimeTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryPrimeTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Prime) { + if (it is DanaRSPacketHistoryPrime) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Prime(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryPrime(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__PRIME", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryRefillTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryRefillTest.kt index 65d484aa77..8a961122d0 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryRefillTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryRefillTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryRefillTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Refill) { + if (it is DanaRSPacketHistoryRefill) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Refill(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryRefill(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__REFILL", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistorySuspendTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistorySuspendTest.kt index 04fba763ee..af5b2adcbd 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistorySuspendTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistorySuspendTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistorySuspendTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Suspend) { + if (it is DanaRSPacketHistorySuspend) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Suspend(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistorySuspend(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__SUSPEND", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryTemporaryTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryTemporaryTest.kt index c8eed86284..5a906984a1 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryTemporaryTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketHistoryTemporaryTest.kt @@ -13,18 +13,18 @@ class DanaRsPacketHistoryTemporaryTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_History_Temporary) { + if (it is DanaRSPacketHistoryTemporary) { it.rxBus = rxBus } } } @Test fun runTest() { - val packet = DanaRS_Packet_History_Temporary(packetInjector, System.currentTimeMillis()) + val packet = DanaRSPacketHistoryTemporary(packetInjector, System.currentTimeMillis()) Assert.assertEquals("REVIEW__TEMPORARY", packet.friendlyName) } } \ No newline at end of file diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt index 9df91c6c38..3e2b68a21c 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyAlarmTest.kt @@ -17,7 +17,7 @@ class DanaRsPacketNotifyAlarmTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Notify_Alarm) { + if (it is DanaRSPacketNotifyAlarm) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -28,9 +28,9 @@ class DanaRsPacketNotifyAlarmTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Notify_Alarm(packetInjector) + val packet = DanaRSPacketNotifyAlarm(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(17, 0x01.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt index ab9b803ad9..ef51dafae2 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyDeliveryRateDisplayTest.kt @@ -39,7 +39,7 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Notify_Delivery_Rate_Display) { + if (it is DanaRSPacketNotifyDeliveryRateDisplay) { it.aapsLogger = aapsLogger it.rxBus = rxBus it.resourceHelper = resourceHelper @@ -51,11 +51,11 @@ class DanaRsPacketNotifyDeliveryRateDisplayTest : DanaRSTestBase() { @Test fun runTest() { `when`(resourceHelper.gs(ArgumentMatchers.anyInt(), anyObject())).thenReturn("SomeString") // val packet = DanaRS_Packet_Notify_Delivery_Rate_Display(1.0, Treatment(treatmentInjector)) - val packet = DanaRS_Packet_Notify_Delivery_Rate_Display(packetInjector) + val packet = DanaRSPacketNotifyDeliveryRateDisplay(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding -// 0% delivered + // 0% delivered packet.handleMessage(createArray(17, 0.toByte())) Assert.assertEquals(true, packet.failed) // 100 % delivered diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyMissedBolusAlarmTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyMissedBolusAlarmTest.kt index 0a25ea13e9..4062e844f8 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyMissedBolusAlarmTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketNotifyMissedBolusAlarmTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketNotifyMissedBolusAlarmTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Notify_Missed_Bolus_Alarm) { + if (it is DanaRSPacketNotifyMissedBolusAlarm) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Notify_Missed_Bolus_Alarm(packetInjector) + val packet = DanaRSPacketNotifyMissedBolusAlarm(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(6, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetPumpTimeTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetPumpTimeTest.kt index 5efaeb9812..d2f8a624f3 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetPumpTimeTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetPumpTimeTest.kt @@ -14,18 +14,18 @@ class DanaRsPacketOptionGetPumpTimeTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } - if (it is DanaRS_Packet_Option_Get_Pump_Time) { + if (it is DanaRSPacketOptionGetPumpTime) { it.danaPump = danaPump } } } @Test fun runTest() { - val packet = DanaRS_Packet_Option_Get_Pump_Time(packetInjector) + val packet = DanaRSPacketOptionGetPumpTime(packetInjector) val array = createArray(8, 0.toByte()) // 6 + 2 putByteToArray(array, 0, 19) // year 2019 putByteToArray(array, 1, 2) // month february diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetUserOptionTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetUserOptionTest.kt index fb55d3c58b..7592981130 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetUserOptionTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionGetUserOptionTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketOptionGetUserOptionTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Option_Get_User_Option) { + if (it is DanaRSPacketOptionGetUserOption) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,9 +21,9 @@ class DanaRsPacketOptionGetUserOptionTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Option_Get_User_Option(packetInjector) + val packet = DanaRSPacketOptionGetUserOption(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(20, 0.toByte())) Assert.assertEquals(true, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionSetPumpTimeTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionSetPumpTimeTest.kt index 2b39688f61..1bcf69767b 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionSetPumpTimeTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketOptionSetPumpTimeTest.kt @@ -14,7 +14,7 @@ class DanaRsPacketOptionSetPumpTimeTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet) { + if (it is DanaRSPacket) { it.aapsLogger = aapsLogger it.dateUtil = dateUtil } @@ -23,9 +23,9 @@ class DanaRsPacketOptionSetPumpTimeTest : DanaRSTestBase() { @Test fun runTest() { val date = DateTime() - val packet = DanaRS_Packet_Option_Set_Pump_Time(packetInjector, date.millis) + val packet = DanaRSPacketOptionSetPumpTime(packetInjector, date.millis) // test params - val params = packet.requestParams + val params = packet.getRequestParams() Assert.assertEquals((date.year - 2000 and 0xff).toByte(), params[0]) // 2019 -> 19 Assert.assertEquals((date.monthOfYear and 0xff).toByte(), params[1]) Assert.assertEquals((date.dayOfMonth and 0xff).toByte(), params[2]) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewBolusAvgTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewBolusAvgTest.kt index c4b7219a41..99688376d5 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewBolusAvgTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewBolusAvgTest.kt @@ -13,16 +13,16 @@ class DanaRsPacketReviewBolusAvgTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Review_Bolus_Avg) { + if (it is DanaRSPacketReviewBolusAvg) { it.aapsLogger = aapsLogger } } } @Test fun runTest() { - val packet = DanaRS_Packet_Review_Bolus_Avg(packetInjector) + val packet = DanaRSPacketReviewBolusAvg(packetInjector) // test params - Assert.assertEquals(null, packet.requestParams) + Assert.assertEquals(0, packet.getRequestParams().size) // test message decoding packet.handleMessage(createArray(12, 0.toByte())) Assert.assertEquals(false, packet.failed) diff --git a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewGetPumpDecRatioTest.kt b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewGetPumpDecRatioTest.kt index 43c56c9496..44deb23fbd 100644 --- a/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewGetPumpDecRatioTest.kt +++ b/danars/src/test/java/info/nightscout/androidaps/danars/comm/DanaRsPacketReviewGetPumpDecRatioTest.kt @@ -13,7 +13,7 @@ class DanaRsPacketReviewGetPumpDecRatioTest : DanaRSTestBase() { private val packetInjector = HasAndroidInjector { AndroidInjector { - if (it is DanaRS_Packet_Review_Get_Pump_Dec_Ratio) { + if (it is DanaRSPacketReviewGetPumpDecRatio) { it.aapsLogger = aapsLogger it.danaPump = danaPump } @@ -21,7 +21,7 @@ class DanaRsPacketReviewGetPumpDecRatioTest : DanaRSTestBase() { } @Test fun runTest() { - val packet = DanaRS_Packet_Review_Get_Pump_Dec_Ratio(packetInjector) + val packet = DanaRSPacketReviewGetPumpDecRatio(packetInjector) val array = ByteArray(100) putByteToArray(array, 0, 4.toByte()) From c00d7448e21e71637bc73b179882f647b749c465 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 1 Jun 2021 10:32:42 +0200 Subject: [PATCH 11/91] fix NS IOB upload --- .../nightscout/androidaps/extensions/DeviceStatusExtension.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt index fcd53753ea..4239f72ab2 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/DeviceStatusExtension.kt @@ -20,7 +20,7 @@ fun DeviceStatus.toJson(dateUtil: DateUtil): JSONObject = it.put("openaps", JSONObject().also { openaps -> if (enacted != null) openaps.put("enacted", JSONObject(enacted)) if (suggested != null) openaps.put("suggested", JSONObject(suggested)) - if (iob != null) openaps.put("iob", iob) + if (iob != null) openaps.put("iob", JSONObject(iob)) }) if (uploaderBattery != 0) it.put("uploaderBattery", uploaderBattery) if (configuration != null) it.put("configuration", JSONObject(configuration)) From 4b017cd0ea13f04acce0829093ecd4a301230205 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 1 Jun 2021 19:48:25 +0200 Subject: [PATCH 12/91] fix sendig logs --- app/src/main/res/xml/filepaths.xml | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/app/src/main/res/xml/filepaths.xml b/app/src/main/res/xml/filepaths.xml index c9f65d8f56..65599ccdd0 100644 --- a/app/src/main/res/xml/filepaths.xml +++ b/app/src/main/res/xml/filepaths.xml @@ -1,4 +1,18 @@ - + + + + + \ No newline at end of file From 1d12883f9592fc73f2483c8ea1ffd904dcd61a53 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 1 Jun 2021 20:04:59 +0200 Subject: [PATCH 13/91] fix receiving NOTEs form NS --- .../plugins/general/nsclient/NSClientAddUpdateWorker.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt index 8bb8413c6d..0559196eac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientAddUpdateWorker.kt @@ -193,6 +193,7 @@ class NSClientAddUpdateWorker( eventType == TherapyEvent.Type.ANNOUNCEMENT.text || eventType == TherapyEvent.Type.QUESTION.text || eventType == TherapyEvent.Type.EXERCISE.text || + eventType == TherapyEvent.Type.NOTE.text || eventType == TherapyEvent.Type.PUMP_BATTERY_CHANGE.text -> if (sp.getBoolean(R.string.key_ns_receive_therapy_events, false) || config.NSCLIENT) { therapyEventFromJson(json)?.let { therapyEvent -> From db95670be52ec495b6537a610f5802ea975dc5ec Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 1 Jun 2021 22:34:18 +0200 Subject: [PATCH 14/91] fix loop dialog --- .../androidaps/dialogs/LoopDialog.kt | 117 ++++++------------ 1 file changed, 36 insertions(+), 81 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt index cfe1a210a3..5cffcd0427 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt @@ -279,7 +279,7 @@ class LoopDialog : DaggerDialogFragment() { loopPlugin.setPluginEnabled(PluginType.LOOP, false) loopPlugin.setFragmentVisible(PluginType.LOOP, false) configBuilder.storeSettings("DisablingLoop") - rxBus.send(EventRefreshOverview("suspendmenu")) + rxBus.send(EventRefreshOverview("suspend_menu")) commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { @@ -302,7 +302,7 @@ class LoopDialog : DaggerDialogFragment() { loopPlugin.setPluginEnabled(PluginType.LOOP, true) loopPlugin.setFragmentVisible(PluginType.LOOP, true) configBuilder.storeSettings("EnablingLoop") - rxBus.send(EventRefreshOverview("suspendmenu")) + rxBus.send(EventRefreshOverview("suspend_menu")) disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now())) .subscribe({ result -> result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } @@ -320,7 +320,7 @@ class LoopDialog : DaggerDialogFragment() { }, { aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) }) - rxBus.send(EventRefreshOverview("suspendmenu")) + rxBus.send(EventRefreshOverview("suspend_menu")) commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (!result.success) { @@ -334,119 +334,74 @@ class LoopDialog : DaggerDialogFragment() { R.id.overview_suspend_1h -> { uel.log(Action.SUSPEND, Sources.LoopDialog, ValueWithUnit.Hour(1)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.hours(1).msecs(), OfflineEvent.Reason.SUSPEND)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + loopPlugin.suspendLoop(T.hours(1).mins().toInt()) + rxBus.send(EventRefreshOverview("suspend_menu")) return true } R.id.overview_suspend_2h -> { uel.log(Action.SUSPEND, Sources.LoopDialog, ValueWithUnit.Hour(2)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.hours(2).msecs(), OfflineEvent.Reason.SUSPEND)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + loopPlugin.suspendLoop(T.hours(2).mins().toInt()) + rxBus.send(EventRefreshOverview("suspend_menu")) return true } R.id.overview_suspend_3h -> { uel.log(Action.SUSPEND, Sources.LoopDialog, ValueWithUnit.Hour(3)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.hours(3).msecs(), OfflineEvent.Reason.SUSPEND)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + loopPlugin.suspendLoop(T.hours(3).mins().toInt()) + rxBus.send(EventRefreshOverview("suspend_menu")) return true } R.id.overview_suspend_10h -> { uel.log(Action.SUSPEND, Sources.LoopDialog, ValueWithUnit.Hour(10)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.hours(10).msecs(), OfflineEvent.Reason.SUSPEND)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + loopPlugin.suspendLoop(T.hours(10).mins().toInt()) + rxBus.send(EventRefreshOverview("suspend_menu")) return true } R.id.overview_disconnect_15m -> { - uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Minute(15)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.mins(15).msecs(), OfflineEvent.Reason.DISCONNECT_PUMP)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + profileFunction.getProfile()?.let { profile -> + uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Minute(15)) + loopPlugin.goToZeroTemp(T.mins(15).mins().toInt(), profile, OfflineEvent.Reason.DISCONNECT_PUMP) + rxBus.send(EventRefreshOverview("suspend_menu")) + } return true } R.id.overview_disconnect_30m -> { - uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Minute(30)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.mins(30).msecs(), OfflineEvent.Reason.DISCONNECT_PUMP)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + profileFunction.getProfile()?.let { profile -> + uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Minute(30)) + loopPlugin.goToZeroTemp(T.mins(30).mins().toInt(), profile, OfflineEvent.Reason.DISCONNECT_PUMP) + rxBus.send(EventRefreshOverview("suspend_menu")) + } return true } R.id.overview_disconnect_1h -> { - uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Hour(1)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.mins(60).msecs(), OfflineEvent.Reason.DISCONNECT_PUMP)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - sp.putBoolean(R.string.key_objectiveusedisconnect, true) - rxBus.send(EventRefreshOverview("suspendmenu")) + profileFunction.getProfile()?.let { profile -> + uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Hour(1)) + loopPlugin.goToZeroTemp(T.hours(1).mins().toInt(), profile, OfflineEvent.Reason.DISCONNECT_PUMP) + rxBus.send(EventRefreshOverview("suspend_menu")) + } return true } R.id.overview_disconnect_2h -> { - uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Hour(2)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.mins(120).msecs(), OfflineEvent.Reason.DISCONNECT_PUMP)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + profileFunction.getProfile()?.let { profile -> + uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Hour(2)) + loopPlugin.goToZeroTemp(T.hours(2).mins().toInt(), profile, OfflineEvent.Reason.DISCONNECT_PUMP) + rxBus.send(EventRefreshOverview("suspend_menu")) + } return true } R.id.overview_disconnect_3h -> { - uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Hour(3)) - disposable += repository.runTransactionForResult(InsertAndCancelCurrentOfflineEventTransaction(dateUtil.now(), T.mins(180).msecs(), OfflineEvent.Reason.DISCONNECT_PUMP)) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated OfflineEvent $it") } - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted OfflineEvent $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving OfflineEvent", it) - }) - rxBus.send(EventRefreshOverview("suspendmenu")) + profileFunction.getProfile()?.let { profile -> + uel.log(Action.DISCONNECT, Sources.LoopDialog, ValueWithUnit.Hour(3)) + loopPlugin.goToZeroTemp(T.hours(3).mins().toInt(), profile, OfflineEvent.Reason.DISCONNECT_PUMP) + rxBus.send(EventRefreshOverview("suspend_menu")) + } return true } } From fedba23405bfd122fcf42c635c747a47c570d8e5 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 1 Jun 2021 22:51:16 +0200 Subject: [PATCH 15/91] code cleanup --- .../database/entities/TherapyEvent.kt | 2 +- .../insight/di/InsightCommModule.kt | 3 +- .../pump/medtronic/MedtronicFragment.kt | 2 +- .../pump/medtronic/comm/MedtronicConverter.kt | 2 +- .../comm/history/MedtronicHistoryDecoder.kt | 2 +- .../comm/history/MedtronicHistoryEntry.kt | 8 ---- .../comm/history/pump/PumpHistoryEntry.kt | 21 ---------- .../comm/history/pump/PumpHistoryEntryType.kt | 1 - .../GetHistoryPageCarelinkMessageBody.kt | 4 -- .../medtronic/data/MedtronicHistoryData.kt | 2 +- .../pump/medtronic/data/dto/BasalProfile.kt | 2 +- .../medtronic/data/dto/BasalProfileEntry.kt | 7 ---- .../pump/medtronic/data/dto/TempBasalPair.kt | 2 +- .../defs/MedtronicNotificationType.kt | 2 +- .../pump/medtronic/di/MedtronicModule.kt | 2 +- .../dialog/MedtronicHistoryActivity.kt | 18 ++++----- .../omnipod/dash/dagger/OmnipodDashModule.kt | 3 +- .../BolusShortInsulinProgramElement.java | 2 +- .../dash/driver/pod/definition/AlarmType.java | 2 +- .../pod/definition/AlertConfiguration.java | 16 ++++---- .../dash/driver/pod/definition/AlertSlot.java | 2 +- .../pod/definition/BeepRepetitionType.java | 2 +- .../dash/driver/pod/definition/BeepType.java | 2 +- .../driver/pod/definition/DeliveryStatus.java | 2 +- .../driver/pod/definition/NakErrorType.java | 2 +- .../dash/driver/pod/definition/PodStatus.java | 2 +- .../driver/pod/response/ResponseType.java | 6 +-- .../pod/response/SetUniqueIdResponse.java | 38 +++++++++---------- 28 files changed, 56 insertions(+), 103 deletions(-) diff --git a/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt b/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt index 8a701e1e21..f930be4645 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/entities/TherapyEvent.kt @@ -48,7 +48,7 @@ data class TherapyEvent( enum class GlucoseUnit { MGDL, MMOL; - companion object { } + companion object } enum class MeterType(val text: String) { diff --git a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt index 7073ad14ae..4359b8d9fa 100644 --- a/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt +++ b/insight/src/main/java/info/nightscout/androidaps/insight/di/InsightCommModule.kt @@ -4,5 +4,4 @@ import dagger.Module @Module @Suppress("unused") -abstract class InsightCommModule { -} \ No newline at end of file +abstract class InsightCommModule \ No newline at end of file diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 95274476fa..57630d6248 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -322,7 +322,7 @@ class MedtronicFragment : DaggerFragment() { val tbrRemainingTime: Int? = medtronicPumpStatus.tbrRemainingTime if (tbrRemainingTime != null) { - tbrStr = resourceHelper.gs(R.string.mdt_tbr_remaining, medtronicPumpStatus.tempBasalAmount, tbrRemainingTime); + tbrStr = resourceHelper.gs(R.string.mdt_tbr_remaining, medtronicPumpStatus.tempBasalAmount, tbrRemainingTime) } binding.tempBasal.text = tbrStr diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.kt index 07da3aceaa..86c04e3e90 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicConverter.kt @@ -109,7 +109,7 @@ class MedtronicConverter @Inject constructor( } } - public fun decodeSettingsLoop(rd: ByteArray): Map { + fun decodeSettingsLoop(rd: ByteArray): Map { val map: MutableMap = HashMap() addSettingToMap("PCFG_MAX_BOLUS", "" + decodeMaxBolus(rd), PumpConfigurationGroup.Bolus, map) addSettingToMap( diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.kt index c834e92711..57a6b175ab 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryDecoder.kt @@ -92,7 +92,7 @@ abstract class MedtronicHistoryDecoder(var aapsLogge StringUtil.appendToStringBuilder(sb, key1, ", ") } val spaces = StringUtils.repeat(" ", 14 - key.name.length) - aapsLogger.info(LTag.PUMPCOMM, " ${key.name}$spaces - ${value.size}. Elements: ${sb.toString()}") + aapsLogger.info(LTag.PUMPCOMM, " ${key.name}$spaces - ${value.size}. Elements: $sb") } else { aapsLogger.info(LTag.PUMPCOMM, " ${key.name} - ${value.size}") } diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.kt index d9baa82acc..dc38b62601 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/MedtronicHistoryEntry.kt @@ -17,24 +17,18 @@ abstract class MedtronicHistoryEntry : MedtronicHistoryEntryInterface { lateinit var rawData: List protected var sizes = IntArray(3) - get() = field lateinit var head: ByteArray lateinit var datetime: ByteArray lateinit var body: ByteArray var id: Long = 0 - set(value) { - field = value - } @Expose var DT: String? = null - get() = field @Expose var atechDateTime: Long = 0L - get() = field set(value) { field = value DT = DateTimeUtil.toString(value) @@ -43,7 +37,6 @@ abstract class MedtronicHistoryEntry : MedtronicHistoryEntryInterface { @Expose var decodedData: MutableMap = mutableMapOf() - get() = field /** * Pump id that will be used with AAPS object (time * 1000 + historyType (max is FF = 255) @@ -61,7 +54,6 @@ abstract class MedtronicHistoryEntry : MedtronicHistoryEntryInterface { * Linked object, see linked */ var linkedObject: Any? = null - get() = field set(value) { linked = true field = value diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.kt index ea6d521e74..0bc1e8106e 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntry.kt @@ -24,16 +24,9 @@ class PumpHistoryEntry : MedtronicHistoryEntry() { override var opCode: Byte? = null // this is set only when we have unknown entry... get() = if (field == null) entryType.code else field - set(value) { - field = value - } var offset = 0 var displayableValue = "" - get() = field - set(value) { - field = value - } fun setEntryType(medtronicDeviceType: MedtronicDeviceType, entryType: PumpHistoryEntryType, opCode: Byte? = null) { this.entryType = entryType @@ -57,17 +50,6 @@ class PumpHistoryEntry : MedtronicHistoryEntry() { + StringUtil.getStringInLength("" + opCode, 3) + ", 0x" + ByteUtil.shortHexString(opCode!!) + "]") - override fun toString(): String { - return super.toString() - // Object object = this.getDecodedDataEntry("Object"); -// -// if (object == null) { -// return super.toString(); -// } else { -// return super.toString() + "PumpHistoryEntry [type=" + StringUtil.getStringInLength(entryType.name(), 20) + ", DT: " + DT + ", Object=" + object.toString() + "]"; -// } - } - override val entryTypeName: String get() = entryType.name @@ -117,9 +99,6 @@ class PumpHistoryEntry : MedtronicHistoryEntry() { } return field } - set(pumpId) { - field = pumpId - } fun hasBolusChanged(entry: PumpHistoryEntry): Boolean { if (entryType == PumpHistoryEntryType.Bolus) { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.kt index 1fc9645f18..1c2dc301f2 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/PumpHistoryEntryType.kt @@ -205,7 +205,6 @@ constructor(var code: Byte, private var specialRulesHead: MutableList? = null private var specialRulesBody: MutableList? = null private var hasSpecialRules = false - get() = field fun getTotalLength(medtronicDeviceType: MedtronicDeviceType): Int { return if (hasSpecialRules) { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/GetHistoryPageCarelinkMessageBody.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/GetHistoryPageCarelinkMessageBody.kt index 1f86c1446a..574bbacc9f 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/GetHistoryPageCarelinkMessageBody.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/message/GetHistoryPageCarelinkMessageBody.kt @@ -22,10 +22,6 @@ class GetHistoryPageCarelinkMessageBody : CarelinkLongMessageBody { override val length: Int get() = data!!.size - override fun init(rxData: ByteArray?) { - super.init(rxData) - } - fun init(pageNum: Int) { val numArgs: Byte = 1 super.init(byteArrayOf(numArgs, pageNum.toByte())) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index 180b5f9d1f..843ebf7df8 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -91,7 +91,7 @@ class MedtronicHistoryData @Inject constructor( .filter { f -> f.pumpId == pumpId } .findFirst() - return if (findFirst.isPresent()) findFirst.get() else null + return if (findFirst.isPresent) findFirst.get() else null } private fun showLogs(header: String?, data: String) { diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.kt index a3d373c5cf..f893c1b2a0 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.kt @@ -314,7 +314,7 @@ class BasalProfile { fun isBasalProfileByHourUndefined(basalByHour: DoubleArray): Boolean { for (i in 0..23) { if (basalByHour[i] > 0.0) { - return false; + return false } } return true diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.kt index 6ffbefcf2d..a8d188e3df 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfileEntry.kt @@ -15,16 +15,9 @@ class BasalProfileEntry { var rate_raw: ByteArray var rate = 0.0 - set(value) { - field = value - } var startTime_raw: Byte var startTime : LocalTime? = null // Just a "time of day" - set(value) { - field = value - } - constructor() { rate = -9.999E6 diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.kt index 1cd5f8dab7..fcc7e71996 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.kt @@ -62,7 +62,7 @@ class TempBasalPair : TempBasalPair { aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "TempBasalPair (with %d byte response): %s", response.size, toString())) } - constructor(insulinRate: Double, isPercent: Boolean, durationMinutes: Int) : super(insulinRate, isPercent, durationMinutes) {} + constructor(insulinRate: Double, isPercent: Boolean, durationMinutes: Int) : super(insulinRate, isPercent, durationMinutes) // list.add((byte) 0); // ? diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicNotificationType.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicNotificationType.kt index aad989679d..b6bd1a758e 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicNotificationType.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/MedtronicNotificationType.kt @@ -19,5 +19,5 @@ enum class MedtronicNotificationType(var notificationType: Int, PumpWrongMaxBasalSet(R.string.medtronic_error_pump_wrong_max_basal_set, Notification.NORMAL), // PumpWrongTimeUrgent(R.string.medtronic_notification_check_time_date, Notification.URGENT), PumpWrongTimeNormal(R.string.medtronic_notification_check_time_date, Notification.NORMAL), TimeChangeOver24h(Notification.OVER_24H_TIME_CHANGE_REQUESTED, R.string.medtronic_error_pump_24h_time_change_requested, Notification.URGENT); - constructor(resourceId: Int, notificationUrgency: Int) : this(Notification.MEDTRONIC_PUMP_ALARM, resourceId, notificationUrgency) {} + constructor(resourceId: Int, notificationUrgency: Int) : this(Notification.MEDTRONIC_PUMP_ALARM, resourceId, notificationUrgency) } \ No newline at end of file diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/di/MedtronicModule.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/di/MedtronicModule.kt index 0be7f1ba73..0eebc3bd81 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/di/MedtronicModule.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/di/MedtronicModule.kt @@ -30,6 +30,6 @@ abstract class MedtronicModule { companion object { @Provides - fun byteUtilProvider(): ByteUtil = ByteUtil(); + fun byteUtilProvider(): ByteUtil = ByteUtil() } } \ No newline at end of file diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt index 6257099574..492b5b9ddb 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt @@ -84,10 +84,6 @@ class MedtronicHistoryActivity : DaggerActivity() { manualChange = false } - override fun onPause() { - super.onPause() - } - override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.medtronic_history_activity) @@ -96,17 +92,17 @@ class MedtronicHistoryActivity : DaggerActivity() { recyclerView = findViewById(R.id.medtronic_history_recyclerview) recyclerView.setHasFixedSize(true) llm = LinearLayoutManager(this) - recyclerView.setLayoutManager(llm) + recyclerView.layoutManager = llm recyclerViewAdapter = RecyclerViewAdapter(filteredHistoryList) - recyclerView.setAdapter(recyclerViewAdapter) - statusView.setVisibility(View.GONE) + recyclerView.adapter = recyclerViewAdapter + statusView.visibility = View.GONE typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(resourceHelper)) val spinnerAdapter = ArrayAdapter(this, R.layout.spinner_centered, typeListFull) - historyTypeSpinner.setAdapter(spinnerAdapter) - historyTypeSpinner.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener { + historyTypeSpinner.adapter = spinnerAdapter + historyTypeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { if (manualChange) return - val selected = historyTypeSpinner.getSelectedItem() as TypeList + val selected = historyTypeSpinner.selectedItem as TypeList showingType = selected selectedGroup = selected.entryGroup filterHistory(selectedGroup) @@ -116,7 +112,7 @@ class MedtronicHistoryActivity : DaggerActivity() { if (manualChange) return filterHistory(PumpHistoryEntryGroup.All) } - }) + } } private fun getTypeList(list: List): List { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index 285349495a..7003c3112b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -4,5 +4,4 @@ import dagger.Module @Module @Suppress("unused") -abstract class OmnipodDashModule { -} +abstract class OmnipodDashModule diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java index 0c23171639..7e80cc70b4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import java.nio.ByteBuffer; public class BolusShortInsulinProgramElement implements ShortInsulinProgramElement { - private short numberOfPulses; + private final short numberOfPulses; public BolusShortInsulinProgramElement(short numberOfPulses) { this.numberOfPulses = numberOfPulses; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java index 7fcf8a8ece..db41aa1653 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java @@ -157,7 +157,7 @@ public enum AlarmType { ALARM_BLE_QN_CRIT_VAR_FAIL((byte) 0xc2), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; AlarmType(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java index b0341235c7..a2c5497619 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java @@ -5,14 +5,14 @@ import androidx.annotation.NonNull; import java.nio.ByteBuffer; public class AlertConfiguration implements Encodable { - private AlertSlot slot; - private boolean enabled; - private short durationInMinutes; - private boolean autoOff; - private AlertTriggerType triggerType; - private short offsetInMinutesOrThresholdInMicroLiters; - private BeepType beepType; - private BeepRepetitionType beepRepetition; + private final AlertSlot slot; + private final boolean enabled; + private final short durationInMinutes; + private final boolean autoOff; + private final AlertTriggerType triggerType; + private final short offsetInMinutesOrThresholdInMicroLiters; + private final BeepType beepType; + private final BeepRepetitionType beepRepetition; public AlertConfiguration(AlertSlot slot, boolean enabled, short durationInMinutes, boolean autoOff, AlertTriggerType triggerType, short offsetInMinutesOrThresholdInMicroLiters, BeepType beepType, BeepRepetitionType beepRepetition) { this.slot = slot; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java index 9e8b23cb74..7ee2b7cb5a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java @@ -11,7 +11,7 @@ public enum AlertSlot { EXPIRATION((byte) 0x07), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; AlertSlot(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java index 2b290f96b5..31cb23dc14 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java @@ -8,7 +8,7 @@ public enum BeepRepetitionType { XXX4((byte) 0x06), // Used in imminent pod expiration alert XXX5((byte) 0x08); // Used in lump of coal alert - private byte value; + private final byte value; BeepRepetitionType(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java index ee750df520..e88f77e67f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java @@ -5,7 +5,7 @@ public enum BeepType { FOUR_TIMES_BIP_BEEP((byte) 0x02), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert LONG_SINGLE_BEEP((byte) 0x06); // Used in stop delivery command - private byte value; + private final byte value; BeepType(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java index 7dc9618fb5..dad0745505 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java @@ -9,7 +9,7 @@ public enum DeliveryStatus { BOLUS_AND_TEMP_BASAL_ACTIVE((byte) 0x06), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; DeliveryStatus(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java index d6482386ee..a7fc43b744 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java @@ -32,7 +32,7 @@ public enum NakErrorType { INVALID_CRC((byte) 0x1d), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; NakErrorType(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java index 88fb98b546..b746cd9435 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java @@ -19,7 +19,7 @@ public enum PodStatus { DEACTIVATED((byte) 0x0f), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; PodStatus(byte value) { this.value = value; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java index 384ae11c0e..f903c28eb9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java @@ -7,7 +7,7 @@ public enum ResponseType { NAK_RESPONSE((byte) 0x06), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; ResponseType(byte value) { this.value = value; @@ -37,7 +37,7 @@ public enum ResponseType { STATUS_RESPONSE_PAGE_81((byte) 0x51), UNKNOWN((byte) 0xff); - private byte value; + private final byte value; AdditionalStatusResponseType(byte value) { this.value = value; @@ -62,7 +62,7 @@ public enum ResponseType { SET_UNIQUE_ID_RESPONSE((byte) 0x1b), UNKNOWN((byte) 0xff); - private byte length; + private final byte length; ActivationResponseType(byte length) { this.length = length; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java index 2c0703258a..6268ae57f5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java @@ -6,25 +6,25 @@ import java.util.Arrays; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; public final class SetUniqueIdResponse extends ActivationResponseBase { - private byte messageType; - private short messageLength; - private short pulseVolumeInTenThousandthMicroLiter; - private short pumpRate; - private short primePumpRate; - private short numberOfEngagingClutchDrivePulses; - private short numberOfPrimePulses; - private short podExpirationTimeInHours; - private short firmwareVersionMajor; - private short firmwareVersionMinor; - private short firmwareVersionInterim; - private short bleVersionMajor; - private short bleVersionMinor; - private short bleVersionInterim; - private short productId; - private PodStatus podStatus; - private long lotNumber; - private long podSequenceNumber; - private long uniqueIdReceivedInCommand; + private final byte messageType; + private final short messageLength; + private final short pulseVolumeInTenThousandthMicroLiter; + private final short pumpRate; + private final short primePumpRate; + private final short numberOfEngagingClutchDrivePulses; + private final short numberOfPrimePulses; + private final short podExpirationTimeInHours; + private final short firmwareVersionMajor; + private final short firmwareVersionMinor; + private final short firmwareVersionInterim; + private final short bleVersionMajor; + private final short bleVersionMinor; + private final short bleVersionInterim; + private final short productId; + private final PodStatus podStatus; + private final long lotNumber; + private final long podSequenceNumber; + private final long uniqueIdReceivedInCommand; public SetUniqueIdResponse(byte[] encoded) { super(ResponseType.ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded); From 328704eb5bbfdd931edb6fa21dbd8a29f6cf9796 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Jun 2021 06:00:22 +0000 Subject: [PATCH 16/91] Bump byteBuddyVersion from 1.11.0 to 1.11.1 Bumps `byteBuddyVersion` from 1.11.0 to 1.11.1. Updates `byte-buddy` from 1.11.0 to 1.11.1 - [Release notes](https://github.com/raphw/byte-buddy/releases) - [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md) - [Commits](https://github.com/raphw/byte-buddy/compare/byte-buddy-1.11.0...byte-buddy-1.11.1) Updates `byte-buddy-android` from 1.11.0 to 1.11.1 - [Release notes](https://github.com/raphw/byte-buddy/releases) - [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md) - [Commits](https://github.com/raphw/byte-buddy/compare/byte-buddy-1.11.0...byte-buddy-1.11.1) Updates `byte-buddy-agent` from 1.11.0 to 1.11.1 - [Release notes](https://github.com/raphw/byte-buddy/releases) - [Changelog](https://github.com/raphw/byte-buddy/blob/master/release-notes.md) - [Commits](https://github.com/raphw/byte-buddy/compare/byte-buddy-1.11.0...byte-buddy-1.11.1) --- updated-dependencies: - dependency-name: net.bytebuddy:byte-buddy dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: net.bytebuddy:byte-buddy-android dependency-type: direct:production update-type: version-update:semver-patch - dependency-name: net.bytebuddy:byte-buddy-agent dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7f5602306e..92d141d6f5 100644 --- a/build.gradle +++ b/build.gradle @@ -33,7 +33,7 @@ buildscript { dexmakerVersion = "1.2" retrofit2Version = '2.9.0' okhttp3Version = '4.9.0' - byteBuddyVersion = '1.11.0' + byteBuddyVersion = '1.11.1' androidx_junit = '1.1.2' androidx_rules = '1.4.0-alpha04' From f74955d062d3ded3e98a0ca58cf0c647a079d3c1 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 2 Jun 2021 16:54:58 +0200 Subject: [PATCH 17/91] Improve APS result logging --- .../androidaps/plugins/aps/loop/APSResult.kt | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt index 39202e1a4b..6c7633e693 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt @@ -30,6 +30,7 @@ import kotlin.math.max /** * Created by mike on 09.06.2016. */ +@Suppress("LeakingThis") open class APSResult @Inject constructor(val injector: HasAndroidInjector) { @Inject lateinit var aapsLogger: AAPSLogger @@ -42,7 +43,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { @Inject lateinit var dateUtil: DateUtil var date: Long = 0 - var reason: String? = null + var reason: String = "" var rate = 0.0 var percent = 0 var usePercent = false @@ -102,16 +103,16 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { val pump = activePlugin.activePump if (isChangeRequested) { // rate - var ret: String = if (rate == 0.0 && duration == 0) "${resourceHelper.gs(R.string.canceltemp)}\n" + var ret: String = if (rate == 0.0 && duration == 0) "${resourceHelper.gs(R.string.canceltemp)} " else if (rate == -1.0) "${resourceHelper.gs(R.string.let_temp_basal_run)}\n" - else if (usePercent) "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h)\n" + - "${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min\n" - else "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%)" + - "${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min\n" + else if (usePercent) "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(percent.toDouble())}% (${DecimalFormatter.to2Decimal(percent * pump.baseBasalRate / 100.0)} U/h) " + + "${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " + else "${resourceHelper.gs(R.string.rate)}: ${DecimalFormatter.to2Decimal(rate)} U/h (${DecimalFormatter.to2Decimal(rate / pump.baseBasalRate * 100)}%) " + + "${resourceHelper.gs(R.string.duration)}: ${DecimalFormatter.to2Decimal(duration.toDouble())} min " // smb - if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, resourceHelper)}\n" + if (smb != 0.0) ret += "SMB: ${DecimalFormatter.toPumpSupportedBolus(smb, activePlugin.activePump, resourceHelper)} " if (isCarbsRequired) { - ret += "$carbsRequiredText\n" + ret += "$carbsRequiredText " } // reason @@ -140,7 +141,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { } // reason - ret += "" + resourceHelper.gs(R.string.reason) + ": " + reason!!.replace("<", "<").replace(">", ">") + ret += "" + resourceHelper.gs(R.string.reason) + ": " + reason.replace("<", "<").replace(">", ">") return fromHtml(ret) } return if (isCarbsRequired) { @@ -156,7 +157,7 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { protected fun doClone(newResult: APSResult) { newResult.date = date - newResult.reason = if (reason != null) reason else null + newResult.reason = reason newResult.rate = rate newResult.duration = duration newResult.tempBasalRequested = tempBasalRequested @@ -332,12 +333,12 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { aapsLogger.debug(LTag.APS, "FALSE: Temp equal") return false } - // always report zerotemp + // always report zero temp if (percent == 0) { aapsLogger.debug(LTag.APS, "TRUE: Zero temp") return true } - // always report hightemp + // always report high temp if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT) { val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0 if (percent.toDouble() == pumpLimit) { @@ -368,12 +369,12 @@ open class APSResult @Inject constructor(val injector: HasAndroidInjector) { aapsLogger.debug(LTag.APS, "FALSE: Temp equal") return false } - // always report zerotemp + // always report zero temp if (rate == 0.0) { aapsLogger.debug(LTag.APS, "TRUE: Zero temp") return true } - // always report hightemp + // always report high temp if (pump.pumpDescription.tempBasalStyle == PumpDescription.ABSOLUTE) { val pumpLimit = pump.pumpDescription.pumpType.tbrSettings?.maxDose ?: 0.0 if (rate == pumpLimit) { From ec73c4b0cbe74eef57c05c82089d5a3fd4829252 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 2 Jun 2021 16:55:19 +0200 Subject: [PATCH 18/91] Insight vibrate permission --- insight/src/main/AndroidManifest.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/insight/src/main/AndroidManifest.xml b/insight/src/main/AndroidManifest.xml index feecfc8067..f00fc7fba9 100644 --- a/insight/src/main/AndroidManifest.xml +++ b/insight/src/main/AndroidManifest.xml @@ -2,6 +2,7 @@ + Date: Wed, 2 Jun 2021 16:56:13 +0200 Subject: [PATCH 19/91] immutable flag for PendingIntent --- .../nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt | 8 ++++---- .../general/overview/notifications/NotificationStore.kt | 2 +- .../PersistentNotificationPlugin.kt | 4 ++-- .../utils/androidNotification/NotificationHolderImpl.kt | 2 +- .../plugins/pump/insight/InsightAlertService.java | 6 +++--- .../complications/ComplicationTapBroadcastReceiver.java | 4 ++-- .../info/nightscout/androidaps/data/ListenerService.java | 2 +- 7 files changed, 14 insertions(+), 14 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index b2a13d8386..ba1f0425c6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -311,15 +311,15 @@ open class LoopPlugin @Inject constructor( if (sp.getBoolean(R.string.key_enable_carbs_required_alert_local, true) && sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, true)) { val intentAction5m = Intent(context, CarbSuggestionReceiver::class.java) intentAction5m.putExtra("ignoreDuration", 5) - val pendingIntent5m = PendingIntent.getBroadcast(context, 1, intentAction5m, PendingIntent.FLAG_UPDATE_CURRENT) + val pendingIntent5m = PendingIntent.getBroadcast(context, 1, intentAction5m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val actionIgnore5m = NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore5m, "Ignore 5m"), pendingIntent5m) val intentAction15m = Intent(context, CarbSuggestionReceiver::class.java) intentAction15m.putExtra("ignoreDuration", 15) - val pendingIntent15m = PendingIntent.getBroadcast(context, 1, intentAction15m, PendingIntent.FLAG_UPDATE_CURRENT) + val pendingIntent15m = PendingIntent.getBroadcast(context, 1, intentAction15m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val actionIgnore15m = NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore15m, "Ignore 15m"), pendingIntent15m) val intentAction30m = Intent(context, CarbSuggestionReceiver::class.java) intentAction30m.putExtra("ignoreDuration", 30) - val pendingIntent30m = PendingIntent.getBroadcast(context, 1, intentAction30m, PendingIntent.FLAG_UPDATE_CURRENT) + val pendingIntent30m = PendingIntent.getBroadcast(context, 1, intentAction30m, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val actionIgnore30m = NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore30m, "Ignore 30m"), pendingIntent30m) val builder = NotificationCompat.Builder(context, CHANNEL_ID) builder.setSmallIcon(R.drawable.notif_icon) @@ -441,7 +441,7 @@ open class LoopPlugin @Inject constructor( stackBuilder.addParentStack(MainActivity::class.java) // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent) - val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) + val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(resultPendingIntent) builder.setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000)) val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt index 2ac420ade8..b273ac952e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt @@ -128,7 +128,7 @@ class NotificationStore @Inject constructor( private fun deleteIntent(id: Int): PendingIntent { val intent = Intent(context, DismissNotificationService::class.java) intent.putExtra("alertID", id) - return PendingIntent.getService(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT) + return PendingIntent.getService(context, id, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) } fun createNotificationChannel() { 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 7a7edb678b..ceac37b723 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 @@ -171,7 +171,7 @@ class PersistentNotificationPlugin @Inject constructor( val msgReadPendingIntent = PendingIntent.getBroadcast(context, notificationHolder.notificationID, msgReadIntent, - PendingIntent.FLAG_UPDATE_CURRENT) + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val msgReplyIntent = Intent() .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) .setAction(REPLY_ACTION) @@ -181,7 +181,7 @@ class PersistentNotificationPlugin @Inject constructor( context, notificationHolder.notificationID, msgReplyIntent, - PendingIntent.FLAG_UPDATE_CURRENT) + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) // Build a RemoteInput for receiving voice input from devices val remoteInput = RemoteInput.Builder(EXTRA_VOICE_REPLY).build() // Create the UnreadConversation diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt index dfe9ed21c4..4fda9e5fd8 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt @@ -40,6 +40,6 @@ class NotificationHolderImpl @Inject constructor( override fun openAppIntent(context: Context): PendingIntent? = TaskStackBuilder.create(context).run { addParentStack(MainActivity::class.java) addNextIntent(Intent(context, MainActivity::class.java)) - getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) + getPendingIntent(0, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) } } diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java index a134c904be..8278203eae 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java @@ -302,17 +302,17 @@ public class InsightAlertService extends DaggerService implements InsightConnect 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); + PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true); switch (alert.getAlertStatus()) { case ACTIVE: Intent muteIntent = new Intent(this, InsightAlertService.class).putExtra("command", "mute"); - PendingIntent mutePendingIntent = PendingIntent.getService(this, 1, muteIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent mutePendingIntent = PendingIntent.getService(this, 1, muteIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.addAction(0, resourceHelper.gs(R.string.mute_alert), mutePendingIntent); case SNOOZED: Intent confirmIntent = new Intent(this, InsightAlertService.class).putExtra("command", "confirm"); - PendingIntent confirmPendingIntent = PendingIntent.getService(this, 2, confirmIntent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent confirmPendingIntent = PendingIntent.getService(this, 2, confirmIntent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); notificationBuilder.addAction(0, resourceHelper.gs(R.string.confirm), confirmPendingIntent); } diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java index 33d302dd6f..8e791b0fbb 100644 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java +++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java @@ -142,7 +142,7 @@ public class ComplicationTapBroadcastReceiver extends BroadcastReceiver { // Pass complicationId as the requestCode to ensure that different complications get // different intents. return PendingIntent.getBroadcast( - context, complicationId, intent, PendingIntent.FLAG_UPDATE_CURRENT); + context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); } /** @@ -161,7 +161,7 @@ public class ComplicationTapBroadcastReceiver extends BroadcastReceiver { // Pass complicationId as the requestCode to ensure that different complications get // different intents. return PendingIntent.getBroadcast( - context, complicationId, intent, PendingIntent.FLAG_UPDATE_CURRENT); + context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); } } diff --git a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java b/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java index e58d886f0e..78803079b8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java +++ b/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java @@ -589,7 +589,7 @@ public class ListenerService extends WearableListenerService implements GoogleAp intent.putExtras(params); PendingIntent resultPendingIntent = - PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); + PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); builder = builder.setContentIntent(resultPendingIntent); From c0dba456d78ebfaf7d2ec658071740fbd71cdbe0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 2 Jun 2021 22:40:30 +0200 Subject: [PATCH 20/91] fix lst bolus query and smb pocessing --- .../androidaps/plugins/aps/loop/LoopPlugin.kt | 26 +++++++++++-- .../androidaps/queue/CommandQueue.kt | 10 +++-- .../queue/commands/CommandSMBBolus.kt | 1 + .../plugins/pump/PumpSyncImplementation.kt | 2 +- .../comm/DanaRSPacketAPSHistoryEvents.kt | 39 +++++++++---------- .../androidaps/database/daos/BolusDao.kt | 8 ++-- 6 files changed, 53 insertions(+), 33 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index ba1f0425c6..40a32ddcc2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -166,11 +166,13 @@ open class LoopPlugin @Inject constructor( } override val isSuspended: Boolean - get() = repository.getOfflineEventActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing + get() = repository.getOfflineEventActiveAt(dateUtil.now()).blockingGet() is ValueWrapper.Existing override var enabled: Boolean get() = isEnabled() - set(value) { setPluginEnabled(PluginType.LOOP, value)} + set(value) { + setPluginEnabled(PluginType.LOOP, value) + } val isLGS: Boolean get() { @@ -209,6 +211,17 @@ open class LoopPlugin @Inject constructor( invoke(initiator, allowNotification, false) } + @Synchronized + fun isEmptyQueue(): Boolean { + val maxMinutes = 2L + val start = dateUtil.now() + while (start + T.mins(maxMinutes).msecs() > dateUtil.now()) { + if (commandQueue.size() == 0 && commandQueue.performing() == null) return true + SystemClock.sleep(100) + } + return false + } + @Synchronized operator fun invoke(initiator: String, allowNotification: Boolean, tempBasalFallback: Boolean) { try { @@ -247,6 +260,12 @@ open class LoopPlugin @Inject constructor( return } else rxBus.send(EventLoopInvoked()) + if (!isEmptyQueue()) { + aapsLogger.debug(LTag.APS, resourceHelper.gs(R.string.pumpbusy)) + rxBus.send(EventLoopSetLastRunGui(resourceHelper.gs(R.string.pumpbusy))) + return + } + // Prepare for pumps using % basals if (pump.pumpDescription.tempBasalStyle == PumpDescription.PERCENT && allowPercentage()) { apsResult.usePercent = true @@ -357,8 +376,7 @@ open class LoopPlugin @Inject constructor( } } if (resultAfterConstraints.isChangeRequested - && !commandQueue.bolusInQueue() - && !commandQueue.isRunning(Command.CommandType.BOLUS)) { + && !commandQueue.bolusInQueue()) { val waiting = PumpEnactResult(injector) waiting.queued = true if (resultAfterConstraints.tempBasalRequested) lastRun.tbrSetByPump = waiting 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 cdaba94dc6..10c0f8e983 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -202,11 +202,11 @@ open class CommandQueue @Inject constructor( @Synchronized override fun bolusInQueue(): Boolean { if (isRunning(CommandType.BOLUS)) return true + if (isRunning(CommandType.SMB_BOLUS)) return true synchronized(queue) { for (i in queue.indices) { - if (queue[i].commandType == CommandType.BOLUS) { - return true - } + if (queue[i].commandType == CommandType.BOLUS) return true + if (queue[i].commandType == CommandType.SMB_BOLUS) return true } } return false @@ -243,13 +243,15 @@ open class CommandQueue @Inject constructor( } var type = if (detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) CommandType.SMB_BOLUS else CommandType.BOLUS if (type == CommandType.SMB_BOLUS) { - if (isRunning(CommandType.BOLUS) || isRunning(CommandType.SMB_BOLUS) || bolusInQueue()) { + if (bolusInQueue()) { aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting SMB since a bolus is queue/running") + callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() return false } val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L if (detailedBolusInfo.lastKnownBolusTime < lastBolusTime) { aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting bolus, another bolus was issued since request time") + callback?.result(PumpEnactResult(injector).enacted(false).success(false))?.run() return false } removeAll(CommandType.SMB_BOLUS) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt index d43493059b..eaac269a71 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -23,6 +23,7 @@ class CommandSMBBolus( override fun execute() { val r: PumpEnactResult val lastBolusTime = repository.getLastBolusRecord()?.timestamp ?: 0L + aapsLogger.debug(LTag.PUMPQUEUE, "Last bolus: $lastBolusTime ${dateUtil.dateAndTimeAndSecondsString(lastBolusTime)}") if (lastBolusTime != 0L && lastBolusTime + T.mins(3).msecs() > dateUtil.now()) { aapsLogger.debug(LTag.PUMPQUEUE, "SMB requested but still in 3 min interval") r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB requested but still in 3 min interval") diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt index 4ea4d4d712..dfe8a94a42 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt @@ -70,7 +70,7 @@ class PumpSyncImplementation @Inject constructor( if (type.description != storedType || serialNumber != storedSerial) rxBus.send(EventNewNotification(Notification(Notification.WRONG_PUMP_DATA, resourceHelper.gs(R.string.wrong_pump_data), Notification.URGENT))) - aapsLogger.error(LTag.PUMP, "Ignoring pump history record Allowed: ${dateUtil.dateAndTimeAndSecondsString(storedTimestamp)} $storedType $storedSerial Received: $timestamp ${dateUtil.dateAndTimeAndSecondsString(timestamp)}${type.description} $serialNumber") + aapsLogger.error(LTag.PUMP, "Ignoring pump history record Allowed: ${dateUtil.dateAndTimeAndSecondsString(storedTimestamp)} $storedType $storedSerial Received: $timestamp ${dateUtil.dateAndTimeAndSecondsString(timestamp)} ${type.description} $serialNumber") return false } diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt index ddf8e3b606..4c26d38dc1 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt @@ -118,14 +118,13 @@ open class DanaRSPacketAPSHistoryEvents( val param1 = intFromBuffMsbLsb(data, 7, 2) val param2 = intFromBuffMsbLsb(data, 9, 2) val pumpId: Long - var id = 0 if (!danaPump.usingUTC) { datetime = dateTimeSecFromBuff(data, 1) // 6 bytes pumpId = datetime } else { datetime = intFromBuffMsbLsb(data, 3, 4) * 1000L - id = intFromBuffMsbLsb(data, 0, 2) // range only 1-2000 - pumpId = datetime shl 16 + id + val id = intFromBuffMsbLsb(data, 0, 2) // range only 1-2000 + pumpId = datetime * 2 + id } val status: String when (recordCode) { @@ -140,7 +139,7 @@ open class DanaRSPacketAPSHistoryEvents( pumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT TEMPSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT TEMPSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min") status = "TEMPSTART " + dateUtil.timeString(datetime) } @@ -150,7 +149,7 @@ open class DanaRSPacketAPSHistoryEvents( endPumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT TEMPSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT TEMPSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") status = "TEMPSTOP " + dateUtil.timeString(datetime) } @@ -163,7 +162,7 @@ open class DanaRSPacketAPSHistoryEvents( pumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") status = "EXTENDEDSTART " + dateUtil.timeString(datetime) } @@ -173,7 +172,7 @@ open class DanaRSPacketAPSHistoryEvents( endPumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") status = "EXTENDEDSTOP " + dateUtil.timeString(datetime) } @@ -186,7 +185,7 @@ open class DanaRSPacketAPSHistoryEvents( pumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U ") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U ") status = "BOLUS " + dateUtil.timeString(datetime) } @@ -199,7 +198,7 @@ open class DanaRSPacketAPSHistoryEvents( pumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") status = "DUALBOLUS " + dateUtil.timeString(datetime) } @@ -212,7 +211,7 @@ open class DanaRSPacketAPSHistoryEvents( pumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALEXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALEXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") status = "DUALEXTENDEDSTART " + dateUtil.timeString(datetime) } @@ -222,17 +221,17 @@ open class DanaRSPacketAPSHistoryEvents( endPumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") status = "DUALEXTENDEDSTOP " + dateUtil.timeString(datetime) } DanaPump.SUSPENDON -> { - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT SUSPENDON (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + "EVENT SUSPENDON (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") status = "SUSPENDON " + dateUtil.timeString(datetime) } DanaPump.SUSPENDOFF -> { - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT SUSPENDOFF (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + "EVENT SUSPENDOFF (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") status = "SUSPENDOFF " + dateUtil.timeString(datetime) } @@ -245,18 +244,18 @@ open class DanaRSPacketAPSHistoryEvents( pumpType = danaPump.pumpType(), pumpSerial = danaPump.serialNumber ) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT REFILL (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT REFILL (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") } status = "REFILL " + dateUtil.timeString(datetime) } DanaPump.PRIME -> { - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT PRIME (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + "EVENT PRIME (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") status = "PRIME " + dateUtil.timeString(datetime) } DanaPump.PROFILECHANGE -> { - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT PROFILECHANGE (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + "EVENT PROFILECHANGE (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h") status = "PROFILECHANGE " + dateUtil.timeString(datetime) } @@ -267,7 +266,7 @@ open class DanaRSPacketAPSHistoryEvents( pumpId = pumpId, pumpType = PumpType.DANA_RS, pumpSerial = danaPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g") status = "CARBS " + dateUtil.timeString(datetime) } @@ -280,19 +279,19 @@ open class DanaRSPacketAPSHistoryEvents( pumpType = danaPump.pumpType(), pumpSerial = danaPump.serialNumber ) - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + (if (newRecord) "**NEW** " else "") + "EVENT PRIMECANNULA(" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + (if (newRecord) "**NEW** " else "") + "EVENT PRIMECANNULA(" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") } status = "PRIMECANNULA " + dateUtil.timeString(datetime) } DanaPump.TIMECHANGE -> { val oldDateTime = intFromBuffMsbLsb(data, 7, 4) * 1000L - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "EVENT TIMECHANGE(" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Previous: " + dateUtil.dateAndTimeString(oldDateTime)) + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + "EVENT TIMECHANGE(" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Previous: " + dateUtil.dateAndTimeString(oldDateTime)) status = "TIMECHANGE " + dateUtil.timeString(datetime) } else -> { - aapsLogger.debug(LTag.PUMPCOMM, "[" + id + "] " + "Event: " + recordCode + " " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2) + aapsLogger.debug(LTag.PUMPCOMM, "[" + pumpId + "] " + "Event: " + recordCode + " " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2) status = "UNKNOWN " + dateUtil.timeString(datetime) } } diff --git a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt index 2483cb04cc..31169c9c93 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/daos/BolusDao.kt @@ -33,16 +33,16 @@ internal interface BolusDao : TraceableDao { @Query("SELECT * FROM $TABLE_BOLUSES WHERE temporaryId = :temporaryId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL") fun findByPumpTempIds(temporaryId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Bolus? - @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY timestamp DESC LIMIT 1") fun getLastBolusRecord(exclude: Bolus.Type = Bolus.Type.PRIMING): Bolus? - @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY timestamp DESC LIMIT 1") fun getLastBolusRecordMaybe(exclude: Bolus.Type = Bolus.Type.PRIMING): Maybe - @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type == :only AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type == :only AND referenceId IS NULL ORDER BY timestamp DESC LIMIT 1") fun getLastBolusRecordOfType(only: Bolus.Type): Bolus? - @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY id ASC LIMIT 1") + @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND type <> :exclude AND referenceId IS NULL ORDER BY timestamp ASC LIMIT 1") fun getOldestBolusRecord(exclude: Bolus.Type = Bolus.Type.PRIMING): Bolus? @Query("SELECT * FROM $TABLE_BOLUSES WHERE isValid = 1 AND timestamp >= :timestamp AND referenceId IS NULL ORDER BY id DESC") From b2fc621375f02e0085c754c44c706f0b91c7003a Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 3 Jun 2021 19:01:38 +0200 Subject: [PATCH 21/91] Dana reset buffer at connect --- .../java/info/nightscout/androidaps/danars/services/BLEComm.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt index 241720a19e..4196a20f32 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt @@ -126,6 +126,7 @@ class BLEComm @Inject internal constructor( encryptedDataRead = false encryptedCommandSent = false isConnecting = true + bufferLength = 0 aapsLogger.debug(LTag.PUMPBTCOMM, "Trying to create a new connection from: $from") connectDeviceName = device.name bluetoothGatt = device.connectGatt(context, false, mGattCallback) From eb11a43d69609bf9268b3fbb30e88846efbd99e2 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 4 Jun 2021 06:52:34 +0000 Subject: [PATCH 22/91] Bump firebase-crashlytics-gradle from 2.6.1 to 2.7.0 Bumps firebase-crashlytics-gradle from 2.6.1 to 2.7.0. --- updated-dependencies: - dependency-name: com.google.firebase:firebase-crashlytics-gradle dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 7f5602306e..1aff2b2bcf 100644 --- a/build.gradle +++ b/build.gradle @@ -49,7 +49,7 @@ buildscript { // see https://issuetracker.google.com/issues/162255866 classpath 'com.android.tools.build:gradle:4.1.3' classpath 'com.google.gms:google-services:4.3.5' - classpath 'com.google.firebase:firebase-crashlytics-gradle:2.6.1' + classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files From cd8f486dc0703d87d86944c7187c35077eb18f1e Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Sun, 6 Jun 2021 15:22:55 +0100 Subject: [PATCH 23/91] - added some additional logs for situation that is problem --- .../pump/medtronic/data/MedtronicHistoryData.kt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index 843ebf7df8..d3cb52acf0 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -611,6 +611,8 @@ class MedtronicHistoryData @Inject constructor( if (processList.isNotEmpty()) { for (tempBasalProcessDTO in processList) { + aapsLogger.debug(LTag.PUMP, "DD: tempBasalProcessDTO.itemOne: " + gson.toJson(tempBasalProcessDTO.itemOne)) + val entryWithTempId = findDbEntry(tempBasalProcessDTO.itemOne, tbrRecords) aapsLogger.debug(LTag.PUMP, "DD: entryWithTempId: " + (if (entryWithTempId == null) "null" else entryWithTempId.toString())) @@ -624,6 +626,18 @@ class MedtronicHistoryData @Inject constructor( aapsLogger.debug(LTag.PUMP, String.format("DD: tempIdEntry=%s, tbrEntry=%s, tempBasalProcessDTO=%s, pumpType=%s, serial=%s", gson.toJson(entryWithTempId), gson.toJson(tbrEntry), gson.toJson(tempBasalProcessDTO), medtronicPumpStatus.pumpType, medtronicPumpStatus.serialNumber)) + aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "BEFORE syncTemporaryBasalWithTempId " + + "[date=%d, dateProcess=%d, tbrEntry.insulinRate=%d, duration=%d, isAbsolute=%b, temporaryId=%d, pumpId=%d, pumpType=%s, pumpSerial=%s]", + tempBasalProcessDTO.atechDateTime, + tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), + tbrEntry.insulinRate, + tempBasalProcessDTO.duration * 60L * 1000L, + !tbrEntry.isPercent, + entryWithTempId.temporaryId, + tempBasalProcessDTO.pumpId, + medtronicPumpStatus.pumpType, + medtronicPumpStatus.serialNumber)) + val result = pumpSync.syncTemporaryBasalWithTempId( tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), tbrEntry.insulinRate, From 86625601d6715d44d6054913426de706e5b6ea51 Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Sun, 6 Jun 2021 15:39:36 +0100 Subject: [PATCH 24/91] - trying to fix some logging --- .../plugins/pump/medtronic/data/MedtronicHistoryData.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index d3cb52acf0..d1c3fc55e5 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -578,7 +578,7 @@ class MedtronicHistoryData @Inject constructor( val tbrRecords = pumpSyncStorage.getTBRs() aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, ProcessHistoryRecord.TBR.description + " List (before filter): %s, FromDb=%s", gson.toJson(entryList), - gson.toJson(tbrRecords))) + tbrRecords)) var processDTO: TempBasalProcessDTO? = null val processList: MutableList = mutableListOf() for (treatment in entryList) { From f2ed33c237128e7713ea030c875e04fda96ea00f Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Sun, 6 Jun 2021 21:54:29 +0100 Subject: [PATCH 25/91] - log changes, little bit of refactoring on PumpSyncStorage class --- .../plugins/pump/medtronic/data/MedtronicHistoryData.kt | 7 +++++-- .../androidaps/plugins/pump/common/sync/PumpSyncStorage.kt | 6 +++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index d1c3fc55e5..28ce753ee8 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -9,6 +9,7 @@ import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder @@ -490,9 +491,11 @@ class MedtronicHistoryData @Inject constructor( if (!multiwave) { val entryWithTempId = findDbEntry(bolus, boluses) - aapsLogger.debug(LTag.PUMP, String.format("DD: entryWithTempId=%s", gson.toJson(entryWithTempId))) + aapsLogger.debug(LTag.PUMP, String.format("DD: entryWithTempId=%s", entryWithTempId)) if (entryWithTempId != null) { + aapsLogger.debug(LTag.PUMP, String.format("DD: entryWithTempId.bolusData=%s", if (entryWithTempId.bolusData == null) "null" else entryWithTempId.bolusData)) + temporaryId = entryWithTempId.temporaryId pumpSyncStorage.removeBolusWithTemporaryId(temporaryId) boluses.remove(entryWithTempId) @@ -725,7 +728,7 @@ class MedtronicHistoryData @Inject constructor( /** * Looks at all boluses that have temporaryId and find one that is correct for us (if such entry exists) */ - private fun findDbEntry(treatment: PumpHistoryEntry, temporaryEntries: MutableList): info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry? { + private fun findDbEntry(treatment: PumpHistoryEntry, temporaryEntries: MutableList): PumpDbEntry? { if (temporaryEntries.isEmpty()) { return null diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt index 8084d52cd6..66ab54cb7b 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt @@ -97,7 +97,11 @@ class PumpSyncStorage @Inject constructor( if (result && writeToInternalHistory) { val innerList: MutableList = pumpSyncStorage[BOLUS]!! - innerList.add(PumpDbEntry(temporaryId, detailedBolusInfo.timestamp, creator.model(), creator.serialNumber(), detailedBolusInfo)) + val dbEntry = PumpDbEntry(temporaryId, detailedBolusInfo.timestamp, creator.model(), creator.serialNumber(), detailedBolusInfo) + + aapsLogger.debug("PumpDbEntry: $dbEntry") + + innerList.add(dbEntry) pumpSyncStorage[BOLUS] = innerList saveStorage() } From ae7bf5ba42b6dd8b3902dff00591e8473b70cf72 Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Sun, 6 Jun 2021 22:11:37 +0100 Subject: [PATCH 26/91] - logging in pumpStorage --- .../androidaps/plugins/pump/common/sync/PumpSyncStorage.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt index 66ab54cb7b..874843015b 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpSyncStorage.kt @@ -46,7 +46,9 @@ class PumpSyncStorage @Inject constructor( if (!jsonData.isBlank()) { pumpSyncStorage = xstream.fromXML(jsonData, MutableMap::class.java) as MutableMap> - aapsLogger.debug(String.format("Loading Pump Sync Storage: boluses=%d, tbrs=%d.", pumpSyncStorage[BOLUS]!!.size, pumpSyncStorage[TBR]!!.size)) + aapsLogger.debug(LTag.PUMP, String.format("Loading Pump Sync Storage: boluses=%d, tbrs=%d.", pumpSyncStorage[BOLUS]!!.size, pumpSyncStorage[TBR]!!.size)) + aapsLogger.debug(LTag.PUMP, "DD: PumpSyncStorage=$pumpSyncStorage") + loaded = true } } From b1f28106ec7840baf2b1a05bd67235761231e240 Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Sun, 6 Jun 2021 22:54:35 +0100 Subject: [PATCH 27/91] - log fixing --- .../plugins/pump/medtronic/data/MedtronicHistoryData.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index 28ce753ee8..f5a2ce8135 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -491,7 +491,7 @@ class MedtronicHistoryData @Inject constructor( if (!multiwave) { val entryWithTempId = findDbEntry(bolus, boluses) - aapsLogger.debug(LTag.PUMP, String.format("DD: entryWithTempId=%s", entryWithTempId)) + aapsLogger.debug(LTag.PUMP, "DD: entryWithTempId=$entryWithTempId") if (entryWithTempId != null) { aapsLogger.debug(LTag.PUMP, String.format("DD: entryWithTempId.bolusData=%s", if (entryWithTempId.bolusData == null) "null" else entryWithTempId.bolusData)) From 6c81770c4d4f832df1b1c8b26ee6e9683e5e45bf Mon Sep 17 00:00:00 2001 From: Andy Rozman Date: Mon, 7 Jun 2021 23:18:46 +0100 Subject: [PATCH 28/91] - fix of logging (logging throws exception ATM) --- .../pump/medtronic/data/MedtronicHistoryData.kt | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index f5a2ce8135..5c8fa3750f 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -629,17 +629,12 @@ class MedtronicHistoryData @Inject constructor( aapsLogger.debug(LTag.PUMP, String.format("DD: tempIdEntry=%s, tbrEntry=%s, tempBasalProcessDTO=%s, pumpType=%s, serial=%s", gson.toJson(entryWithTempId), gson.toJson(tbrEntry), gson.toJson(tempBasalProcessDTO), medtronicPumpStatus.pumpType, medtronicPumpStatus.serialNumber)) - aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "BEFORE syncTemporaryBasalWithTempId " + - "[date=%d, dateProcess=%d, tbrEntry.insulinRate=%d, duration=%d, isAbsolute=%b, temporaryId=%d, pumpId=%d, pumpType=%s, pumpSerial=%s]", - tempBasalProcessDTO.atechDateTime, - tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), - tbrEntry.insulinRate, - tempBasalProcessDTO.duration * 60L * 1000L, - !tbrEntry.isPercent, - entryWithTempId.temporaryId, - tempBasalProcessDTO.pumpId, - medtronicPumpStatus.pumpType, - medtronicPumpStatus.serialNumber)) + aapsLogger.debug(LTag.PUMP, "BEFORE syncTemporaryBasalWithTempId " + + "[date=${tempBasalProcessDTO.atechDateTime}, dateProcess=${tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime)}, " + + "tbrEntry.insulinRate=${tbrEntry.insulinRate}, duration=${tempBasalProcessDTO.duration * 60L * 1000L}, " + + "isAbsolute=${!tbrEntry.isPercent}, temporaryId=${entryWithTempId.temporaryId}, " + + "pumpId=${tempBasalProcessDTO.pumpId}, pumpType=${medtronicPumpStatus.pumpType}, " + + "pumpSerial=${medtronicPumpStatus.serialNumber}]") val result = pumpSync.syncTemporaryBasalWithTempId( tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), From 39667b86742eadf50bf2598e9672b7832c416aa8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 8 Jun 2021 07:27:23 +0000 Subject: [PATCH 29/91] Bump xstream from 1.4.7 to 1.4.17 Bumps [xstream](https://github.com/x-stream/xstream) from 1.4.7 to 1.4.17. - [Release notes](https://github.com/x-stream/xstream/releases) - [Commits](https://github.com/x-stream/xstream/commits) Signed-off-by: dependabot[bot] --- pump-common/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pump-common/build.gradle b/pump-common/build.gradle index 996daf31dd..4661d58948 100644 --- a/pump-common/build.gradle +++ b/pump-common/build.gradle @@ -18,7 +18,7 @@ dependencies { implementation project(':core') //implementation project(':database') - implementation('com.thoughtworks.xstream:xstream:1.4.7') { + implementation('com.thoughtworks.xstream:xstream:1.4.17') { exclude group: 'xmlpull', module: 'xmlpull' } } From 8e466be92cb66f531bac6f3bce14b818b30a1325 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 8 Jun 2021 23:27:14 +0200 Subject: [PATCH 30/91] Diaconn support --- app/build.gradle | 1 + .../activities/MyPreferenceFragment.kt | 3 + .../dependencyInjection/AppComponent.kt | 4 +- .../dependencyInjection/PluginsModule.kt | 7 + .../general/actions/ActionsFragment.kt | 7 +- .../profile/local/LocalProfileFragment.kt | 2 +- .../queue/commands/CommandLoadEvents.kt | 8 + .../queue/commands/CommandLoadHistory.kt | 8 + .../queue/commands/CommandSetUserSettings.kt | 7 + .../androidaps/activities/TDDStatsActivity.kt | 2 +- .../androidaps/interfaces/Diaconn.kt | 8 + .../plugins/common/ManufacturerType.kt | 3 +- .../pump/common/defs/PumpCapability.kt | 1 + .../plugins/pump/common/defs/PumpType.kt | 19 +- .../database/embedments/InterfaceIDs.kt | 1 + diaconn/build.gradle | 30 + diaconn/consumer-rules.pro | 0 diaconn/proguard-rules.pro | 21 + .../1.json | 92 + diaconn/src/main/AndroidManifest.xml | 22 + .../androidaps/diaconn/DiaconnG8Fragment.kt | 197 + .../androidaps/diaconn/DiaconnG8Plugin.kt | 583 ++ .../androidaps/diaconn/DiaconnG8Pump.kt | 333 + .../activities/DiaconnG8BLEScanActivity.kt | 184 + .../activities/DiaconnG8HistoryActivity.kt | 257 + .../DiaconnG8UserOptionsActivity.kt | 192 + .../androidaps/diaconn/common/RecordTypes.kt | 11 + .../database/DiaconnHistoryDatabase.kt | 32 + .../diaconn/database/DiaconnHistoryRecord.kt | 19 + .../database/DiaconnHistoryRecordDao.kt | 17 + .../diaconn/di/DiaconnG8ActivitiesModule.kt | 17 + .../androidaps/diaconn/di/DiaconnG8Module.kt | 12 + .../diaconn/di/DiaconnG8PacketModule.kt | 81 + .../diaconn/di/DiaconnG8ServiceModule.kt | 11 + .../diaconn/di/DiaconnHistoryModule.kt | 21 + .../events/EventDiaconnG8DeviceChange.kt | 5 + .../diaconn/events/EventDiaconnG8NewStatus.kt | 5 + .../diaconn/packet/AppCancelSettingPacket.kt | 32 + .../packet/AppCancelSettingResponsePacket.kt | 44 + .../diaconn/packet/AppConfirmSettingPacket.kt | 39 + .../packet/AppConfirmSettingResponsePacket.kt | 43 + .../diaconn/packet/BasalLimitInquirePacket.kt | 30 + .../packet/BasalLimitInquireResponsePacket.kt | 44 + .../diaconn/packet/BasalPauseReportPacket.kt | 37 + .../diaconn/packet/BasalPauseSettingPacket.kt | 32 + .../packet/BasalPauseSettingResponsePacket.kt | 48 + .../diaconn/packet/BasalSettingPacket.kt | 54 + .../packet/BasalSettingReportPacket.kt | 40 + .../packet/BasalSettingResponsePacket.kt | 46 + .../packet/BatteryWarningReportPacket.kt | 44 + .../diaconn/packet/BigLogInquirePacket.kt | 35 + .../packet/BigLogInquireResponsePacket.kt | 774 +++ .../packet/BigMainInfoInquirePacket.kt | 33 + .../BigMainInfoInquireResponsePacket.kt | 359 + .../diaconn/packet/BolusSpeedInquirePacket.kt | 27 + .../packet/BolusSpeedInquireResponsePacket.kt | 49 + .../diaconn/packet/BolusSpeedSettingPacket.kt | 32 + .../packet/BolusSpeedSettingReportPacket.kt | 40 + .../packet/BolusSpeedSettingResponsePacket.kt | 47 + .../diaconn/packet/ConfirmReportPacket.kt | 38 + .../diaconn/packet/DiaconnG8Packet.java | 300 + .../DiaconnG8ResponseMessageHashTable.kt | 52 + ...iaconnG8SettingResponseMessageHashTable.kt | 36 + .../packet/DisplayTimeInquirePacket.kt | 30 + .../DisplayTimeInquireResponsePacket.kt | 45 + .../packet/DisplayTimeoutSettingPacket.kt | 32 + .../DisplayTimeoutSettingResponsePacket.kt | 46 + .../packet/IncarnationInquirePacket.kt | 29 + .../IncarnationInquireResponsePacket.kt | 50 + .../packet/InjectionBasalReportPacket.kt | 37 + .../packet/InjectionBasalSettingPacket.kt | 31 + .../InjectionBasalSettingResponsePacket.kt | 47 + .../packet/InjectionBlockReportPacket.kt | 45 + .../packet/InjectionCancelSettingPacket.kt | 32 + .../InjectionCancelSettingResponsePacket.kt | 46 + ...njectionExtendedBolusResultReportPacket.kt | 59 + .../InjectionExtendedBolusSettingPacket.kt | 35 + ...ctionExtendedBolusSettingResponsePacket.kt | 46 + .../packet/InjectionMealSettingPacket.kt | 33 + .../InjectionMealSettingResponsePacket.kt | 46 + .../packet/InjectionSnackInquirePacket.kt | 26 + .../InjectionSnackInquireResponsePacket.kt | 51 + .../InjectionSnackResultReportPacket.kt | 60 + .../packet/InjectionSnackSettingPacket.kt | 31 + .../InjectionSnackSettingResponsePacket.kt | 46 + .../diaconn/packet/InsulinLackReportPacket.kt | 44 + .../diaconn/packet/LanguageInquirePacket.kt | 30 + .../packet/LanguageInquireResponsePacket.kt | 44 + .../diaconn/packet/LanguageSettingPacket.kt | 32 + .../packet/LanguageSettingResponsePacket.kt | 47 + .../diaconn/packet/LogStatusInquirePacket.kt | 28 + .../packet/LogStatusInquireResponsePacket.kt | 49 + .../diaconn/packet/RejectReportPacket.kt | 41 + .../diaconn/packet/SneckLimitInquirePacket.kt | 30 + .../packet/SneckLimitInquireResponsePacket.kt | 47 + .../diaconn/packet/SoundInquirePacket.kt | 30 + .../packet/SoundInquireResponsePacket.kt | 47 + .../diaconn/packet/SoundSettingPacket.kt | 34 + .../packet/SoundSettingResponsePacket.kt | 47 + .../diaconn/packet/TempBasalInquirePacket.kt | 29 + .../packet/TempBasalInquireResponsePacket.kt | 60 + .../diaconn/packet/TempBasalReportPacket.kt | 58 + .../diaconn/packet/TempBasalSettingPacket.kt | 44 + .../packet/TempBasalSettingResponsePacket.kt | 47 + .../diaconn/packet/TimeInquirePacket.kt | 30 + .../packet/TimeInquireResponsePacket.kt | 41 + .../diaconn/packet/TimeReportPacket.kt | 49 + .../diaconn/packet/TimeSettingPacket.kt | 43 + .../packet/TimeSettingResponsePacket.kt | 47 + .../diaconn/pumplog/LOG_ALARM_BATTERY.kt | 53 + .../diaconn/pumplog/LOG_ALARM_BLOCK.kt | 59 + .../diaconn/pumplog/LOG_ALARM_SHORTAGE.kt | 56 + .../pumplog/LOG_CHANGE_INJECTOR_SUCCESS.kt | 53 + .../pumplog/LOG_CHANGE_NEEDLE_SUCCESS.kt | 53 + .../pumplog/LOG_CHANGE_TUBE_SUCCESS.kt | 53 + .../diaconn/pumplog/LOG_INJECTION_1DAY.kt | 53 + .../pumplog/LOG_INJECTION_1DAY_BASAL.kt | 49 + .../pumplog/LOG_INJECTION_1HOUR_BASAL.kt | 61 + .../pumplog/LOG_INJECTION_DUAL_NORMAL.kt | 60 + .../diaconn/pumplog/LOG_INJECT_DUAL_FAIL.kt | 64 + .../pumplog/LOG_INJECT_DUAL_SUCCESS.kt | 60 + .../diaconn/pumplog/LOG_INJECT_MEAL_FAIL.kt | 64 + .../pumplog/LOG_INJECT_MEAL_SUCCESS.kt | 64 + .../diaconn/pumplog/LOG_INJECT_NORMAL_FAIL.kt | 64 + .../pumplog/LOG_INJECT_NORMAL_SUCCESS.kt | 60 + .../diaconn/pumplog/LOG_INJECT_SQUARE_FAIL.kt | 61 + .../pumplog/LOG_INJECT_SQUARE_SUCCESS.kt | 57 + .../diaconn/pumplog/LOG_RESET_SYS_V3.kt | 56 + .../diaconn/pumplog/LOG_SET_DUAL_INJECTION.kt | 60 + .../pumplog/LOG_SET_SQUARE_INJECTION.kt | 57 + .../diaconn/pumplog/LOG_SUSPEND_RELEASE_V2.kt | 71 + .../diaconn/pumplog/LOG_SUSPEND_V2.kt | 63 + .../diaconn/pumplog/LOG_TB_START_V3.kt | 61 + .../diaconn/pumplog/LOG_TB_STOP_V3.kt | 64 + .../diaconn/pumplog/PumplogUtil.java | 157 + .../diaconn/service/BLECommonService.kt | 367 + .../diaconn/service/DiaconnG8Service.kt | 641 ++ .../src/main/res/drawable/ic_diaconn_g8.xml | 6100 +++++++++++++++++ .../layout/diaconn_g8_blescanner_activity.xml | 51 + .../res/layout/diaconn_g8_blescanner_item.xml | 27 + .../main/res/layout/diaconn_g8_fragment.xml | 714 ++ .../layout/diaconn_g8_history_activity.xml | 94 + .../res/layout/diaconn_g8_history_item.xml | 90 + .../diaconn_g8_user_options_activity.xml | 336 + .../src/main/res/values-ko-rKR/strings.xml | 143 + diaconn/src/main/res/values/arrays.xml | 48 + diaconn/src/main/res/values/colors.xml | 10 + diaconn/src/main/res/values/ids.xml | 12 + diaconn/src/main/res/values/strings.xml | 166 + diaconn/src/main/res/values/themes.xml | 16 + diaconn/src/main/res/xml/pref_diaconn.xml | 50 + settings.gradle | 1 + 152 files changed, 16972 insertions(+), 6 deletions(-) create mode 100644 core/src/main/java/info/nightscout/androidaps/interfaces/Diaconn.kt create mode 100644 diaconn/build.gradle create mode 100644 diaconn/consumer-rules.pro create mode 100644 diaconn/proguard-rules.pro create mode 100644 diaconn/schemas/info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase/1.json create mode 100644 diaconn/src/main/AndroidManifest.xml create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Pump.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/common/RecordTypes.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryDatabase.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecord.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecordDao.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ActivitiesModule.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8Module.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8PacketModule.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ServiceModule.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnHistoryModule.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8DeviceChange.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8NewStatus.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BatteryWarningReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/ConfirmReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8Packet.java create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8ResponseMessageHashTable.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8SettingResponseMessageHashTable.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBlockReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InsulinLackReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/RejectReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquirePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquireResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeReportPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingPacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingResponsePacket.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BATTERY.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BLOCK.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_SHORTAGE.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_INJECTOR_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_NEEDLE_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_TUBE_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY_BASAL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1HOUR_BASAL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_DUAL_NORMAL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_FAIL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_FAIL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_FAIL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_FAIL.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_SUCCESS.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_RESET_SYS_V3.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_DUAL_INJECTION.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_SQUARE_INJECTION.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_RELEASE_V2.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_V2.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_START_V3.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_STOP_V3.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/PumplogUtil.java create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt create mode 100644 diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt create mode 100644 diaconn/src/main/res/drawable/ic_diaconn_g8.xml create mode 100644 diaconn/src/main/res/layout/diaconn_g8_blescanner_activity.xml create mode 100644 diaconn/src/main/res/layout/diaconn_g8_blescanner_item.xml create mode 100644 diaconn/src/main/res/layout/diaconn_g8_fragment.xml create mode 100644 diaconn/src/main/res/layout/diaconn_g8_history_activity.xml create mode 100644 diaconn/src/main/res/layout/diaconn_g8_history_item.xml create mode 100644 diaconn/src/main/res/layout/diaconn_g8_user_options_activity.xml create mode 100644 diaconn/src/main/res/values-ko-rKR/strings.xml create mode 100644 diaconn/src/main/res/values/arrays.xml create mode 100644 diaconn/src/main/res/values/colors.xml create mode 100644 diaconn/src/main/res/values/ids.xml create mode 100644 diaconn/src/main/res/values/strings.xml create mode 100644 diaconn/src/main/res/values/themes.xml create mode 100644 diaconn/src/main/res/xml/pref_diaconn.xml diff --git a/app/build.gradle b/app/build.gradle index 85354209ff..21658892cf 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -192,6 +192,7 @@ dependencies { implementation project(':omnipod-common') implementation project(':omnipod-eros') implementation project(':omnipod-dash') + implementation project(':diaconn') implementation fileTree(include: ['*.jar'], dir: 'libs') 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 e7ea847509..4c253c55f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -14,6 +14,7 @@ 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.diaconn.DiaconnG8Plugin import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventRebuildTabs @@ -99,6 +100,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var passwordCheck: PasswordCheck @Inject lateinit var nsSettingStatus: NSSettingsStatus @Inject lateinit var openHumansUploader: OpenHumansUploader + @Inject lateinit var diaconnG8Plugin: DiaconnG8Plugin override fun onAttach(context: Context) { AndroidSupportInjection.inject(this) @@ -173,6 +175,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(diaconnG8Plugin, rootKey, config.PUMPDRIVERS) addPreferencesFromResource(R.xml.pref_pump, rootKey, config.PUMPDRIVERS) addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey) addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, rootKey) 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 5b74972932..5432082ada 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -13,6 +13,7 @@ import info.nightscout.androidaps.danar.di.DanaRModule import info.nightscout.androidaps.danars.di.DanaRSModule import info.nightscout.androidaps.database.DatabaseModule import info.nightscout.androidaps.di.CoreModule +import info.nightscout.androidaps.diaconn.di.DiaconnG8Module import info.nightscout.androidaps.insight.di.InsightDatabaseModule import info.nightscout.androidaps.insight.di.InsightModule import info.nightscout.androidaps.plugins.pump.common.di.PumpCommonModule @@ -56,7 +57,8 @@ import javax.inject.Singleton InsightModule::class, InsightDatabaseModule::class, WorkersModule::class, - OHUploaderModule::class + OHUploaderModule::class, + DiaconnG8Module::class ] ) interface AppComponent : AndroidInjector { 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 40bce88096..7b467893d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -8,6 +8,7 @@ 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.diaconn.DiaconnG8Plugin import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin @@ -158,6 +159,12 @@ abstract class PluginsModule { // @IntKey(155) // abstract fun bindOmnipodPumpPlugin(plugin: OmnipodErosPumpPlugin): PluginBase + @Binds + @PumpDriver + @IntoMap + @IntKey(155) + abstract fun bindDiaconnG8Plugin(plugin: DiaconnG8Plugin): PluginBase + @Binds @NotNSClient @IntoMap 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 8ffbd696ee..60fc700dcf 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 @@ -29,6 +29,7 @@ import info.nightscout.androidaps.extensions.toStringMedium import info.nightscout.androidaps.extensions.toStringShort import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.activities.HistoryBrowseActivity +import info.nightscout.androidaps.diaconn.DiaconnG8Plugin import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Config @@ -304,7 +305,11 @@ class ActionsFragment : DaggerFragment() { val activeBgSource = activePlugin.activeBgSource historyBrowser?.visibility = (profile != null).toVisibility() fill?.visibility = (pump.pumpDescription.isRefillingCapable && pump.isInitialized() && !pump.isSuspended()).toVisibility() - pumpBatteryChange?.visibility = (pump.pumpDescription.isBatteryReplaceable || (pump is OmnipodErosPumpPlugin && pump.isUseRileyLinkBatteryLevel && pump.isBatteryChangeLoggingEnabled)).toVisibility() + if(pump is DiaconnG8Plugin) { + pumpBatteryChange?.visibility = (pump.pumpDescription.isBatteryReplaceable && !pump.isBatteryChangeLoggingEnabled()).toVisibility() + } else { + pumpBatteryChange?.visibility = (pump.pumpDescription.isBatteryReplaceable || (pump is OmnipodErosPumpPlugin && pump.isUseRileyLinkBatteryLevel && pump.isBatteryChangeLoggingEnabled)).toVisibility() + } tempTarget?.visibility = (profile != null && config.APS).toVisibility() tddStats?.visibility = pump.pumpDescription.supportsTDDs.toVisibility() 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 0b11136ed1..1d2eb8f84e 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 @@ -129,7 +129,7 @@ class LocalProfileFragment : DaggerFragment() { binding.dia.setParams(currentProfile.dia, hardLimits.minDia(), hardLimits.maxDia(), 0.1, DecimalFormat("0.0"), false, binding.save, textWatch) binding.dia.tag = "LP_DIA" TimeListEdit(context, aapsLogger, dateUtil, view, R.id.ic, "IC", resourceHelper.gs(R.string.ic_label), currentProfile.ic, null, hardLimits.minIC(), hardLimits.maxIC(), 0.1, DecimalFormat("0.0"), save) - basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.basal_holder, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), currentProfile.basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) + basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.basal_holder, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), currentProfile.basal, null, pumpDescription.basalMinimumRate, pumpDescription.basalMaximumRate, 0.01, DecimalFormat("0.00"), save) if (units == Constants.MGDL) { TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf, "ISF", resourceHelper.gs(R.string.isf_label), currentProfile.isf, null, HardLimits.MIN_ISF, HardLimits.MAX_ISF, 1.0, DecimalFormat("0"), save) TimeListEdit(context, aapsLogger, dateUtil, view, R.id.target, "TARGET", resourceHelper.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, HardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), HardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt index f959eff033..58a0570eaf 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.queue.commands import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.Dana +import info.nightscout.androidaps.interfaces.Diaconn import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.queue.Callback import javax.inject.Inject @@ -22,6 +23,13 @@ class CommandLoadEvents( aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") callback?.result(r)?.run() } + + if (pump is Diaconn) { + val diaconnPump = pump as Diaconn + val r = diaconnPump.loadHistory() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } } override fun status(): String = "LOAD EVENTS" diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt index 431b4fe12e..3ff9c133c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.queue.commands import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.Dana +import info.nightscout.androidaps.interfaces.Diaconn import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.queue.Callback import javax.inject.Inject @@ -23,6 +24,13 @@ class CommandLoadHistory( aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted) callback?.result(r)?.run() } + + if (pump is Diaconn) { + val diaconnG8Pump = pump as Diaconn + val r = diaconnG8Pump.loadHistory() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: " + r.success + " enacted: " + r.enacted) + callback?.result(r)?.run() + } } override fun status(): String = "LOAD HISTORY $type" diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt index abefe7e00e..7460529e67 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.queue.commands import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.Dana +import info.nightscout.androidaps.interfaces.Diaconn import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.queue.Callback import javax.inject.Inject @@ -21,6 +22,12 @@ class CommandSetUserSettings( aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") callback?.result(r)?.run() } + + if (pump is Diaconn) { + val r = pump.setUserOptions() + aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") + callback?.result(r)?.run() + } } override fun status(): String = "SET USER SETTINGS" diff --git a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt index 1015274a08..58b939b2cb 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt @@ -425,7 +425,7 @@ class TDDStatsActivity : NoSplashAppCompatActivity() { private fun isOldData(historyList: List): Boolean { val type = activePlugin.activePump.pumpDescription.pumpType - val startsYesterday = type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT_VIRTUAL + val startsYesterday = type == PumpType.DANA_R || type == PumpType.DANA_RS || type == PumpType.DANA_RV2 || type == PumpType.DANA_R_KOREAN || type == PumpType.ACCU_CHEK_INSIGHT_VIRTUAL || type == PumpType.DIACONN_G8 val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) return historyList.size < 3 || df.format(Date(historyList[0].timestamp)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) } diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/Diaconn.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/Diaconn.kt new file mode 100644 index 0000000000..be3bfa1b87 --- /dev/null +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/Diaconn.kt @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.interfaces + +import info.nightscout.androidaps.data.PumpEnactResult + +interface Diaconn { + fun loadHistory(): PumpEnactResult // for history browser + fun setUserOptions(): PumpEnactResult // pump etc settings +} \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/common/ManufacturerType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/common/ManufacturerType.kt index 47b977e5d8..a7ac2b5596 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/common/ManufacturerType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/common/ManufacturerType.kt @@ -9,5 +9,6 @@ enum class ManufacturerType(val description: String) { Animas("Animas"), Cellnovo("Cellnovo"), Roche("Roche"), - Ypsomed("Ypsomed"); + Ypsomed("Ypsomed"), + G2e("G2e"); } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt index b8e74bb0a6..1ceac452df 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpCapability.kt @@ -23,6 +23,7 @@ enum class PumpCapability { MedtronicCapabilities(arrayOf(Bolus, TempBasal, BasalProfileSet, Refill, ReplaceBattery, TDD)), OmnipodCapabilities(arrayOf(Bolus, TempBasal, BasalProfileSet, BasalRate30min)), YpsomedCapabilities(arrayOf(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, ReplaceBattery, TDD, ManualTDDLoad)), // BasalRates (separately grouped) + DiaconnCapabilities(arrayOf(Bolus, ExtendedBolus, TempBasal, BasalProfileSet, Refill, ReplaceBattery, TDD, ManualTDDLoad)), // BasalRate_Duration15minAllowed, BasalRate_Duration30minAllowed, BasalRate_Duration15and30minAllowed(arrayOf(BasalRate_Duration15minAllowed, BasalRate_Duration30minAllowed)), diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index 387386f927..88d268b6f1 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -284,7 +284,23 @@ enum class PumpType { model = "USER", tbrSettings = DoseSettings(1.0, 15, 24 * 60, 0.0, 500.0), extendedBolusSettings = DoseSettings(0.1, 15, 12 * 60, 0.1), - pumpCapability = PumpCapability.MDI); + pumpCapability = PumpCapability.MDI), + + //Diaconn Pump + DIACONN_G8(description = "DiaconnG8", + manufacturer = ManufacturerType.G2e, + model = "Diaconn G8", + bolusSize = 0.01, + specialBolusSize = null, + extendedBolusSettings = DoseSettings(0.05, 10, 5 * 60, 0.05), + pumpTempBasalType = PumpTempBasalType.Absolute, + tbrSettings = DoseSettings(0.01, 30, 24 * 60, 0.0, 6.0), + specialBasalDurations = PumpCapability.BasalRate_Duration30minAllowed, + baseBasalMinValue = 0.05, + baseBasalMaxValue = 3.0, + baseBasalStep = 0.01, + baseBasalSpecialSteps = null, + pumpCapability = PumpCapability.DanaWithHistoryCapabilities); val description: String var manufacturer: ManufacturerType? = null @@ -444,5 +460,6 @@ enum class PumpType { YPSOPUMP -> InterfaceIDs.PumpType.YPSOPUMP MDI -> InterfaceIDs.PumpType.MDI USER -> InterfaceIDs.PumpType.USER + DIACONN_G8 -> InterfaceIDs.PumpType.DIACONN_G8 } } \ No newline at end of file diff --git a/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt b/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt index beb7eb5184..b06098f4ee 100644 --- a/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt +++ b/database/src/main/java/info/nightscout/androidaps/database/embedments/InterfaceIDs.kt @@ -43,6 +43,7 @@ data class InterfaceIDs( TANDEM_T_SLIM_X2, YPSOPUMP, MDI, + DIACONN_G8, USER; companion object { diff --git a/diaconn/build.gradle b/diaconn/build.gradle new file mode 100644 index 0000000000..6194f079e3 --- /dev/null +++ b/diaconn/build.gradle @@ -0,0 +1,30 @@ +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-kapt' +apply plugin: 'com.hiya.jacoco-android' + +apply from: "${project.rootDir}/gradle/android_dependencies.gradle" +apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle" +apply from: "${project.rootDir}/gradle/test_dependencies.gradle" + +android { + defaultConfig { + versionCode 1 + versionName "1.0" + kapt { + arguments { + arg("room.incremental", "true") + arg("room.schemaLocation", "$projectDir/schemas") + } + } + } +} + +dependencies { + implementation project(':core') + + api "androidx.room:room-ktx:$room_version" + api "androidx.room:room-runtime:$room_version" + api "androidx.room:room-rxjava2:$room_version" + kapt "androidx.room:room-compiler:$room_version" +} \ No newline at end of file diff --git a/diaconn/consumer-rules.pro b/diaconn/consumer-rules.pro new file mode 100644 index 0000000000..e69de29bb2 diff --git a/diaconn/proguard-rules.pro b/diaconn/proguard-rules.pro new file mode 100644 index 0000000000..481bb43481 --- /dev/null +++ b/diaconn/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/diaconn/schemas/info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase/1.json b/diaconn/schemas/info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase/1.json new file mode 100644 index 0000000000..b6e405a524 --- /dev/null +++ b/diaconn/schemas/info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase/1.json @@ -0,0 +1,92 @@ +{ + "formatVersion": 1, + "database": { + "version": 1, + "identityHash": "698b023da2f9efdc0351236c43eb20b6", + "entities": [ + { + "tableName": "diaconnHistory", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`timestamp` INTEGER NOT NULL, `code` INTEGER NOT NULL, `value` REAL NOT NULL, `bolusType` TEXT NOT NULL, `stringValue` TEXT NOT NULL, `duration` INTEGER NOT NULL, `dailyBasal` REAL NOT NULL, `dailyBolus` REAL NOT NULL, `alarm` TEXT NOT NULL, PRIMARY KEY(`timestamp`))", + "fields": [ + { + "fieldPath": "timestamp", + "columnName": "timestamp", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "code", + "columnName": "code", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "bolusType", + "columnName": "bolusType", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "stringValue", + "columnName": "stringValue", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "duration", + "columnName": "duration", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "dailyBasal", + "columnName": "dailyBasal", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "dailyBolus", + "columnName": "dailyBolus", + "affinity": "REAL", + "notNull": true + }, + { + "fieldPath": "alarm", + "columnName": "alarm", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "columnNames": [ + "timestamp" + ], + "autoGenerate": false + }, + "indices": [ + { + "name": "index_diaconnHistory_code_timestamp", + "unique": false, + "columnNames": [ + "code", + "timestamp" + ], + "createSql": "CREATE INDEX IF NOT EXISTS `index_diaconnHistory_code_timestamp` ON `${TABLE_NAME}` (`code`, `timestamp`)" + } + ], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '698b023da2f9efdc0351236c43eb20b6')" + ] + } +} \ No newline at end of file diff --git a/diaconn/src/main/AndroidManifest.xml b/diaconn/src/main/AndroidManifest.xml new file mode 100644 index 0000000000..3ddb6c3a37 --- /dev/null +++ b/diaconn/src/main/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt new file mode 100644 index 0000000000..3e7e9a2e01 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt @@ -0,0 +1,197 @@ +package info.nightscout.androidaps.diaconn + +import android.annotation.SuppressLint +import android.content.Intent +import android.os.Bundle +import android.os.Handler +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import dagger.android.support.DaggerFragment +import info.nightscout.androidaps.activities.TDDStatsActivity +import info.nightscout.androidaps.diaconn.databinding.DiaconnG8FragmentBinding +import info.nightscout.androidaps.diaconn.events.EventDiaconnG8NewStatus +import info.nightscout.androidaps.events.EventExtendedBolusChange +import info.nightscout.androidaps.events.EventInitializationChanged +import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.events.EventTempBasalChange +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.Pump +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.queue.events.EventQueueChanged +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.WarnColors +import io.reactivex.rxkotlin.plusAssign +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import javax.inject.Inject + +class DiaconnG8Fragment : DaggerFragment() { + + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var sp: SP + @Inject lateinit var warnColors: WarnColors + @Inject lateinit var dateUtil: DateUtil + + private var disposable: CompositeDisposable = CompositeDisposable() + + private val loopHandler = Handler() + private lateinit var refreshLoop: Runnable + + private var _binding: DiaconnG8FragmentBinding? = null + + // This property is only valid between onCreateView and + // onDestroyView. + private val binding get() = _binding!! + + init { + refreshLoop = Runnable { + activity?.runOnUiThread { updateGUI() } + loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) + } + } + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View { + _binding = DiaconnG8FragmentBinding.inflate(inflater, container, false) + return binding.root + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + binding.diaconnG8Pumpstatus.setBackgroundColor(resourceHelper.gc(R.color.colorInitializingBorder)) + binding.history.setOnClickListener { startActivity(Intent(context, info.nightscout.androidaps.diaconn.activities.DiaconnG8HistoryActivity::class.java)) } + binding.stats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } + binding.userOptions.setOnClickListener { startActivity(Intent(context, info.nightscout.androidaps.diaconn.activities.DiaconnG8UserOptionsActivity::class.java)) } + binding.btconnection.setOnClickListener { + aapsLogger.debug(LTag.PUMP, "Clicked connect to pump") + diaconnG8Pump.lastConnection = 0 + commandQueue.readStatus("Clicked connect to pump", null) + } + } + + @Synchronized + override fun onResume() { + super.onResume() + loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) + disposable += rxBus + .toObservable(EventInitializationChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventDiaconnG8NewStatus::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventExtendedBolusChange::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventTempBasalChange::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventQueueChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventPumpStatusChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + when (it.status) { + EventPumpStatusChanged.Status.CONNECTING -> + @Suppress("SetTextI18n") + binding.btconnection.text = "{fa-bluetooth-b spin} ${it.secondsElapsed}s" + EventPumpStatusChanged.Status.CONNECTED -> + @Suppress("SetTextI18n") + binding.btconnection.text = "{fa-bluetooth}" + EventPumpStatusChanged.Status.DISCONNECTED -> + @Suppress("SetTextI18n") + binding.btconnection.text = "{fa-bluetooth-b}" + else -> {} + } + if (it.getStatus(resourceHelper) != "") { + binding.diaconnG8Pumpstatus.text = it.getStatus(resourceHelper) + binding.diaconnG8Pumpstatuslayout.visibility = View.VISIBLE + } else { + binding.diaconnG8Pumpstatuslayout.visibility = View.GONE + } + }, fabricPrivacy::logException) + updateGUI() + } + + @Synchronized + override fun onPause() { + super.onPause() + disposable.clear() + loopHandler.removeCallbacks(refreshLoop) + } + + @Synchronized + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + @SuppressLint("SetTextI18n") + @Synchronized + fun updateGUI() { + if (_binding == null) return + val pump = diaconnG8Pump + val plugin: Pump = activePlugin.activePump + if (pump.lastConnection != 0L) { + val agoMsec = System.currentTimeMillis() - pump.lastConnection + val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt() + binding.lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + resourceHelper.gs(R.string.minago, agoMin) + ")" + warnColors.setColor(binding.lastconnection, agoMin.toDouble(), 16.0, 31.0) + } + if (pump.lastBolusTime != 0L) { + val agoMsec = System.currentTimeMillis() - pump.lastBolusTime + val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0 + if (agoHours < 6) + // max 6h back + binding.lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + dateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) + else + binding.lastbolus.text = "" + } + + binding.dailyunits.text = resourceHelper.gs(R.string.reservoirvalue, (pump.todayBaseAmount + pump.todaySnackAmount + pump.todayMealAmount), ((pump.maxBasal.toInt() * 24) + pump.maxBolusePerDay.toInt())) + warnColors.setColor(binding.dailyunits, pump.baseInjAmount, pump.baseAmount * 0.75, pump.baseAmount * 0.9) + binding.basabasalrate.text = pump.baseInjAmount.toString() +" / "+ resourceHelper.gs(R.string.pump_basebasalrate, plugin.baseBasalRate) + + binding.tempbasal.text = diaconnG8Pump.temporaryBasalToString() + binding.extendedbolus.text = diaconnG8Pump.extendedBolusToString() + binding.reservoir.text = resourceHelper.gs(R.string.reservoirvalue, pump.systemRemainInsulin, 307) + warnColors.setColorInverse(binding.reservoir, pump.systemRemainInsulin , 50.0, 20.0) + binding.battery.text = "{fa-battery-" + pump.systemRemainBattery / 25 + "}" + " ("+ pump.systemRemainBattery + " %)" + warnColors.setColorInverse(binding.battery, pump.systemRemainBattery.toDouble(), 51.0, 26.0) + //binding.tdd.text = "basal: " +pump.todayBaseAmount + "/ bolus: "+ (pump.todaySnackAmount + pump.todayMealAmount) + binding.firmware.text = resourceHelper.gs(R.string.diaconn_g8_pump) + "\nVersion: " + pump.majorVersion.toString() + "." + pump.minorVersion.toString() + "\nCountry: "+pump.country.toString() + "\nProductType: "+ pump.productType.toString() + "\nManufacture: " + pump.makeYear + "." + pump.makeMonth + "." + pump.makeDay + binding.basalstep.text = pump.basalStep.toString() + binding.bolusstep.text = pump.bolusStep.toString() + binding.serialNumber.text = pump.serialNo.toString() + val status = commandQueue.spannedStatus() + if (status.toString() == "") { + binding.queue.visibility = View.GONE + } else { + binding.queue.visibility = View.VISIBLE + binding.queue.text = status + } + + binding.userOptions.visibility = View.VISIBLE + } +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt new file mode 100644 index 0000000000..098b3cca9b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt @@ -0,0 +1,583 @@ +package info.nightscout.androidaps.diaconn + +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.ServiceConnection +import android.os.IBinder +import android.text.format.DateFormat +import androidx.preference.Preference +import androidx.preference.PreferenceFragmentCompat +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.diaconn.events.EventDiaconnG8DeviceChange +import info.nightscout.androidaps.diaconn.service.DiaconnG8Service +import info.nightscout.androidaps.events.EventAppExit +import info.nightscout.androidaps.events.EventConfigBuilderChange +import info.nightscout.androidaps.extensions.convertedToAbsolute +import info.nightscout.androidaps.extensions.plannedRemainingMinutes +import info.nightscout.androidaps.interfaces.* +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.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.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.common.bolusInfo.TemporaryBasalStorage +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import org.json.JSONException +import org.json.JSONObject +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.abs +import kotlin.math.max + +@Singleton +class DiaconnG8Plugin @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + private val rxBus: RxBusWrapper, + private val context: Context, + resourceHelper: ResourceHelper, + private val constraintChecker: ConstraintChecker, + private val profileFunction: ProfileFunction, + private val sp: SP, + commandQueue: CommandQueueProvider, + private val diaconnG8Pump: DiaconnG8Pump, + private val pumpSync: PumpSync, + private val detailedBolusInfoStorage: DetailedBolusInfoStorage, + private val temporaryBasalStorage: TemporaryBasalStorage, + private val fabricPrivacy: FabricPrivacy, + private val dateUtil: DateUtil +) : PumpPluginBase(PluginDescription() + .mainType(PluginType.PUMP) + .fragmentClass(DiaconnG8Fragment::class.java.name) + .pluginIcon(R.drawable.ic_diaconn_g8) + .pluginName(R.string.diaconn_g8_pump) + .shortName(R.string.diaconn_g8_pump_shortname) + .preferencesId(R.xml.pref_diaconn) + .description(R.string.description_pump_diaconn_g8), + injector, aapsLogger, resourceHelper, commandQueue +), Pump, Diaconn, Constraints { + + private val disposable = CompositeDisposable() + private var diaconnG8Service: DiaconnG8Service? = null + private var mDeviceAddress = "" + var mDeviceName = "" + override val pumpDescription = PumpDescription(PumpType.DIACONN_G8) + + override fun onStart() { + super.onStart() + val intent = Intent(context, DiaconnG8Service::class.java) + context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE) + disposable.add(rxBus + .toObservable(EventAppExit::class.java) + .observeOn(Schedulers.io()) + .subscribe({ context.unbindService(mConnection) }) { fabricPrivacy.logException(it) } + ) + disposable.add(rxBus + .toObservable(EventConfigBuilderChange::class.java) + .observeOn(Schedulers.io()) + .subscribe { diaconnG8Pump.reset() } + ) + disposable.add(rxBus + .toObservable(EventDiaconnG8DeviceChange::class.java) + .observeOn(Schedulers.io()) + .subscribe({ changePump() }) { fabricPrivacy.logException(it) } + ) + changePump() // load device name + } + + override fun onStop() { + context.unbindService(mConnection) + disposable.clear() + super.onStop() + } + + private val mConnection: ServiceConnection = object : ServiceConnection { + override fun onServiceDisconnected(name: ComponentName) { + aapsLogger.debug(LTag.PUMP, "Service is disconnected") + diaconnG8Service = null + } + + override fun onServiceConnected(name: ComponentName, service: IBinder) { + aapsLogger.debug(LTag.PUMP, "Service is connected") + val mLocalBinder = service as DiaconnG8Service.LocalBinder + diaconnG8Service = mLocalBinder.serviceInstance + } + } + + fun changePump() { + mDeviceAddress = sp.getString(R.string.key_diaconn_g8_address, "") + mDeviceName = sp.getString(R.string.key_diaconn_g8_name, "") + diaconnG8Pump.reset() + commandQueue.readStatus("DeviceChanged", null) + } + + override fun connect(reason: String) { + aapsLogger.debug(LTag.PUMP, "Diaconn G8 connect from: $reason") + if(diaconnG8Service != null && mDeviceAddress != "" && mDeviceName != "") { + val success = diaconnG8Service?.connect(reason, mDeviceAddress) ?: false + if(!success) ToastUtils.showToastInUiThread(context, resourceHelper.gs(R.string.ble_not_supported)) + } + } + + override fun isConnected(): Boolean = diaconnG8Service?.isConnected ?: false + override fun isConnecting(): Boolean = diaconnG8Service?.isConnecting ?: false + override fun isHandshakeInProgress(): Boolean = false + + + override fun disconnect(reason: String) { + aapsLogger.debug(LTag.PUMP, "Diaconn G8 disconnect from: $reason") + diaconnG8Service?.disconnect(reason) + } + + override fun stopConnecting() { + diaconnG8Service?.stopConnecting() + } + + override fun getPumpStatus(reason: String) { + diaconnG8Service?.readPumpStatus() + pumpDescription.basalStep = diaconnG8Pump.basalStep + pumpDescription.bolusStep = diaconnG8Pump.bolusStep + pumpDescription.basalMaximumRate = diaconnG8Pump.maxBasalPerHours + } + + // Diaconn Pump Interface + override fun loadHistory(): PumpEnactResult { + return diaconnG8Service?.loadHistory() ?: PumpEnactResult(injector).success(false) + } + + override fun setUserOptions(): PumpEnactResult { + return diaconnG8Service?.setUserSettings() ?: PumpEnactResult(injector).success(false) + } + + // Constraints interface + override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { + absoluteRate.setIfSmaller(aapsLogger, diaconnG8Pump.maxBasal, resourceHelper.gs(R.string.limitingbasalratio, diaconnG8Pump.maxBasal, resourceHelper.gs(R.string.pumplimit)), this) + return absoluteRate + } + + override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { + percentRate.setIfGreater(aapsLogger, 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this) + percentRate.setIfSmaller(aapsLogger, pumpDescription.maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, pumpDescription.maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this) + return percentRate + } + + override fun applyBolusConstraints(insulin: Constraint): Constraint { + insulin.setIfSmaller(aapsLogger, diaconnG8Pump.maxBolus, resourceHelper.gs(R.string.limitingbolus, diaconnG8Pump.maxBolus, resourceHelper.gs(R.string.pumplimit)), this) + return insulin + } + + override fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { + return applyBolusConstraints(insulin) + } + + // Pump interface + override fun isInitialized(): Boolean = + diaconnG8Pump.lastConnection > 0 && diaconnG8Pump.maxBasal > 0 + + override fun isSuspended(): Boolean = + diaconnG8Pump.basePauseStatus == 1 + + override fun isBusy(): Boolean = + diaconnG8Service?.isConnected ?: false || diaconnG8Service?.isConnecting ?: false + + override fun setNewBasalProfile(profile: Profile): PumpEnactResult { + val result = PumpEnactResult(injector) + if (!isInitialized()) { + val notification = Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT) + rxBus.send(EventNewNotification(notification)) + result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet) + return result + } else { + rxBus.send(EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)) + } + return if (diaconnG8Service?.updateBasalsInPump(profile) != true) { + val notification = Notification(Notification.FAILED_UPDATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT) + rxBus.send(EventNewNotification(notification)) + result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile) + result + } else { + rxBus.send(EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)) + rxBus.send(EventDismissNotification(Notification.FAILED_UPDATE_PROFILE)) + val notification = Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60) + rxBus.send(EventNewNotification(notification)) + result.success = true + result.enacted = true + result.comment = "OK" + result + } + } + + override fun isThisProfileSet(profile: Profile): Boolean { + if (!isInitialized()) return true // TODO: not sure what's better. so far TRUE to prevent too many SMS + if (diaconnG8Pump.pumpProfiles == null) return true // TODO: not sure what's better. so far TRUE to prevent too many SMS + val basalValues = 24 + val basalIncrement = 60 * 60 + for (h in 0 until basalValues) { + val pumpValue = diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][h] + val profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement) + if (abs(pumpValue - profileValue) > pumpDescription.basalStep) { + aapsLogger.debug(LTag.PUMP, "Diff found. Hour: $h Pump: $pumpValue Profile: $profileValue") + return false + } + } + return true + } + + override fun lastDataTime(): Long = diaconnG8Pump.lastConnection + + override val baseBasalRate: Double + get() = diaconnG8Pump.baseAmount + override val reservoirLevel: Double + get() = diaconnG8Pump.systemRemainInsulin + override val batteryLevel: Int + get() = diaconnG8Pump.systemRemainBattery + + + @Synchronized + override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { + detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value() + return if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { + val carbs = detailedBolusInfo.carbs + detailedBolusInfo.carbs = 0.0 + var carbTimeStamp = detailedBolusInfo.carbsTimestamp ?: detailedBolusInfo.timestamp + if (carbTimeStamp == detailedBolusInfo.timestamp) carbTimeStamp -= T.mins(1).msecs() // better set 1 min back to prevents clash with insulin + detailedBolusInfoStorage.add(detailedBolusInfo) // will be picked up on reading history + val t = EventOverviewBolusProgress.Treatment(0.0, 0, detailedBolusInfo.bolusType == DetailedBolusInfo.BolusType.SMB) + var connectionOK = false + if (detailedBolusInfo.insulin > 0 || carbs > 0) connectionOK = diaconnG8Service?.bolus(detailedBolusInfo.insulin, carbs.toInt(), carbTimeStamp, t) + ?: false + val result = PumpEnactResult(injector) + result.success = connectionOK + result.bolusDelivered = t.insulin + result.carbsDelivered = detailedBolusInfo.carbs + + if(result.success) result.enacted = true + if (!result.success) { + setErrorMsg(diaconnG8Pump.bolusStartErrorCode, result) + } else result.comment = resourceHelper.gs(R.string.ok) + aapsLogger.debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered) + result + } else { + val result = PumpEnactResult(injector) + result.success = false + result.bolusDelivered = 0.0 + result.carbsDelivered = 0.0 + result.comment = resourceHelper.gs(R.string.invalidinput) + aapsLogger.error("deliverTreatment: Invalid input") + result + } + } + + override fun stopBolusDelivering() { + diaconnG8Service?.bolusStop() + } + + // This is called from APS + @Synchronized + override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { + val result = PumpEnactResult(injector) + var absoluteAfterConstrain = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value() + val doTempOff = baseBasalRate - absoluteAfterConstrain == 0.0 + val doLowTemp = absoluteAfterConstrain < baseBasalRate + val doHighTemp = absoluteAfterConstrain > baseBasalRate + if (doTempOff) { + // If temp in progress + if (diaconnG8Pump.isTempBasalInProgress) { + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doTempOff)") + return cancelTempBasal(false) + } + result.success = true + result.enacted = false + result.absolute = baseBasalRate + result.isPercent = false + result.isTempCancel = true + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: doTempOff OK") + return result + } + + if (doLowTemp || doHighTemp) { + // Check if some temp is already in progress + if(absoluteAfterConstrain > 6.0) absoluteAfterConstrain = 6.0 // pumpLimit + //val activeTemp = activePluginProvider.activeTreatments.getTempBasalFromHistory(System.currentTimeMillis()) + if (diaconnG8Pump.isTempBasalInProgress) { + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: currently running") + // Correct basal already set ? + if (diaconnG8Pump.tempBasalAbsoluteRate == absoluteAfterConstrain && diaconnG8Pump.tempBasalRemainingMin > 4) { + if (!enforceNew) { + result.success = true + result.absolute = absoluteAfterConstrain + result.enacted = false + result.duration = diaconnG8Pump.tempBasalRemainingMin + result.isPercent = false + result.isTempCancel = false + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)") + return result + } + } + } + temporaryBasalStorage.add(PumpSync.PumpState.TemporaryBasal(dateUtil.now(), T.mins(durationInMinutes.toLong()).msecs(), absoluteRate, true, tbrType, 0L, 0L)) + // Convert duration from minutes to hours + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal $absoluteAfterConstrain% for $durationInMinutes mins (doLowTemp || doHighTemp)") + val connectionOK: Boolean = if (durationInMinutes == 15 || durationInMinutes == 30) { + diaconnG8Service?.tempBasalShortDuration(absoluteAfterConstrain, durationInMinutes) ?: false + } else { + val durationInHours = max(durationInMinutes / 60, 1) + diaconnG8Service?.tempBasal(absoluteAfterConstrain, durationInHours) ?: false + } + + if (connectionOK && diaconnG8Pump.isTempBasalInProgress && diaconnG8Pump.tempBasalAbsoluteRate == absoluteAfterConstrain) { + result.enacted = true + result.success = true + result.comment = resourceHelper.gs(R.string.ok) + result.isTempCancel = false + result.duration = diaconnG8Pump.tempBasalRemainingMin + result.absolute = diaconnG8Pump.tempBasalAbsoluteRate + result.isPercent = false + aapsLogger.debug(LTag.PUMP, "setTempBasalAbsolute: OK") + return result + } + } + + result.enacted = false + result.success = false + result.comment = resourceHelper.gs(R.string.tempbasaldeliveryerror) + aapsLogger.error("setTempBasalAbsolute: Failed to set temp basal") + return result + } + + @Synchronized + override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean, tbrType: PumpSync.TemporaryBasalType): PumpEnactResult { + return if (percent == 0) { + setTempBasalAbsolute(0.0, durationInMinutes, profile, enforceNew, tbrType) + } else { + var absoluteValue = profile.getBasal() * (percent / 100.0) + absoluteValue = pumpDescription.pumpType.determineCorrectBasalSize(absoluteValue) + aapsLogger.warn(LTag.PUMP, "setTempBasalPercent [DiaconnG8Plugin] - You are trying to use setTempBasalPercent with percent other then 0% ($percent). This will start setTempBasalAbsolute, with calculated value ($absoluteValue). Result might not be 100% correct.") + setTempBasalAbsolute(absoluteValue, durationInMinutes, profile, enforceNew, tbrType) + } + + } + + @Synchronized + override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { + var insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + // needs to be rounded + //val durationInHalfHours = max(durationInMinutes / 30, 1) + insulinAfterConstraint = Round.roundTo(insulinAfterConstraint, pumpDescription.extendedBolusStep) + val result = PumpEnactResult(injector) + + if (diaconnG8Pump.isExtendedInProgress && abs(diaconnG8Pump.extendedBolusAmount - insulinAfterConstraint) < pumpDescription.extendedBolusStep) { + result.enacted = false + result.success = true + result.comment = resourceHelper.gs(R.string.ok) + result.duration = diaconnG8Pump.extendedBolusRemainingMinutes + result.absolute = diaconnG8Pump.extendedBolusAbsoluteRate + result.isPercent = false + result.isTempCancel = false + aapsLogger.debug(LTag.PUMP, "setExtendedBolus: Correct extended bolus already set. Current: " + diaconnG8Pump.extendedBolusAmount + " Asked: " + insulinAfterConstraint) + return result + } + val connectionOK = diaconnG8Service?.extendedBolus(insulinAfterConstraint, durationInMinutes) + ?: false + + if (connectionOK) { + result.enacted = true + result.success = true + result.comment = resourceHelper.gs(R.string.ok) + result.isTempCancel = false + result.duration = diaconnG8Pump.extendedBolusRemainingMinutes + result.absolute = diaconnG8Pump.extendedBolusAbsoluteRate + result.bolusDelivered = diaconnG8Pump.extendedBolusAmount + result.isPercent = false + aapsLogger.debug(LTag.PUMP, "setExtendedBolus: OK") + return result + } + + result.enacted = false + result.success = false + setErrorMsg(diaconnG8Pump.bolusStartErrorCode, result) + aapsLogger.error("setExtendedBolus: Failed to extended bolus") + return result + } + + @Synchronized + override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { + val result = PumpEnactResult(injector) + if (diaconnG8Pump.isTempBasalInProgress) { + diaconnG8Service?.tempBasalStop() + result.success = !diaconnG8Pump.isTempBasalInProgress + result.enacted = true + result.isTempCancel = true + } else { + result.success = true + result.enacted = false + result.isTempCancel = true + result.comment = resourceHelper.gs(R.string.ok) + aapsLogger.debug(LTag.PUMP, "cancelRealTempBasal: OK") + } + return result + } + + @Synchronized override fun cancelExtendedBolus(): PumpEnactResult { + val result = PumpEnactResult(injector) + if (diaconnG8Pump.isExtendedInProgress) { + diaconnG8Service?.extendedBolusStop() + result.success = !diaconnG8Pump.isExtendedInProgress + result.enacted = true + } else { + result.success = true + result.enacted = false + result.comment = resourceHelper.gs(R.string.ok) + aapsLogger.debug(LTag.PUMP, "cancelExtendedBolus: OK") + } + return result + } + + override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject { + val now = System.currentTimeMillis() + if (diaconnG8Pump.lastConnection + 60 * 60 * 1000L < System.currentTimeMillis()) { + return JSONObject() + } + val pumpJson = JSONObject() + val battery = JSONObject() + val status = JSONObject() + val extended = JSONObject() + try { + battery.put("percent", diaconnG8Pump.systemRemainBattery) + status.put("status", if (diaconnG8Pump.pumpSuspended) "suspended" else "normal") + status.put("timestamp", dateUtil.toISOString(diaconnG8Pump.lastConnection)) + extended.put("Version", version) + if (diaconnG8Pump.lastBolusTime != 0L) { + extended.put("LastBolus", dateUtil.dateAndTimeString(diaconnG8Pump.lastBolusTime)) + extended.put("LastBolusAmount", diaconnG8Pump.lastBolusAmount) + } + val tb = pumpSync.expectedPumpState().temporaryBasal + if (tb != null) { + extended.put("TempBasalAbsoluteRate", tb.convertedToAbsolute(now, profile)) + extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.timestamp)) + extended.put("TempBasalRemaining", tb.plannedRemainingMinutes) + } + val eb = pumpSync.expectedPumpState().extendedBolus + if (eb != null) { + extended.put("ExtendedBolusAbsoluteRate", eb.rate) + extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.timestamp)) + extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes) + } + extended.put("BaseBasalRate", baseBasalRate) + try { + extended.put("ActiveProfile", profileFunction.getProfileName()) + } catch (e: Exception) { + aapsLogger.error("Unhandled exception", e) + } + pumpJson.put("battery", battery) + pumpJson.put("status", status) + pumpJson.put("extended", extended) + pumpJson.put("reservoir", diaconnG8Pump.systemRemainInsulin.toInt()) + pumpJson.put("clock", dateUtil.toISOString(now)) + } catch (e: JSONException) { + aapsLogger.error("Unhandled exception", e) + } + return pumpJson + } + + override fun manufacturer(): ManufacturerType { + return ManufacturerType.G2e + } + + override fun model(): PumpType { + return PumpType.DIACONN_G8 + } + + override fun serialNumber(): String { + return diaconnG8Pump.serialNo.toString() + } + + override fun shortStatus(veryShort: Boolean): String { + var ret = "" + if (diaconnG8Pump.lastConnection != 0L) { + val agoMillis = System.currentTimeMillis() - diaconnG8Pump.lastConnection + val agoMin = (agoMillis / 60.0 / 1000.0).toInt() + ret += "LastConn: $agoMin minago\n" + } + if (diaconnG8Pump.lastBolusTime != 0L) + ret += "LastBolus: ${DecimalFormatter.to2Decimal(diaconnG8Pump.lastBolusAmount)}U @${DateFormat.format("HH:mm", diaconnG8Pump.lastBolusTime)}" + + if (diaconnG8Pump.isTempBasalInProgress) + ret += "Temp: ${diaconnG8Pump.temporaryBasalToString()}" + + if (diaconnG8Pump.isExtendedInProgress) + ret += "Extended: ${diaconnG8Pump.extendedBolusToString()}\n" + + if (!veryShort) { + ret += "TDD: ${DecimalFormatter.to0Decimal(diaconnG8Pump.dailyTotalUnits)} / ${diaconnG8Pump.maxDailyTotalUnits} U" + } + ret += "Reserv: ${DecimalFormatter.to0Decimal(diaconnG8Pump.systemRemainInsulin)} U" + ret += "Batt: ${diaconnG8Pump.systemRemainBattery}" + return ret + } + override val isFakingTempsByExtendedBoluses: Boolean = false + override fun loadTDDs(): PumpEnactResult = loadHistory() + override fun getCustomActions(): List? = null + override fun executeCustomAction(customActionType: CustomActionType) {} + override fun canHandleDST(): Boolean = false + + fun isBatteryChangeLoggingEnabled():Boolean { + return sp.getBoolean(R.string.key_diaconn_g8_logbatterychange, false) + } + + fun isInsulinChangeLoggingEnabled():Boolean { + return sp.getBoolean(R.string.key_diaconn_g8_loginsulinchange, false) + } + + @Synchronized + fun setErrorMsg(errorCode: Int, result: PumpEnactResult) { + when (errorCode) { + 1 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_1) + 2 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_2) + 3 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_3) + 4 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_4) + 6 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_6) + 7 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_7) + 8 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_8) + 9 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_9) + 10 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_10) + 11 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_11) + 12 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_12) + 13 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_13) + 14 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_14) + 15 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_15) + else -> result.comment = "not defined Error code: $errorCode" + } + } + + override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { + + val bolusSpeedPreference: Preference? = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_diaconn_g8_bolusspeed)) + bolusSpeedPreference?.setOnPreferenceChangeListener { _, newValue -> + val intBolusSpeed = newValue.toString().toInt() + + diaconnG8Pump.bolusSpeed = intBolusSpeed + diaconnG8Pump.speed = intBolusSpeed + diaconnG8Pump.setUserOptionType = DiaconnG8Pump.BOLUS_SPEED + sp.putBoolean("diaconn_g8_isbolusspeedsync", false) + + true + } + } + +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Pump.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Pump.kt new file mode 100644 index 0000000000..7c89920fc8 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Pump.kt @@ -0,0 +1,333 @@ +package info.nightscout.androidaps.diaconn + + +import info.nightscout.androidaps.interfaces.Profile +import info.nightscout.androidaps.interfaces.PumpSync +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.DecimalFormatter +import info.nightscout.androidaps.utils.T +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt + +@Singleton +class DiaconnG8Pump @Inject constructor( + private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil +) { + + var maxBolusePerDay: Double = 0.0 + var pumpIncarnationNum: Int = 65536 + var isPumpVersionGe2_63: Boolean = false // is pumpVersion higher then 2.63 + var insulinWarningGrade: Int =0 + var insulinWarningProcess: Int =0 + var insulinWarningRemain: Int =0 + var batteryWaningGrade: Int = 0 + var batteryWaningProcess: Int = 0 + var batteryWaningRemain: Int = 0 + var injectionBlockType: Int =0 + var injectionBlockRemainAmount: Double = 0.0 + var injectionBlockProcess: Int = 0 + var injectionBlockGrade: Int = 0 + var lastConnection: Long = 0 + var lastSettingsRead: Long = 0 + + // time + private var pumpTime: Long = 0 + + fun setPumpTime(value: Long) { + pumpTime = value + } + fun getPumpTime() = pumpTime + + // Status + var pumpSuspended = false + var dailyTotalUnits = 0.0 + var maxDailyTotalUnits = 0 + var bolusStep = 0.01 + var basalStep = 0.01 + var iob = 0.0 + + + var bolusBlocked = false + var lastBolusTime: Long = 0 + var lastBolusAmount = 0.0 + var extendedBolusMinutes = 0 + var extendedBolusSoFarInMinutes = 0 + var extendedBolusDeliveredSoFar = 0.0 + + /* + * TEMP BASALS + */ + var isTempBasalInProgress = false + var tempBasalPercent = 0 + var tempBasalStart: Long = 0 + var tempBasalAbsoluteRate: Double = 0.0 + var tempBasalDuration: Long = 0 + + val tempBasalRemainingMin: Int + get() = max(tbElapsedTime, 0) + + fun temporaryBasalToString(): String { + if (!isTempBasalInProgress) return "" + return tempBasalAbsoluteRate.toString() + "U @" + + dateUtil.timeString(tempBasalStart) + + " " + tbElapsedTime + "/" + T.msecs(tempBasalDuration).mins() + "'" + } + + fun fromTemporaryBasal(tbr: PumpSync.PumpState.TemporaryBasal?) { + if (tbr == null) { + tempBasalStart = 0 + tempBasalDuration = 0 + tempBasalAbsoluteRate = 0.0 + } else { + tempBasalStart = tbr.timestamp + tempBasalDuration = tbr.duration + tempBasalAbsoluteRate = tbr.rate + } + } + + /* + * EXTENDED BOLUSES + */ + var extendedBolusStart: Long = 0 + var extendedBolusDuration: Long = 0 + var extendedBolusAmount = 0.0 + var isExtendedInProgress:Boolean = false + var extendedBolusPassedMinutes = 0 + var extendedBolusRemainingMinutes = 0 + var extendedBolusAbsoluteRate = 0.0 + + fun extendedBolusToString(): String { + if (!isExtendedInProgress) return "" + return "E "+ DecimalFormatter.to2Decimal(extendedBolusDeliveredSoFar) +"/" + DecimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" + + dateUtil.timeString(extendedBolusStart) + + " " + extendedBolusPassedMinutes + "/" + extendedBolusMinutes + "'" + } + + fun fromExtendedBolus(eb: PumpSync.PumpState.ExtendedBolus?) { + if (eb == null) { + extendedBolusStart = 0 + extendedBolusDuration = 0 + extendedBolusAmount = 0.0 + } else { + extendedBolusStart = eb.timestamp + extendedBolusDuration = eb.duration + extendedBolusAmount = eb.amount + } + } + // Profile + var units = 0 + var activeProfile = 0 + var pumpProfiles: Array>? = null + + //Limits + var maxBolus = 0.0 + var maxBasal = 0.0 + + // User settings + var setUserOptionType = 0 // ALARM:0, LCD:1, LANG:2, BOLUS_SPEED:3 + var beepAndAlarm = 0 + var alarmIntesity = 0 + var lcdOnTimeSec = 0 + var selectedLanguage = 0 + var bolusSpeed = 0 + + + // Bolus settings + var bolusStartErrorCode: Int = 0 // last start bolus erroCode + var historyDoneReceived: Boolean = false // true when last history message is received + var bolusingTreatment: EventOverviewBolusProgress.Treatment? = null // actually delivered treatment + var bolusAmountToBeDelivered = 0.0 // amount to be delivered + var bolusProgressLastTimeStamp: Long = 0 // timestamp of last bolus progress message + var bolusStopped = false // bolus finished + var bolusStopForced = false // bolus forced to stop by user + var bolusDone = false // success end + + fun buildDiaconnG8ProfileRecord(nsProfile: Profile): Array { + val record = Array(24) { 0.0 } + for (hour in 0..23) { + //Some values get truncated to the next lower one. + // -> round them to two decimals and make sure we are a small delta larger (that will get truncated) + val value = (100.0 * nsProfile.getBasalTimeFromMidnight((hour * 60 * 60))).roundToInt() / 100.0 + 0.00001 + aapsLogger.debug(LTag.PUMP, "NS basal value for $hour:00 is $value") + record[hour] = value + //aapsLogger.debug(LTag.PUMP, "NS basal value * 100 for $hour:00 is $value") + } + return record + } + + fun reset() { + aapsLogger.debug(LTag.PUMP, "Diaconn G8 Pump reset") + lastConnection = 0 + lastSettingsRead = 0 + } + + // G8 pump + var result:Int = 0 // 조회결과 + + // 1. pump setting info + var systemRemainInsulin = 0.0 // 인슐린 잔량 + var systemRemainBattery = 0 // 배터리 잔량(0~100%) + var systemBasePattern = 0 // 기저주입 패턴(0=없음, 1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2) + var systemTbStatus = 0 // 임시기저 상태(1=임시기저 중, 2=임시기저 해제) + var systemInjectionMealStatus = 0 // 식사주입 상태(1=주입중, 2=주입상태아님) + var systemInjectionSnackStatus = 0 // 일반간식 주입 상태(1=주입중, 2=주입상태아님) + var systemInjectionSquareStatue = 0 // 스퀘어회식 주입 상태(1=주입중, 2=주입상태아님) + var systemInjectionDualStatus = 0 // 더블회식 주입 상태(1=주입중, 2=주입상태아님) + + // 2. basal injection suspend status (1:stop, 2:release) + var basePauseStatus = 0 // 상태(1=정지,2=해제) + + // 3. Pump time + var year = 0 // 년 (18~99) + var month = 0 // 월 (1~12) + var day = 0 // 일 (1~31) + var hour = 0 // 시 (0~23) + var minute = 0 // 분 (0~59) + var second = 0 // 초 (0~59) + + + // 4. pump system info + var country = 0 // 생산국(K, C), ASCII + var productType = 0 // 제품종류(A ~ Z), ASCII + var makeYear = 0 // 제조년 + var makeMonth = 0 // 제조월 + var makeDay = 0 // 제조일 + var lotNo = 0 // LOT NO + var serialNo = 0 // SERIAL NO + var majorVersion = 0 // Major 버전 + var minorVersion = 0 // Minor 버전 + + // 5. pump log status + var pumpLastLogNum = 0 // 마지막 저장 로그 번호(0~9999) + var pumpWrappingCount = 0 // wrapping 카운트(0~255) + var apslastLogNum = 0 // 앱에서 처리한 마지막 로그 번호. + var apsWrappingCount = 0 // 앱에서 처리한 마지막 로그 번호. + var isProgressPumpLogSync = false // 로그 동기화 진행 여부 + + // 6. bolus speed status. + var speed = 0 // 주입 속도(1 ~ 8) + var maxBasalPerHours = 0.0 + + // 7. Tempbasal status + var tbStatus = 0 // 임시기저 상태 + var tbTime = 0 // 임시기저 시간 + var tbInjectRateRatio = 0 // 임시기저 주입량/률 1000(0.00U)~1600(6.00U), 50000(0%)~50200(200%), 50000이상이면 주입률로 판정 + var tbElapsedTime = 0 // 임시기저 경과 시간(0~1425분) + var tbInjectAbsoluteValue = 0.0 // 임시기저 주입량/률 1000(0.00U)~1600(6.00U) + + // 8. Basal status + var baseStatus = 0 // 주입상태 + var baseHour = 0 // 현재주입시간(0~23) + var baseAmount = 0.0 // 주입설정량(량*100, 23.25->2325, 15.2->1520) + var baseInjAmount = 0.0 // 현재주입량(량*100, 23.25->2325, 15.2->1520) + + + // 9. meal bolus status + var mealKind = 0 // 주입종류(1=아침,2=점심,3=저녁) + var mealStartTime = 0 // 식사주입 시작시간(time_t) + var mealStatus = 0 // 주입상태(1=주입중,2=주입상태아님) + var mealAmount = 0.0 // 주입설정량(량*100, 23.25->2325, 15.2->1520) + var mealInjAmount = 0.0 // 현재주입량(량*100, 23.25->2325, 15.2->1520) + var mealSpeed = 0 // 주입속도(1~8) + + + // 10. snack bolus status + var snackStatus = 0 // 주입상태(1=주입중,2=주입상태아님) + var snackAmount = 0.0 // 주입설정량(량*100, 23.25->2325, 15.2->1520) + var snackInjAmount = 0.0 // 현재주입량(량*100, 23.25->2325, 15.2->1520) + var snackSpeed = 0 // 주입속도(1~8) + + + // 11. square(extended) bolus status + var squareStatus = 0 // 주입상태 + var squareTime = 0 // 설정 주입시간(10~300분) + var squareInjTime = 0 // 경과 주입시간(10~300분) + var squareAmount = 0.0 // 주입 설정량 + var squareInjAmount = 0.0 // 현재 주입량 + + + // 12. daul bolus status + var dualStatus = 0 // 주입상태 + var dualAmount = 0.0 // 일반주입 설정량 + var dualInjAmount = 0.0 // 일반주입량 + var dualSquareTime = 0 // 스퀘어주입 설정시간(10~300분) + var dualInjSquareTime = 0 // 스퀘어주입 경과시간(10~300분) + var dualSquareAmount = 0.0 // 스퀘어주입 설정량 + var dualInjSquareAmount = 0.0 // 스퀘어주입량 + + + // 13. last injection status + var recentKind1 = 0 // 최근-1 주입 종류(1=식사, 2=일반간식, 3=스퀘어회식, 4=더블회식) + var recentTime1 = 0 // 최근-1 주입 시간 + var recentAmount1 = 0.0 // 최근-1 주입량 + var recentKind2 = 0 // 최근-2 주입 종류(1=식사, 2=일반간식, 3=스퀘어회식, 4=더블회식) + var recentTime2 = 0 // 최근-2 주입 시간 + var recentAmount2 = 0.0 // 최근-2 주입량 + + + // 14. daily injection status + var todayBaseAmount = 0.0 // 기저주입 총량 + var todayMealAmount = 0.0 // 식사주입 총량 + var todaySnackAmount = 0.0 // 회식주입 총량 + + + // 15. meat setting status + var morningHour = 0 // 아침 개시 시간(0~23) + var morningAmount = 0.0 // 아침 식전량 + var lunchHour = 0 // 점심 개시 시간(0~23) + var lunchAmount = 0.0 // 점심 식전량 + var dinnerHour = 0 // 저녁 개시 시간(0~23) + var dinnerAmount = 0.0 // 저녁 식전량 + + + // 16. basal injection status at this hour + var currentBasePattern = 0 // 패턴 종류 (1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2) + var currentBaseHour = 0 // 현재주입시간(0~23) + var currentBaseTbBeforeAmount = 0.0 // 해당시간의 임시기저 계산 전 기저주입량: 기저주입막힘 발생 시 기저주입 막힘량 제외, 기저정지로 인해 주입되지 않은 량 제외, 리셋으로 인해 주입되지 않은 량 제외(47.5=4750) + var currentBaseTbAfterAmount = 0.0 // 해당시간의 임시기저 계산 후 기저주입량: 기저주입막힘 발생 시 기저주입 막힘량 제외, 기저정지로 인해 주입되지 않은 량 제외, 리셋으로 인해 주입되지 않은 량 제외(47.5=4750) + + + // 17. saved basal pattern status + var baseAmount1 = 0.00// 주입량 1(량*100, 23.25->2325, 15.2->1520) + var baseAmount2 = 0.0// 주입량 2(량*100, 23.25->2325, 15.2->1520) + var baseAmount3 = 0.0 // 주입량 3(량*100, 23.25->2325, 15.2->1520) + var baseAmount4 = 0.0 // 주입량 4(량*100, 23.25->2325, 15.2->1520) + var baseAmount5 = 0.0 // 주입량 5(량*100, 23.25->2325, 15.2->1520) + var baseAmount6 = 0.0 // 주입량 6(량*100, 23.25->2325, 15.2->1520) + var baseAmount7 = 0.0 // 주입량 7(량*100, 23.25->2325, 15.2->1520) + var baseAmount8 = 0.0 // 주입량 8(량*100, 23.25->2325, 15.2->1520) + var baseAmount9 = 0.0 // 주입량 9(량*100, 23.25->2325, 15.2->1520) + var baseAmount10 = 0.0 // 주입량 10(량*100, 23.25->2325, 15.2->1520) + var baseAmount11 = 0.0 // 주입량 11(량*100, 23.25->2325, 15.2->1520) + var baseAmount12 = 0.0 // 주입량 12(량*100, 23.25->2325, 15.2->1520) + var baseAmount13 = 0.0 // 주입량 13(량*100, 23.25->2325, 15.2->1520) + var baseAmount14 = 0.0 // 주입량 14(량*100, 23.25->2325, 15.2->1520) + var baseAmount15 = 0.0 // 주입량 15(량*100, 23.25->2325, 15.2->1520) + var baseAmount16 = 0.0 // 주입량 16(량*100, 23.25->2325, 15.2->1520) + var baseAmount17 = 0.0 // 주입량 17(량*100, 23.25->2325, 15.2->1520) + var baseAmount18 = 0.0 // 주입량 18(량*100, 23.25->2325, 15.2->1520) + var baseAmount19 = 0.0 // 주입량 19(량*100, 23.25->2325, 15.2->1520) + var baseAmount20 = 0.0 // 주입량 20(량*100, 23.25->2325, 15.2->1520) + var baseAmount21 = 0.0 // 주입량 21(량*100, 23.25->2325, 15.2->1520) + var baseAmount22 = 0.0 // 주입량 22(량*100, 23.25->2325, 15.2->1520) + var baseAmount23 = 0.0 // 주입량 23(량*100, 23.25->2325, 15.2->1520) + var baseAmount24 = 0.0 // 주입량 24(량*100, 23.25->2325, 15.2->1520) + + var otpNumber = 0 + + companion object { + // User settings + const val ALARM = 0 + const val LCD = 1 + const val LANG = 2 + const val BOLUS_SPEED = 3 + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt new file mode 100644 index 0000000000..df908e0bca --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8BLEScanActivity.kt @@ -0,0 +1,184 @@ +package info.nightscout.androidaps.diaconn.activities + +import android.annotation.SuppressLint +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothDevice +import android.bluetooth.le.BluetoothLeScanner +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanFilter +import android.bluetooth.le.ScanResult +import android.bluetooth.le.ScanSettings +import android.content.pm.ActivityInfo +import android.os.Bundle +import android.os.Handler +import android.os.ParcelUuid +import android.view.View +import android.view.ViewGroup +import android.widget.BaseAdapter +import android.widget.TextView +import info.nightscout.androidaps.activities.NoSplashAppCompatActivity +import info.nightscout.androidaps.diaconn.events.EventDiaconnG8DeviceChange +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.databinding.DiaconnG8BlescannerActivityBinding +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck +import info.nightscout.androidaps.utils.sharedPreferences.SP +import java.util.* +import javax.inject.Inject + +class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() { + + @Inject lateinit var sp: SP + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var blePreCheck: BlePreCheck + + private var listAdapter: ListAdapter? = null + private val devices = ArrayList() + private var bluetoothLeScanner: BluetoothLeScanner? = null + private val serviceUUID = UUID.fromString("6e400001-b5a3-f393-e0a9-e50e24dcca9e") // BLE GATT Service UUID + + private lateinit var binding: DiaconnG8BlescannerActivityBinding + + @SuppressLint("SourceLockedOrientationActivity") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = DiaconnG8BlescannerActivityBinding.inflate(layoutInflater) + setContentView(binding.root) + requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT + + blePreCheck.prerequisitesCheck(this) + + listAdapter = ListAdapter() + binding.blescannerListview.emptyView = binding.blescannerNodevice + binding.blescannerListview.adapter = listAdapter + listAdapter?.notifyDataSetChanged() + } + + override fun onResume() { + super.onResume() + + BluetoothAdapter.getDefaultAdapter()?.let { bluetoothAdapter -> + if (!bluetoothAdapter.isEnabled) bluetoothAdapter.enable() + bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner + startScan() + } + } + + override fun onPause() { + super.onPause() + stopScan() + } + + private fun startScan() = + try { + val filters: MutableList = ArrayList() + val scan_filter = ScanFilter.Builder() + .setServiceUuid(ParcelUuid(serviceUUID)) + .build() + filters.add(scan_filter) + + val settings = ScanSettings.Builder() + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build() + + bluetoothLeScanner?.startScan(filters, settings, mBleScanCallback) + } catch (e: IllegalStateException) { + } // ignore BT not on + + private fun stopScan() = + try { + bluetoothLeScanner?.stopScan(mBleScanCallback) + } catch (e: IllegalStateException) { + } // ignore BT not on + + private fun addBleDevice(device: BluetoothDevice?) { + if (device == null || device.name == null || device.name == "") { + return + } + val item = BluetoothDeviceItem(device) + if (devices.contains(item)) { + return + } + devices.add(item) + Handler().post { listAdapter!!.notifyDataSetChanged() } + } + + private val mBleScanCallback: ScanCallback = object : ScanCallback() { + override fun onScanResult(callbackType: Int, result: ScanResult) { + addBleDevice(result.device) + } + } + + internal inner class ListAdapter : BaseAdapter() { + + override fun getCount(): Int = devices.size + override fun getItem(i: Int): BluetoothDeviceItem = devices[i] + override fun getItemId(i: Int): Long = 0 + + override fun getView(i: Int, convertView: View?, parent: ViewGroup?): View { + var v = convertView + val holder: ViewHolder + if (v == null) { + v = View.inflate(applicationContext, R.layout.diaconn_g8_blescanner_item, null) + holder = ViewHolder(v) + v.tag = holder + } else { + // reuse view if already exists + holder = v.tag as ViewHolder + } + val item = getItem(i) + holder.setData(item) + return v!! + } + + private inner class ViewHolder(v: View) : View.OnClickListener { + + private lateinit var item: BluetoothDeviceItem + private val name: TextView = v.findViewById(R.id.ble_name) + private val address: TextView = v.findViewById(R.id.ble_address) + + init { + v.setOnClickListener(this@ViewHolder) + } + + override fun onClick(v: View) { + sp.putString(R.string.key_diaconn_g8_address, item.device.address) + sp.putString(R.string.key_diaconn_g8_name, name.text.toString()) + item.device.createBond() + rxBus.send(EventDiaconnG8DeviceChange()) + finish() + } + + fun setData(data: BluetoothDeviceItem) { + var tTitle = data.device.name + if (tTitle == null || tTitle == "") { + tTitle = "(unknown)" + } + name.text = tTitle + address.text = data.device.address + item = data + } + + } + } + + // + inner class BluetoothDeviceItem internal constructor(val device: BluetoothDevice) { + override fun equals(other: Any?): Boolean { + if (other !is BluetoothDeviceItem) { + return false + } + return stringEquals(device.address, other.device.address) + } + + private fun stringEquals(arg1: String, arg2: String): Boolean { + return try { + arg1 == arg2 + } catch (e: Exception) { + false + } + } + + override fun hashCode(): Int = device.hashCode() + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt new file mode 100644 index 0000000000..06ec319cb4 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8HistoryActivity.kt @@ -0,0 +1,257 @@ +package info.nightscout.androidaps.diaconn.activities + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.AdapterView +import android.widget.ArrayAdapter +import android.widget.TextView +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import info.nightscout.androidaps.activities.NoSplashAppCompatActivity +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.common.RecordTypes +import info.nightscout.androidaps.diaconn.database.DiaconnHistoryRecord +import info.nightscout.androidaps.diaconn.database.DiaconnHistoryRecordDao +import info.nightscout.androidaps.diaconn.databinding.DiaconnG8HistoryActivityBinding +import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.DecimalFormatter +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.rx.AapsSchedulers + + +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.rxkotlin.plusAssign +import java.util.* +import javax.inject.Inject + +class DiaconnG8HistoryActivity : NoSplashAppCompatActivity() { + + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var diaconnHistoryRecordDao: DiaconnHistoryRecordDao + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers + + private val disposable = CompositeDisposable() + + private var showingType = RecordTypes.RECORD_TYPE_ALARM + private var historyList: List = ArrayList() + + class TypeList internal constructor(var type: Byte, var name: String) { + + override fun toString(): String = name + } + + private lateinit var binding: DiaconnG8HistoryActivityBinding + + override fun onResume() { + super.onResume() + disposable += rxBus + .toObservable(EventPumpStatusChanged::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ binding.status.text = it.getStatus(resourceHelper) }) { fabricPrivacy.logException(it) } + swapAdapter(showingType) + } + + override fun onPause() { + super.onPause() + disposable.clear() + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = DiaconnG8HistoryActivityBinding.inflate(layoutInflater) + setContentView(binding.root) + + binding.recyclerview.setHasFixedSize(true) + binding.recyclerview.layoutManager = LinearLayoutManager(this) + binding.recyclerview.adapter = RecyclerViewAdapter(historyList) + binding.status.visibility = View.GONE + + // Types + val typeList = ArrayList() + typeList.add(TypeList(RecordTypes.RECORD_TYPE_ALARM, resourceHelper.gs(R.string.diaconn_g8_history_alarm))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, resourceHelper.gs(R.string.diaconn_g8_history_basalhours))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_BOLUS, resourceHelper.gs(R.string.diaconn_g8_history_bolus))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_TB, resourceHelper.gs(R.string.diaconn_g8_history_tempbasal))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_DAILY, resourceHelper.gs(R.string.diaconn_g8_history_dailyinsulin))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_REFILL, resourceHelper.gs(R.string.diaconn_g8_history_refill))) + typeList.add(TypeList(RecordTypes.RECORD_TYPE_SUSPEND, resourceHelper.gs(R.string.diaconn_g8_history_suspend))) + binding.spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, typeList) + + binding.reload.setOnClickListener { + val selected = binding.spinner.selectedItem as TypeList? + ?: return@setOnClickListener + runOnUiThread { + binding.reload.visibility = View.GONE + binding.status.visibility = View.VISIBLE + } + clearCardView() + commandQueue.loadHistory(selected.type, object : Callback() { + override fun run() { + swapAdapter(selected.type) + runOnUiThread { + binding.reload.visibility = View.VISIBLE + binding.status.visibility = View.GONE + } + } + }) + } + binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + val selected = typeList[position] + swapAdapter(selected.type) + showingType = selected.type + } + + override fun onNothingSelected(parent: AdapterView<*>?) { + clearCardView() + } + } + } + + inner class RecyclerViewAdapter internal constructor(private var historyList: List) : RecyclerView.Adapter() { + + override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): HistoryViewHolder = + HistoryViewHolder(LayoutInflater.from(viewGroup.context).inflate(R.layout.diaconn_g8_history_item, viewGroup, false)) + + override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { + val record = historyList[position] + holder.time.text = dateUtil.dateAndTimeString(record.timestamp) + holder.value.text = DecimalFormatter.to2Decimal(record.value) + holder.stringValue.text = record.stringValue + holder.bolusType.text = record.bolusType + holder.duration.text = DecimalFormatter.to0Decimal(record.duration.toDouble()) + holder.alarm.text = record.alarm + when (showingType) { + RecordTypes.RECORD_TYPE_ALARM -> { + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.VISIBLE + holder.stringValue.visibility = View.VISIBLE + holder.bolusType.visibility = View.GONE + holder.duration.visibility = View.GONE + holder.dailyBasal.visibility = View.GONE + holder.dailyBolus.visibility = View.GONE + holder.dailyTotal.visibility = View.GONE + holder.alarm.visibility = View.VISIBLE + } + + RecordTypes.RECORD_TYPE_BOLUS -> { + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.VISIBLE + holder.stringValue.visibility = View.VISIBLE + holder.bolusType.visibility = View.VISIBLE + holder.duration.visibility = View.VISIBLE + holder.dailyBasal.visibility = View.GONE + holder.dailyBolus.visibility = View.GONE + holder.dailyTotal.visibility = View.GONE + holder.alarm.visibility = View.GONE + } + + RecordTypes.RECORD_TYPE_DAILY -> { + holder.dailyBasal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBasal) + holder.dailyBolus.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus) + holder.dailyTotal.text = resourceHelper.gs(R.string.formatinsulinunits, record.dailyBolus + record.dailyBasal) + holder.time.text = dateUtil.dateString(record.timestamp) + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.GONE + holder.stringValue.visibility = View.GONE + holder.bolusType.visibility = View.GONE + holder.duration.visibility = View.GONE + holder.dailyBasal.visibility = View.VISIBLE + holder.dailyBolus.visibility = View.VISIBLE + holder.dailyTotal.visibility = View.VISIBLE + holder.alarm.visibility = View.GONE + } + + RecordTypes.RECORD_TYPE_BASALHOUR -> { + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.VISIBLE + holder.stringValue.visibility = View.VISIBLE + holder.bolusType.visibility = View.GONE + holder.duration.visibility = View.GONE + holder.dailyBasal.visibility = View.GONE + holder.dailyBolus.visibility = View.GONE + holder.dailyTotal.visibility = View.GONE + holder.alarm.visibility = View.GONE + } + RecordTypes.RECORD_TYPE_REFILL -> { + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.VISIBLE + holder.stringValue.visibility = View.VISIBLE + holder.bolusType.visibility = View.GONE + holder.duration.visibility = View.GONE + holder.dailyBasal.visibility = View.GONE + holder.dailyBolus.visibility = View.GONE + holder.dailyTotal.visibility = View.GONE + holder.alarm.visibility = View.GONE + } + + RecordTypes.RECORD_TYPE_TB -> { + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.VISIBLE + holder.stringValue.visibility = View.VISIBLE + holder.bolusType.visibility = View.GONE + holder.duration.visibility = View.VISIBLE + holder.dailyBasal.visibility = View.GONE + holder.dailyBolus.visibility = View.GONE + holder.dailyTotal.visibility = View.GONE + holder.alarm.visibility = View.GONE + } + + RecordTypes.RECORD_TYPE_SUSPEND -> { + holder.time.visibility = View.VISIBLE + holder.value.visibility = View.GONE + holder.stringValue.visibility = View.VISIBLE + holder.bolusType.visibility = View.GONE + holder.duration.visibility = View.GONE + holder.dailyBasal.visibility = View.GONE + holder.dailyBolus.visibility = View.GONE + holder.dailyTotal.visibility = View.GONE + holder.alarm.visibility = View.GONE + } + } + } + + override fun getItemCount(): Int { + return historyList.size + } + + inner class HistoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { + + var time: TextView = itemView.findViewById(R.id.diaconn_g8_history_time) + var value: TextView = itemView.findViewById(R.id.diaconn_g8_history_value) + var bolusType: TextView = itemView.findViewById(R.id.diaconn_g8_history_bolustype) + var stringValue: TextView = itemView.findViewById(R.id.diaconn_g8_history_stringvalue) + var duration: TextView = itemView.findViewById(R.id.diaconn_g8_history_duration) + var dailyBasal: TextView = itemView.findViewById(R.id.diaconn_g8_history_dailybasal) + var dailyBolus: TextView = itemView.findViewById(R.id.diaconn_g8_history_dailybolus) + var dailyTotal: TextView = itemView.findViewById(R.id.diaconn_g8_history_dailytotal) + var alarm: TextView = itemView.findViewById(R.id.diaconn_g8_history_alarm) + } + } + + private fun swapAdapter(type: Byte) { + disposable += diaconnHistoryRecordDao + .allFromByType(dateUtil.now() - T.months(1).msecs(), type) + .subscribeOn(aapsSchedulers.io) + .observeOn(aapsSchedulers.main) + .subscribe { historyList -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(historyList), false) } + } + + private fun clearCardView() = binding.recyclerview.swapAdapter(RecyclerViewAdapter(ArrayList()), false) +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt new file mode 100644 index 0000000000..4ec3c4b3a2 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/activities/DiaconnG8UserOptionsActivity.kt @@ -0,0 +1,192 @@ +package info.nightscout.androidaps.diaconn.activities + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.view.View +import android.widget.AdapterView +import android.widget.ArrayAdapter +import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.activities.NoSplashAppCompatActivity + + +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.databinding.DiaconnG8UserOptionsActivityBinding + +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.ToastUtils +import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.reactivex.disposables.CompositeDisposable +import java.text.DecimalFormat +import javax.inject.Inject + +class DiaconnG8UserOptionsActivity : NoSplashAppCompatActivity() { + + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var context: Context + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var sp: SP + + private val disposable = CompositeDisposable() + + private lateinit var binding: DiaconnG8UserOptionsActivityBinding + + @Synchronized + override fun onResume() { + super.onResume() + } + + @Synchronized + override fun onPause() { + disposable.clear() + super.onPause() + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = DiaconnG8UserOptionsActivityBinding.inflate(layoutInflater) + setContentView(binding.root) + + binding.saveAlarm.setOnClickListener { onSaveAlarmClick() } + binding.saveLcdOnTime.setOnClickListener { onSavelcdOnTimeClick() } + binding.saveLang.setOnClickListener { onSaveLangClick() } + + binding.saveBolusSpeed.setOnClickListener { onSaveBolusSpeedClick() } + + val spBolusSpeed = sp.getString("g8_bolusspeed", "5") + + binding.bolusSpeed.setParams(spBolusSpeed.toDouble(), 1.0, 8.0, 1.0, DecimalFormat("1"), true, binding.saveBolusSpeed) + + aapsLogger.debug(LTag.PUMP, + "UserOptionsLoaded:" + (System.currentTimeMillis() - diaconnG8Pump.lastConnection) / 1000 + " s ago" + + "\nbeepAndAlarm:" + diaconnG8Pump.beepAndAlarm + + "\nalarmIntesity:" + diaconnG8Pump.alarmIntesity + + "\nlanguage:" + diaconnG8Pump.selectedLanguage + + "\nlcdOnTimeSec:" + diaconnG8Pump.lcdOnTimeSec) + + fillSoundCategory() + fillSoundSubCategory() + + binding.beepAndAlarm.setSelection(diaconnG8Pump.beepAndAlarm - 1) + binding.alarmIntesity.setSelection(diaconnG8Pump.alarmIntesity - 1) + + binding.beepAndAlarm.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { + binding.alarmIntesity.visibility = if("silent" == binding.beepAndAlarm.getItemAtPosition(position).toString()) View.GONE else View.VISIBLE + } + override fun onNothingSelected(parent: AdapterView<*>?) {} + } + + when (diaconnG8Pump.lcdOnTimeSec) { + 1 -> binding.pumpscreentimeout10.isChecked = true + 2 -> binding.pumpscreentimeout20.isChecked = true + 3 -> binding.pumpscreentimeout30.isChecked = true + } + + when (diaconnG8Pump.selectedLanguage) { + 1 -> binding.pumplangChiness.isChecked = true + 2 -> binding.pumplangKorean.isChecked = true + 3 -> binding.pumplangEnglish.isChecked = true + } + } + + private fun onSaveAlarmClick() { + + diaconnG8Pump.setUserOptionType = DiaconnG8Pump.ALARM + + diaconnG8Pump.beepAndAlarm = binding.beepAndAlarm.selectedItemPosition + 1 + diaconnG8Pump.alarmIntesity = binding.alarmIntesity.selectedItemPosition + 1 + + onSaveClick() + } + + private fun onSavelcdOnTimeClick() { + + diaconnG8Pump.setUserOptionType = DiaconnG8Pump.LCD + + diaconnG8Pump.lcdOnTimeSec = when { + binding.pumpscreentimeout10.isChecked -> 1 + binding.pumpscreentimeout20.isChecked -> 2 + binding.pumpscreentimeout30.isChecked -> 3 + else -> 1 + } + + onSaveClick() + } + + private fun onSaveLangClick() { + + diaconnG8Pump.setUserOptionType = DiaconnG8Pump.LANG + + diaconnG8Pump.selectedLanguage = when { + binding.pumplangChiness.isChecked -> 1 + binding.pumplangKorean.isChecked -> 2 + binding.pumplangEnglish.isChecked -> 3 + else -> 2 + } + + onSaveClick() + } + + private fun onSaveBolusSpeedClick() { + val intSpeed = binding.bolusSpeed.value.toInt() + + diaconnG8Pump.bolusSpeed = intSpeed + diaconnG8Pump.speed = intSpeed + diaconnG8Pump.setUserOptionType = DiaconnG8Pump.BOLUS_SPEED + sp.putString("g8_bolusspeed", intSpeed.toString()) + sp.putBoolean("diaconn_g8_isbolusspeedsync", false) + + ToastUtils.okToast(context, "Save Success!") + } + + private fun onSaveClick() { + commandQueue.setUserOptions(object : Callback() { + override fun run() { + if (!result.success) { + val i = Intent(context, ErrorHelperActivity::class.java) + i.putExtra("soundid", R.raw.boluserror) + i.putExtra("status", result.comment) + i.putExtra("title", resourceHelper.gs(R.string.pumperror)) + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(i) + } + } + }) + finish() + } + + private fun fillSoundCategory() { + val categories = ArrayList() + categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_sound)) + categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_vibrate)) + categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_silent)) + context.let { context -> + val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories) + binding.beepAndAlarm.adapter = adapterCategories + } + } + + private fun fillSoundSubCategory() { + val categories = ArrayList() + categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_intensity_low)) + categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_intensity_middle)) + categories.add(resourceHelper.gs(R.string.diaconn_g8_pumpalarm_intensity_high)) + context.let { context -> + val adapterCategories = ArrayAdapter(context, R.layout.spinner_centered, categories) + binding.alarmIntesity.adapter = adapterCategories + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/common/RecordTypes.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/common/RecordTypes.kt new file mode 100644 index 0000000000..e4fbc8122d --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/common/RecordTypes.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.diaconn.common + +object RecordTypes { + const val RECORD_TYPE_BOLUS = 0x01.toByte() + const val RECORD_TYPE_DAILY = 0x02.toByte() + const val RECORD_TYPE_ALARM = 0x03.toByte() + const val RECORD_TYPE_REFILL = 0x04.toByte() + const val RECORD_TYPE_SUSPEND = 0x05.toByte() + const val RECORD_TYPE_BASALHOUR = 0x06.toByte() + const val RECORD_TYPE_TB = 0x07.toByte() +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryDatabase.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryDatabase.kt new file mode 100644 index 0000000000..38a082133a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryDatabase.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase + +const val TABLE_DIACONN_HISTORY = "diaconnHistory" + +@Database( + entities = [DiaconnHistoryRecord::class], + exportSchema = true, + version = DiaconnHistoryDatabase.VERSION +) +abstract class DiaconnHistoryDatabase : RoomDatabase() { + + abstract fun historyRecordDao(): DiaconnHistoryRecordDao + + companion object { + + const val VERSION = 1 + + fun build(context: Context) = + Room.databaseBuilder( + context.applicationContext, + DiaconnHistoryDatabase::class.java, + "diaconn_database.db" + ) + .fallbackToDestructiveMigration() + .build() + } +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecord.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecord.kt new file mode 100644 index 0000000000..46d7e28e89 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecord.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.diaconn.database + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity(tableName = TABLE_DIACONN_HISTORY, + indices = [Index("code", "timestamp")]) +data class DiaconnHistoryRecord( + @PrimaryKey var timestamp: Long, + var code: Byte = 0x0F, + var value: Double = 0.0, + var bolusType: String = "None", + var stringValue: String = "", + var duration: Int = 0, + var dailyBasal: Double = 0.0, + var dailyBolus: Double = 0.0, + var alarm: String = "" +) diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecordDao.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecordDao.kt new file mode 100644 index 0000000000..127be05acd --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/database/DiaconnHistoryRecordDao.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.diaconn.database + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import io.reactivex.Single + +@Dao +abstract class DiaconnHistoryRecordDao { + + @Query("SELECT * from $TABLE_DIACONN_HISTORY WHERE timestamp >= :timestamp AND code = :type") + abstract fun allFromByType(timestamp: Long, type: Byte): Single> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun createOrUpdate(diaconnHistoryRecord: DiaconnHistoryRecord) +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ActivitiesModule.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ActivitiesModule.kt new file mode 100644 index 0000000000..8a39b928a0 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ActivitiesModule.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.diaconn.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Fragment +import info.nightscout.androidaps.diaconn.activities.DiaconnG8BLEScanActivity +import info.nightscout.androidaps.diaconn.activities.DiaconnG8HistoryActivity +import info.nightscout.androidaps.diaconn.activities.DiaconnG8UserOptionsActivity + +@Module +@Suppress("unused") +abstract class DiaconnG8ActivitiesModule { + @ContributesAndroidInjector abstract fun contributesDiaconnG8Fragment(): DiaconnG8Fragment + @ContributesAndroidInjector abstract fun contributesDiaconnG8HistoryActivity(): DiaconnG8HistoryActivity + @ContributesAndroidInjector abstract fun contributesDiaconnG8UserOptionsActivity(): DiaconnG8UserOptionsActivity + @ContributesAndroidInjector abstract fun contributesDiaconnG8BLEScanActivity(): DiaconnG8BLEScanActivity +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8Module.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8Module.kt new file mode 100644 index 0000000000..870d460bf0 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8Module.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.diaconn.di + +import dagger.Module + +@Module(includes = [ + DiaconnG8ActivitiesModule::class, + DiaconnG8ServiceModule::class, + DiaconnG8PacketModule::class, + DiaconnHistoryModule::class +]) + +open class DiaconnG8Module \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8PacketModule.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8PacketModule.kt new file mode 100644 index 0000000000..65e252098a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8PacketModule.kt @@ -0,0 +1,81 @@ +package info.nightscout.androidaps.diaconn.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.diaconn.packet.* + +@Module +@Suppress("unused") +abstract class DiaconnG8PacketModule { + @ContributesAndroidInjector abstract fun contributesDiaconnG8Packet(): DiaconnG8Packet + @ContributesAndroidInjector abstract fun contributesAppCancelSettingPacket(): AppCancelSettingPacket + @ContributesAndroidInjector abstract fun contributesAppCancelSettingResponsePacket(): AppCancelSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesAppConfirmSettingPacket(): AppConfirmSettingPacket + @ContributesAndroidInjector abstract fun contributesAppConfirmSettingResponsePacket(): AppConfirmSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesSneckLimitInquirePacket(): SneckLimitInquirePacket + @ContributesAndroidInjector abstract fun contributesBasalLimitInquirePacket(): BasalLimitInquirePacket + @ContributesAndroidInjector abstract fun contributesSneckLimitInquireResponsePacket(): SneckLimitInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesBasalLimitInquireResponsePacket(): BasalLimitInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesBasalPauseReportPacket(): BasalPauseReportPacket + @ContributesAndroidInjector abstract fun contributesBasalPauseSettingPacket(): BasalPauseSettingPacket + @ContributesAndroidInjector abstract fun contributesBasalPauseSettingResponsePacket(): BasalPauseSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesBasalSettingPacket(): BasalSettingPacket + @ContributesAndroidInjector abstract fun contributesBasalSettingReportPacket(): BasalSettingReportPacket + @ContributesAndroidInjector abstract fun contributesBasalSettingResponsePacket(): BasalSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesBigMainInfoInquirePacket(): BigMainInfoInquirePacket + @ContributesAndroidInjector abstract fun contributesBigMainInfoInquireResponsePacket(): BigMainInfoInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesBigLogInquirePacket(): BigLogInquirePacket + @ContributesAndroidInjector abstract fun contributesBigLogInquireResponsePacket(): BigLogInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesConfirmReportPacket(): ConfirmReportPacket + @ContributesAndroidInjector abstract fun contributesInjectionBasalSettingPacket(): InjectionBasalSettingPacket + @ContributesAndroidInjector abstract fun contributesInjectionBasalSettingResponsePacket(): InjectionBasalSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesInjectionSnackResultReportPacket(): InjectionSnackResultReportPacket + @ContributesAndroidInjector abstract fun contributesInjectionSnactSettingPacket(): InjectionSnackSettingPacket + @ContributesAndroidInjector abstract fun contributesInjectionSnackSettingResponsePacket(): InjectionSnackSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesInjectionExtendedBolusResultReportPacket(): InjectionExtendedBolusResultReportPacket + @ContributesAndroidInjector abstract fun contributesInjectionExtendedBolusSettingPacket(): InjectionExtendedBolusSettingPacket + @ContributesAndroidInjector abstract fun contributesInjectionExtendedBolusSettingResponsePacket(): InjectionExtendedBolusSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesInjectionBasalReportPacket(): InjectionBasalReportPacket + @ContributesAndroidInjector abstract fun contributesInjectionSnackInquirePacket(): InjectionSnackInquirePacket + @ContributesAndroidInjector abstract fun contributesInjectionSnackInquireResponsePacket(): InjectionSnackInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesRejectReportPacket(): RejectReportPacket + @ContributesAndroidInjector abstract fun contributesTempBasalReportPacket(): TempBasalReportPacket + @ContributesAndroidInjector abstract fun contributesTempBasalSettingPacket(): TempBasalSettingPacket + @ContributesAndroidInjector abstract fun contributesTempBasalSettingResponsePacket(): TempBasalSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesTempBasalInquirePacket(): TempBasalInquirePacket + @ContributesAndroidInjector abstract fun contributesTempBasalInquireResponsePacket(): TempBasalInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesTimeInquirePacket(): TimeInquirePacket + @ContributesAndroidInjector abstract fun contributesTimeInquireResponsePacket(): TimeInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesTimeReportPacket(): TimeReportPacket + @ContributesAndroidInjector abstract fun contributesTimeSettingPacket(): TimeSettingPacket + @ContributesAndroidInjector abstract fun contributesTimeSettingResponsePacket(): TimeSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesLogStatusInquirePacket(): LogStatusInquirePacket + @ContributesAndroidInjector abstract fun contributesLogStatusInquireResponsePacket(): LogStatusInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesInjectionCancelSettingPacket(): InjectionCancelSettingPacket + @ContributesAndroidInjector abstract fun contributesInjectionCancelSettingResponsePacket(): InjectionCancelSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesSoundSettingPacket(): SoundSettingPacket + @ContributesAndroidInjector abstract fun contributesSoundSettingResponsePacket(): SoundSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesDisplayTimeoutSettingPacket(): DisplayTimeoutSettingPacket + @ContributesAndroidInjector abstract fun contributesDisplayTimeoutSettingResponsePacket(): DisplayTimeoutSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesLanguageSettingPacket(): LanguageSettingPacket + @ContributesAndroidInjector abstract fun contributesLanguageSettingResponsePacket(): LanguageSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesInjectionBlockReportPacket(): InjectionBlockReportPacket + @ContributesAndroidInjector abstract fun contributesBatteryWarningReportPacket(): BatteryWarningReportPacket + @ContributesAndroidInjector abstract fun contributesInsulinLackReportPacket(): InsulinLackReportPacket + @ContributesAndroidInjector abstract fun contributesIncarnationInquirePacket(): IncarnationInquirePacket + @ContributesAndroidInjector abstract fun contributesIncarnationInquireResponsePacket(): IncarnationInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesBolusSpeedSettingPacket(): BolusSpeedSettingPacket + @ContributesAndroidInjector abstract fun contributesBolusSpeedSettingResponsePacket(): BolusSpeedSettingResponsePacket + @ContributesAndroidInjector abstract fun contributesInjectionSpeedInquirePacket(): BolusSpeedInquirePacket + @ContributesAndroidInjector abstract fun contributesInjectionSpeedInquireResponsePacket(): BolusSpeedInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesBolusSpeedSettingReportPacket(): BolusSpeedSettingReportPacket + @ContributesAndroidInjector abstract fun contributesSoundInquirePacket(): SoundInquirePacket + @ContributesAndroidInjector abstract fun contributesSoundInquireResponsePacket(): SoundInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesDisplayTimeInquirePacket(): DisplayTimeInquirePacket + @ContributesAndroidInjector abstract fun contributesDisplayTimeInquireResponsePacket(): DisplayTimeInquireResponsePacket + @ContributesAndroidInjector abstract fun contributesLanguageInquirePacket(): LanguageInquirePacket + @ContributesAndroidInjector abstract fun contributesLanguageInquireResponsePacket(): LanguageInquireResponsePacket + + + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ServiceModule.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ServiceModule.kt new file mode 100644 index 0000000000..ecc84e13d7 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8ServiceModule.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.diaconn.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.diaconn.service.DiaconnG8Service + +@Module +@Suppress("unused") +abstract class DiaconnG8ServiceModule { + @ContributesAndroidInjector abstract fun contributesDiaconnG8Service(): DiaconnG8Service +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnHistoryModule.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnHistoryModule.kt new file mode 100644 index 0000000000..fed5f0ed58 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnHistoryModule.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.diaconn.di + +import android.content.Context +import dagger.Module +import dagger.Provides +import info.nightscout.androidaps.diaconn.database.DiaconnHistoryDatabase +import info.nightscout.androidaps.diaconn.database.DiaconnHistoryRecordDao +import javax.inject.Singleton + +@Module +class DiaconnHistoryModule { + + @Provides + @Singleton + internal fun provideDatabase(context: Context): DiaconnHistoryDatabase = DiaconnHistoryDatabase.build(context) + + @Provides + @Singleton + internal fun provideHistoryRecordDao(diaconnHistoryDatabase: DiaconnHistoryDatabase): DiaconnHistoryRecordDao = + diaconnHistoryDatabase.historyRecordDao() +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8DeviceChange.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8DeviceChange.kt new file mode 100644 index 0000000000..a4c565ec9d --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8DeviceChange.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.diaconn.events + +import info.nightscout.androidaps.events.Event + +class EventDiaconnG8DeviceChange : Event() \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8NewStatus.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8NewStatus.kt new file mode 100644 index 0000000000..b275db0111 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/events/EventDiaconnG8NewStatus.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.diaconn.events + +import info.nightscout.androidaps.events.Event + +class EventDiaconnG8NewStatus : Event() diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingPacket.kt new file mode 100644 index 0000000000..a3cfaed4ce --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingPacket.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * AppCancelSettingPacket + */ +class AppCancelSettingPacket( + injector: HasAndroidInjector, + private var reqMsgType: Byte, +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x29 + aapsLogger.debug(LTag.PUMPCOMM, "AppCancelSettingPacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.put(reqMsgType) // 명령코드 + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_APP_CANCEL_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingResponsePacket.kt new file mode 100644 index 0000000000..bdba88b35f --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppCancelSettingResponsePacket.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * AppCancelSettingResponsePacket + */ +class AppCancelSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result =0 + init { + msgType = 0xA9.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "AppCancelSettingResPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "AppCancelSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${result}") + } + + + override fun getFriendlyName(): String { + return "PUMP_APP_CANCEL_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingPacket.kt new file mode 100644 index 0000000000..d0805f6a5f --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingPacket.kt @@ -0,0 +1,39 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * AppConfirmSettingPacket + */ +class AppConfirmSettingPacket( + injector: HasAndroidInjector, + private var reqMsgType: Byte, // 명령코드 + private var otp: Int // 응답시 전달받은 opt (random 6 digit numbner) +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x37 + aapsLogger.debug(LTag.PUMPCOMM, "AppConfirmSettingPacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + + buffer.put(reqMsgType) // 명령코드 + buffer.putInt(otp) // 응답시 전달받은 opt (random 6digit numbner) + + aapsLogger.debug(LTag.PUMPCOMM, "reqMsgType -> ${reqMsgType}") + aapsLogger.debug(LTag.PUMPCOMM, "otp -> ${otp}") + + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_APP_CONFRIM_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingResponsePacket.kt new file mode 100644 index 0000000000..096516e501 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/AppConfirmSettingResponsePacket.kt @@ -0,0 +1,43 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * AppConfirmSettingResponsePacket + */ +class AppConfirmSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result =0 + init { + msgType = 0xB7.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "AppConfirmSettingReqPacket Response ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "AppConfirmSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${result}") + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + } + + override fun getFriendlyName(): String { + return "PUMP_APP_CONFIRM_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquirePacket.kt new file mode 100644 index 0000000000..36a484cf4a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquirePacket.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalLimitInquirePacket + */ +class BasalLimitInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x52.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BasalLimitInquirePacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_LIMIT_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt new file mode 100644 index 0000000000..26bb9a78ab --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalLimitInquireResponsePacket + */ +class BasalLimitInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x92.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BasalLimitInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BasalLimitInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + diaconnG8Pump.maxBasalPerHours = getShortToInt(bufferData).toDouble() / 100.0 // not include tempbasal limit + diaconnG8Pump.maxBasal = diaconnG8Pump.maxBasalPerHours * 2 // include tempbasal + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") + aapsLogger.debug(LTag.PUMPCOMM, "maxBasal --> ${diaconnG8Pump.maxBasal}") + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_LIMIT_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseReportPacket.kt new file mode 100644 index 0000000000..f1aac0371b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseReportPacket.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalPauseReportPacket + */ +class BasalPauseReportPacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var status:Int? = null + + init { + msgType = 0xC3.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + status = getByteToInt(bufferData) //(1: pauseed, 2: pause cancel) + aapsLogger.debug(LTag.PUMPCOMM, "status --> ${status}") + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_PAUSE_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingPacket.kt new file mode 100644 index 0000000000..69c88187e9 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingPacket.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * Basal Pause Setting Packet + */ +class BasalPauseSettingPacket( + injector: HasAndroidInjector, + private var status:Int //(1:pause, 2: cancel pause) +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x03 + aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseSettingPacket Init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + buffer.put(status.toByte()) // (1:pause, 2: cancel pause) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_PAUSE_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingResponsePacket.kt new file mode 100644 index 0000000000..649ed7ff5e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalPauseSettingResponsePacket.kt @@ -0,0 +1,48 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalPauseSettingResponsePacket + */ +class BasalPauseSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + + init { + msgType = 0x83.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseSettingResponsePacket Init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BasalPauseSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${result}") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_PAUSE_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingPacket.kt new file mode 100644 index 0000000000..f5ddbbdaa8 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingPacket.kt @@ -0,0 +1,54 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalSettingPacket + */ +class BasalSettingPacket( + injector: HasAndroidInjector, + private var pattern: Int, // pattern(1=basic, 2=life1, 3=life2, 4=life3, 5=dr1, 6=dr2) + private var group: Int, //hour group (1=00~05, 2=06~11, 3=12~17, 4=18~23) + private var amount1: Int, + private var amount2: Int, + private var amount3: Int, + private var amount4: Int, + private var amount5: Int, + private var amount6: Int +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x0B + aapsLogger.debug(LTag.PUMPCOMM, "Setting new basal rates for profile") + + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = if (group == 4) { + // 마지막 그룹일때 + prefixEncode(msgType, msgSeq, MSG_CON_END) + } else { + // 1, 2, 3 그룹일때 + prefixEncode(msgType, msgSeq, MSG_CON_CONTINUE) + } + buffer.put(pattern.toByte()) // 패턴 종류 (1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2) + buffer.put(group.toByte()) // 그룹 (1=00~05, 2=06~11, 3=12~17, 4=18~23) + buffer.putShort(amount1.toShort()) // 주입량 1 + buffer.putShort(amount2.toShort()) // 주입량 2 + buffer.putShort(amount3.toShort()) // 주입량 3 + buffer.putShort(amount4.toShort()) // 주입량 4 + buffer.putShort(amount5.toShort()) // 주입량 5 + buffer.putShort(amount6.toShort()) // 주입량 6 + + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingReportPacket.kt new file mode 100644 index 0000000000..3f28ffd3e8 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingReportPacket.kt @@ -0,0 +1,40 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalSettingReportPacket + */ +class BasalSettingReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + + init { + msgType = 0xCB.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BasalSettingReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BasalSettingReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + // no Response + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_SETTING_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingResponsePacket.kt new file mode 100644 index 0000000000..10ee5d139a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalSettingResponsePacket.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BasalSettingResponsePacket + */ +class BasalSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + + init { + msgType = 0x8B.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BasalSettingResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BasalSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_BASAL_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BatteryWarningReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BatteryWarningReportPacket.kt new file mode 100644 index 0000000000..260a5d7e02 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BatteryWarningReportPacket.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BatteryWarningReportPacket + */ +class BatteryWarningReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0xD7.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BatteryWarningReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BatteryWarningReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.batteryWaningGrade = getByteToInt(bufferData) + diaconnG8Pump.batteryWaningProcess = getByteToInt(bufferData) + diaconnG8Pump.batteryWaningRemain = getByteToInt(bufferData) + + aapsLogger.debug(LTag.PUMPCOMM, "batteryWaningGrade --> ${diaconnG8Pump.batteryWaningGrade} (1:info, 2: warning , 3: major , 4: critical)") + aapsLogger.debug(LTag.PUMPCOMM, "batteryWaningProcess --> ${diaconnG8Pump.batteryWaningProcess} (1:skip, 2: stop , 3: ignore ) ") + aapsLogger.debug(LTag.PUMPCOMM, "batteryWaningRemain --> ${diaconnG8Pump.batteryWaningRemain} (0~100%) )") + + } + + override fun getFriendlyName(): String { + return "PUMP_BATTERY_WARNING_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquirePacket.kt new file mode 100644 index 0000000000..6a0bc9e4cb --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquirePacket.kt @@ -0,0 +1,35 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + + * BigLogInquirePacket + */ +class BigLogInquirePacket( + injector: HasAndroidInjector, + private val start: Int, + private val end:Int, + private val delay:Int +) : DiaconnG8Packet(injector ) { + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x72 + aapsLogger.debug(LTag.PUMPCOMM, "BigLogInquirePacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.putShort(start.toShort()) + buffer.putShort(end.toShort()) + buffer.put(delay.toByte()) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_BIG_LOG_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt new file mode 100644 index 0000000000..d703cf70e8 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt @@ -0,0 +1,774 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.common.RecordTypes +import info.nightscout.androidaps.diaconn.database.DiaconnHistoryRecord +import info.nightscout.androidaps.diaconn.database.DiaconnHistoryRecordDao +import info.nightscout.androidaps.diaconn.pumplog.* +import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.PumpDescription +import info.nightscout.androidaps.interfaces.PumpSync +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage +import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.apache.commons.lang3.time.DateUtils +import org.joda.time.DateTime +import javax.inject.Inject + +/** + * BigLogInquireResponsePacket + */ +class BigLogInquireResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector) { + + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage + @Inject lateinit var temporaryBasalStorage: TemporaryBasalStorage + @Inject lateinit var sp: SP + @Inject lateinit var pumpSync: PumpSync + @Inject lateinit var diaconnHistoryRecordDao: DiaconnHistoryRecordDao + var result = 0// 조회결과 + private var pumpDesc = PumpDescription(PumpType.DIACONN_G8) + init { + msgType = 0xb2.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BigLogInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BigLogInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) // 데이타 영역 15바이트 버퍼 + val result2 = getByteToInt(bufferData) // 조회결과 1 byte + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + val logLength = getByteToInt(bufferData) // 로그의 갯수. 1byte + + // initalize + val dailyMaxvalInfo = mutableMapOf>() + dailyMaxvalInfo[""] = mutableMapOf() + + // 15 byte를 로그갯수만큼 돌기. + for(i in 0 until logLength) { + val wrapingCount = getByteToInt(bufferData) // 1byte + val logNum = getShortToInt(bufferData) // 2byte + // log Data Parsing + val logdata = byteArrayOf( + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData), + PumplogUtil.getByte(bufferData) + ) + + diaconnG8Pump.apsWrappingCount = wrapingCount + diaconnG8Pump.apslastLogNum = logNum + sp.putInt(resourceHelper.gs(R.string.apslastLogNum), logNum) + sp.putInt(resourceHelper.gs(R.string.apsWrappingCount), wrapingCount) + + // process Log to DB + val logDataToHexString = toNarrowHex(logdata) + val pumplogKind: Byte = PumplogUtil.getKind(logDataToHexString) + var status: String + val diaconnG8HistoryRecord = DiaconnHistoryRecord(0) + when(pumplogKind) { + + LOG_INJECT_MEAL_SUCCESS.LOG_KIND -> { // 8(식사주입성공) + val logItem = LOG_INJECT_MEAL_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(logDateTime, logItem.injectAmount / 100.0) + + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.injectAmount / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT MEALBOLUS (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Bolus: " + logItem.injectAmount / 100.0 + "U ") + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "M" // meal bolus + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logmealsuccess) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "MEALBOLUSSUCCESS" + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_MEAL_FAIL.LOG_KIND -> { + val logItem = LOG_INJECT_MEAL_FAIL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(logDateTime, logItem.injectAmount / 100.0) + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.injectAmount / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT MEALBOLUS (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Bolus: " + logItem.injectAmount / 100.0 + "U ") + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = if ((logItem.injectAmount / 100.0) < 0) 0.0 else (logItem.injectAmount / 100.0) + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "M" // Meal bolus + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logmealfail) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "MEALBOLUSFAIL " + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_NORMAL_SUCCESS.LOG_KIND -> { + val logItem = LOG_INJECT_NORMAL_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(logDateTime, logItem.injectAmount / 100.0) + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.injectAmount / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Bolus: " + logItem.injectAmount / 100.0 + "U ") + + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "B" // bolus + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logsuccess) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "BOLUSSUCCESS" + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_NORMAL_FAIL.LOG_KIND -> { + val logItem = LOG_INJECT_NORMAL_FAIL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + // APS DB process + val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(logDateTime, logItem.injectAmount / 100.0) + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.injectAmount / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Bolus: " + logItem.injectAmount / 100.0 + "U ") + + + // Diaconn History Process + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = if ((logItem.injectAmount / 100.0) < 0) 0.0 else (logItem.injectAmount / 100.0) + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "B" // bolus + diaconnG8HistoryRecord.stringValue = getReasonName(pumplogKind, logItem.reason) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "BOLUSFAIL " + dateUtil.timeString(logDateTime) + } + + LOG_SET_SQUARE_INJECTION.LOG_KIND -> { + val logItem = LOG_SET_SQUARE_INJECTION.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + val newRecord = pumpSync.syncExtendedBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.setAmount / 100.0, + duration = T.mins((logItem.getInjectTime() * 10).toLong()).msecs(), + isEmulatingTB = false, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTART (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Amount: " + logItem.setAmount / 100.0 + "U Duration: " + logItem.getInjectTime() * 10 + "min") + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.setAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logsquarestart) + diaconnG8HistoryRecord.bolusType = "E" // Extended + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "EXTENDEDBOLUSSTART " + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_SQUARE_SUCCESS.LOG_KIND -> { + val logItem = LOG_INJECT_SQUARE_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logsquaresuccess) + diaconnG8HistoryRecord.bolusType = "E" // Extended + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "EXTENDEDBOLUSEND " + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_SQUARE_FAIL.LOG_KIND -> { + val logItem = LOG_INJECT_SQUARE_FAIL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + val newRecord = pumpSync.syncStopExtendedBolusWithPumpId( + timestamp = logDateTime, + endPumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTOP (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Delivered: " + logItem.injectAmount / 100.0 + "U RealDuration: " + logItem.getInjectTime() + "min") + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.stringValue = getReasonName(pumplogKind, logItem.reason) + diaconnG8HistoryRecord.bolusType = "E" + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "EXTENDEDBOLUSFAIL " + dateUtil.timeString(logDateTime) + } + + LOG_SET_DUAL_INJECTION.LOG_KIND -> { + val logItem = LOG_SET_DUAL_INJECTION.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + // dual square 처리. + val newRecord = pumpSync.syncExtendedBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.setSquareAmount / 100.0, + duration = T.mins((logItem.getInjectTime() * 10).toLong()).msecs(), + isEmulatingTB = false, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT EXTENDEDSTART (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Amount: " + logItem.setSquareAmount / 100.0 + "U Duration: " + logItem.getInjectTime() * 10 + "min") + + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.setSquareAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() * 10 // (1~30) 1:10min 30:300min + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logdualsquarestart) + diaconnG8HistoryRecord.bolusType = "D" // Extended + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + + status = "DUALEXTENTEDSTART " + dateUtil.timeString(logDateTime) + } + + LOG_INJECTION_DUAL_NORMAL.LOG_KIND -> { + val logItem = LOG_INJECTION_DUAL_NORMAL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(logDateTime, logItem.injectAmount / 100.0) + val newRecord = pumpSync.syncBolusWithPumpId( + timestamp = logDateTime, + amount = logItem.injectAmount / 100.0, + type = detailedBolusInfo?.bolusType, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Bolus: " + logItem.injectAmount / 100.0 + "U Duration: " + logItem.getInjectTime() + "min") + + //Diaconn History + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.injectAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "D" // bolus + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logdualnormalsuccess) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "DUALBOLUS" + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_DUAL_SUCCESS.LOG_KIND -> { + val logItem = LOG_INJECT_DUAL_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.injectSquareAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "D" + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logdualsquaresuccess) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "DUALBOLUS SQUARESUCCESS " + dateUtil.timeString(logDateTime) + } + + LOG_INJECT_DUAL_FAIL.LOG_KIND -> { + val logItem = LOG_INJECT_DUAL_FAIL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BOLUS + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.injectNormAmount / 100.0 + logItem.injectSquareAmount / 100.0 + diaconnG8HistoryRecord.duration = logItem.getInjectTime() + diaconnG8HistoryRecord.bolusType = "D" + diaconnG8HistoryRecord.stringValue = getReasonName(pumplogKind, logItem.reason) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "DUALBOLUS FAIL " + dateUtil.timeString(logDateTime) + } + + LOG_INJECTION_1HOUR_BASAL.LOG_KIND -> { + val logItem = LOG_INJECTION_1HOUR_BASAL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_BASALHOUR + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.beforeAmount / 100.0 + diaconnG8HistoryRecord.stringValue = "TB before: ${logItem.beforeAmount / 100.0} / TB after: ${logItem.afterAmount / 100.0}" + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "1HOUR BASAL " + dateUtil.dateAndTimeString(logDateTime) + } + + LOG_SUSPEND_V2.LOG_KIND -> { + val logItem = LOG_SUSPEND_V2.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_SUSPEND + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_lgosuspend, logItem.getBasalPattern()) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "SUSPEND " + dateUtil.timeString(logDateTime) + } + + LOG_SUSPEND_RELEASE_V2.LOG_KIND -> { + val logItem = LOG_SUSPEND_RELEASE_V2.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_SUSPEND + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_lgorelease, logItem.getBasalPattern()) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "SUSPENDRELEASE " + dateUtil.timeString(logDateTime) + } + + LOG_CHANGE_INJECTOR_SUCCESS.LOG_KIND -> { + val logItem = LOG_CHANGE_INJECTOR_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + if (sp.getBoolean(R.string.key_diaconn_g8_loginsulinchange, true)) { + val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp = logDateTime, + type = DetailedBolusInfo.EventType.INSULIN_CHANGE, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString() + ) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT INSULINCHANGE(" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Amount: " + logItem.remainAmount / 100.0 + "U") + } + + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.remainAmount / 100.0 + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_loginjectorprime, logItem.primeAmount / 100.0) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "INSULINCHANGE " + dateUtil.timeString(logDateTime) + } + + LOG_CHANGE_TUBE_SUCCESS.LOG_KIND -> { + val logItem = LOG_CHANGE_TUBE_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + if (sp.getBoolean(R.string.key_diaconn_g8_logtubechange, true)) { + val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp = logDateTime, + type = DetailedBolusInfo.EventType.NOTE, + note = resourceHelper.gs(R.string.diaconn_g8_logtubeprime, logItem.primeAmount / 100.0), + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString() + ) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT TUBECHANGE(" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Amount: " + logItem.primeAmount / 100.0 + "U") + } + + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.remainAmount / 100.0 + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logtubeprime, logItem.primeAmount / 100.0) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "TUBECHANGE " + dateUtil.timeString(logDateTime) + } + + LOG_INJECTION_1DAY.LOG_KIND -> { // Daily Bolus Log + val logItem = LOG_INJECTION_1DAY.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_DAILY + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.dailyBolus = logItem.extAmount / 100.0 + logItem.mealAmount / 100.0 + + val recordDateStr = "" + diaconnG8HistoryRecord.timestamp + var recordMap: MutableMap = mutableMapOf("dummy" to 0.0) + + if (dailyMaxvalInfo.containsKey(recordDateStr)) { + recordMap = dailyMaxvalInfo[recordDateStr]!! + } else { + recordMap["bolus"] = 0.0 + recordMap["basal"] = 0.0 + dailyMaxvalInfo[recordDateStr] = recordMap + } + + if (diaconnG8HistoryRecord.dailyBolus > recordMap["bolus"]!!) { + recordMap["bolus"] = diaconnG8HistoryRecord.dailyBolus + } else { + diaconnG8HistoryRecord.dailyBolus = recordMap["bolus"]!! + } + + if (recordMap["basal"]!! > 0.0) { + diaconnG8HistoryRecord.dailyBasal = recordMap["basal"]!! + } + + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + + //If it is a TDD, store it for stats also. + pumpSync.createOrUpdateTotalDailyDose( + timestamp = diaconnG8HistoryRecord.timestamp, + bolusAmount = diaconnG8HistoryRecord.dailyBolus, + basalAmount = diaconnG8HistoryRecord.dailyBasal, + totalAmount = 0.0, + pumpId = null, + pumpType = PumpType.DIACONN_G8, + diaconnG8Pump.serialNo.toString() + ) + + status = "DAILYBOLUS " + dateUtil.timeString(logDateTime) + } + + LOG_INJECTION_1DAY_BASAL.LOG_KIND -> { // Daily Basal Log + val logItem = LOG_INJECTION_1DAY_BASAL.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_DAILY + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.dailyBasal = logItem.amount / 100.0 + + val recordDateStr = "" + diaconnG8HistoryRecord.timestamp + var recordMap: MutableMap = mutableMapOf("dummy" to 0.0) + + if (dailyMaxvalInfo.containsKey(recordDateStr)) { + recordMap = dailyMaxvalInfo[recordDateStr]!! + } else { + recordMap["bolus"] = 0.0 + recordMap["basal"] = 0.0 + dailyMaxvalInfo[recordDateStr] = recordMap + } + + if (diaconnG8HistoryRecord.dailyBasal > recordMap["basal"]!!) { + recordMap["basal"] = diaconnG8HistoryRecord.dailyBasal + } else { + diaconnG8HistoryRecord.dailyBasal = recordMap["basal"]!! + } + + if (recordMap["bolus"]!! > 0.0) { + diaconnG8HistoryRecord.dailyBolus = recordMap["bolus"]!! + } + + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + + //If it is a TDD, store it for stats also. + // pumpSync.createOrUpdateTotalDailyDose( + // timestamp = diaconnG8HistoryRecord.timestamp, + // bolusAmount = diaconnG8HistoryRecord.dailyBolus, + // basalAmount = diaconnG8HistoryRecord.dailyBasal, + // totalAmount = 0.0, + // pumpId = null, + // pumpType = PumpType.DIACONN_G8, + // diaconnG8Pump.serialNo.toString() + // ) + + + status = "DAILYBASAL " + dateUtil.timeString(logDateTime) + } + + LOG_CHANGE_NEEDLE_SUCCESS.LOG_KIND -> { + val logItem = LOG_CHANGE_NEEDLE_SUCCESS.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + if (sp.getBoolean(R.string.key_diaconn_g8_logneedlechange, true)) { + val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp = logDateTime, + type = DetailedBolusInfo.EventType.CANNULA_CHANGE, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString() + ) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT NEEDLECHANGE(" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Amount: " + logItem.remainAmount / 100.0 + "U") + } + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_REFILL + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.remainAmount / 100.0 + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logneedleprime, logItem.primeAmount / 100.0) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "NEEDLECHANGE " + dateUtil.timeString(logDateTime) + } + + LOG_TB_START_V3.LOG_KIND -> { + val logItem = LOG_TB_START_V3.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + var absoluteRate = 0.0 + if (logItem.getTbInjectRateRatio() >= 50000) { + val tempBasalPercent = logItem.getTbInjectRateRatio() - 50000 + absoluteRate = pumpDesc.pumpType.determineCorrectBasalSize(diaconnG8Pump.baseAmount * (tempBasalPercent / 100.0)) + } + + if (logItem.getTbInjectRateRatio() in 1000..1600) { + absoluteRate = (logItem.getTbInjectRateRatio() - 1000) / 100.0 + } + + val temporaryBasalInfo = temporaryBasalStorage.findTemporaryBasal(logDateTime, absoluteRate) + val newRecord = pumpSync.syncTemporaryBasalWithPumpId( + timestamp = logDateTime, + rate = absoluteRate, + duration = T.mins((logItem.tbTime * 15).toLong()).msecs(), + isAbsolute = true, + type = temporaryBasalInfo?.type, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT TEMPSTART (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " Ratio: " + absoluteRate + "U Duration: " + logItem.tbTime * 15 + "min") + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_TB + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.duration = logItem.tbTime * 15 + diaconnG8HistoryRecord.value = absoluteRate + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logtempstart) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "TEMPSTART " + dateUtil.timeString(logDateTime) + } + + LOG_TB_STOP_V3.LOG_KIND -> { + val logItem = LOG_TB_STOP_V3.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + var absoluteRate = 0.0 + if (logItem.getTbInjectRateRatio() >= 50000) { + val tempBasalPercent = logItem.getTbInjectRateRatio() - 50000 + absoluteRate = diaconnG8Pump.baseAmount * (tempBasalPercent / 100.0) + } + if (logItem.getTbInjectRateRatio() in 1000..1600) { + absoluteRate = (logItem.getTbInjectRateRatio() - 1000) / 100.0 + } + + val newRecord = pumpSync.syncStopTemporaryBasalWithPumpId( + timestamp = logDateTime, + endPumpId = dateUtil.now(), + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString()) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT TEMPSTOP (" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")") + + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_TB + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = absoluteRate + diaconnG8HistoryRecord.stringValue = getReasonName(pumplogKind, logItem.reason) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "TEMPSTOP " + dateUtil.timeString(logDateTime) + } + + LOG_ALARM_BATTERY.LOG_KIND -> { // BATTERY SHORTAGE ALARM + val logItem = LOG_ALARM_BATTERY.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logbatteryshorage) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "BATTERYALARM " + dateUtil.timeString(logDateTime) + } + + LOG_ALARM_BLOCK.LOG_KIND -> { // INJECTION BLOCKED ALARM + val logItem = LOG_ALARM_BLOCK.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.amount / 100.0 + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_logalarmblock, getReasonName(pumplogKind, logItem.reason)) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "BLOCKALARM " + dateUtil.timeString(logDateTime) + } + + LOG_ALARM_SHORTAGE.LOG_KIND -> { // INSULIN SHORTAGE ALARM + val logItem = LOG_ALARM_SHORTAGE.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.value = logItem.remain.toDouble() + diaconnG8HistoryRecord.stringValue = resourceHelper.gs(R.string.diaconn_g8_loginsulinshorage) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + status = "SHORTAGEALARM " + dateUtil.timeString(logDateTime) + } + + LOG_RESET_SYS_V3.LOG_KIND -> { + val logItem = LOG_RESET_SYS_V3.parse(logDataToHexString) + aapsLogger.debug(LTag.PUMPCOMM, "$logItem ") + + val logStartDate = DateUtils.parseDate(logItem.dttm, "yyyy-MM-dd HH:mm:ss") + val logDateTime = logStartDate.time + + diaconnG8HistoryRecord.code = RecordTypes.RECORD_TYPE_ALARM + diaconnG8HistoryRecord.timestamp = logDateTime + diaconnG8HistoryRecord.stringValue = getReasonName(pumplogKind, logItem.reason) + diaconnHistoryRecordDao.createOrUpdate(diaconnG8HistoryRecord) + if (logItem.reason == 3.toByte()) { + if (sp.getBoolean(R.string.key_diaconn_g8_logbatterychange, true)) { + val newRecord = pumpSync.insertTherapyEventIfNewWithTimestamp( + timestamp = logDateTime, + type = DetailedBolusInfo.EventType.PUMP_BATTERY_CHANGE, + pumpId = logDateTime, + pumpType = PumpType.DIACONN_G8, + pumpSerial = diaconnG8Pump.serialNo.toString() + ) + aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT BATTERYCHANGE(" + pumplogKind + ") " + dateUtil.dateAndTimeString(logDateTime) + " (" + logDateTime + ")" + " remainAmount: " + logItem.batteryRemain.toInt() + "%") + } + } + status = "RESET " + dateUtil.timeString(logDateTime) + } + + else -> { + status = resourceHelper.gs(R.string.diaconn_g8_logsyncinprogress) + rxBus.send(EventPumpStatusChanged(status)) + continue + } + } + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status)) + } + } + + override fun getFriendlyName(): String { + return "BIG_LOG_INQUIRE_RESPONSE" + } + + private fun getReasonName(logKind: Byte, reason: Byte): String{ + val logInjectNormalFail: Byte = 0x0B + val logInjectSquareFail: Byte = 0x0E + val logInjectDualFail: Byte = 0x11 + val logTBStopV3: Byte = 0x13 + val logResetSysV3: Byte = 0x01 + val logALarmBlock: Byte = 0x29 + + return when (logKind) { + logInjectNormalFail, logInjectSquareFail, logInjectDualFail, logTBStopV3 -> failLog(reason) + logResetSysV3 -> resetLog(reason) + logALarmBlock -> blockLog(reason) + else -> "" + } + } + + private fun failLog(reason: Byte): String { + return when (reason) { + //1=Injection blockage, 2=Battery shortage, 3=Drug shortage, 4=User shutdown, 5=System reset, 6=Other, 7=Emergency shutdown + 0.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasoncomplete) + 1.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasoninjectonblock) + 2.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonbatteryshortage) + 3.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasoninsulinshortage) + 4.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonuserstop) + 5.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonsystemreset) + 6.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonother) + 7.toByte() -> resourceHelper.gs(R.string.diaconn_g8_reasonemergencystop) + else -> "No Reason" + } + } + + private fun resetLog(reason: Byte): String { + return when (reason.toInt()) { + 1 -> resourceHelper.gs(R.string.diaconn_g8_resetfactoryreset) + 2 -> resourceHelper.gs(R.string.diaconn_g8_resetemergencyoff) + 3 -> resourceHelper.gs(R.string.diaconn_g8_resetbatteryreplacement) + 4 -> resourceHelper.gs(R.string.diaconn_g8_resetaftercalibration) + 5 -> resourceHelper.gs(R.string.diaconn_g8_resetpreshipment) + 9 -> resourceHelper.gs(R.string.diaconn_g8_resetunexpected) + else -> "" + } + } + + private fun blockLog(reason: Byte): String { + return when (reason.toInt()) { + 1 -> resourceHelper.gs(R.string.diacon_g8_blockbasal) + 2 -> resourceHelper.gs(R.string.diacon_g8_blockmealbolus) + 3 -> resourceHelper.gs(R.string.diacon_g8_blocknormalbolus) + 4 -> resourceHelper.gs(R.string.diacon_g8_blocksquarebolus) + 5 -> resourceHelper.gs(R.string.diacon_g8_blockdualbolus) + 6 -> resourceHelper.gs(R.string.diacon_g8_blockreplacetube) + 7 -> resourceHelper.gs(R.string.diacon_g8_blockreplaceneedle) + 8 -> resourceHelper.gs(R.string.diacon_g8_blockreplacesyringe) + else -> "" + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquirePacket.kt new file mode 100644 index 0000000000..ddf9a2f465 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquirePacket.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + + * BigMainInfoInquirePacket + */ +class BigMainInfoInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x73 + aapsLogger.debug(LTag.PUMPCOMM, "BigMainInfoInquirePacket init") + + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_BIG_MAIN_INFO_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt new file mode 100644 index 0000000000..79d9de8c99 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt @@ -0,0 +1,359 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.pumplog.PumplogUtil +import info.nightscout.androidaps.interfaces.PumpDescription +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import org.joda.time.DateTime +import javax.inject.Inject +import kotlin.math.floor + +/** + * BigMainInfoInquireResponsePacket + */ +class BigMainInfoInquireResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var sp: SP + @Inject lateinit var resourceHelper: ResourceHelper + private var pumpDesc = PumpDescription(PumpType.DIACONN_G8) + + init { + msgType = 0xb3.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BigMainInfoInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BigMainInfoInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) // 결과비트 상위 4비트 제거 + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + // 1. pump system setting info + diaconnG8Pump.systemRemainInsulin = floor(getShortToInt(bufferData) / 100.0) // 인슐린 잔량 + diaconnG8Pump.systemRemainBattery = getByteToInt(bufferData) // 베터리잔량(1~100%) + diaconnG8Pump.systemBasePattern = getByteToInt(bufferData) // 기저주입 패턴(0=없음, 1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2) + diaconnG8Pump.systemTbStatus = getByteToInt(bufferData) // 임시기저 상태(1=임시기저 중, 2=임시기저 해제) + diaconnG8Pump.systemInjectionMealStatus = getByteToInt(bufferData) // 식사주입 상태(1=주입중, 2=주입상태아님) + diaconnG8Pump.systemInjectionSnackStatus = getByteToInt(bufferData) // 일반간식 주입 상태(1=주입중, 2=주입상태아님) + diaconnG8Pump.systemInjectionSquareStatue = getByteToInt(bufferData) // 스퀘어회식 주입 상태(1=주입중, 2=주입상태아님) + diaconnG8Pump.systemInjectionDualStatus = getByteToInt(bufferData) // 더블회식 주입 상태(1=주입중, 2=주입상태아님) + + // 2. basal injection suspend status (1:stop, 2:release) + diaconnG8Pump.basePauseStatus = getByteToInt(bufferData) // 상태(1=정지,2=해제) + + // 3. Pump time + diaconnG8Pump.year = getByteToInt(bufferData) + 2000 // 년 (18~99) + diaconnG8Pump.month = getByteToInt(bufferData) // 월 (1~12) + diaconnG8Pump.day = getByteToInt(bufferData) // 일 (1~31) + diaconnG8Pump.hour = getByteToInt(bufferData) // 시 (0~23) + diaconnG8Pump.minute = getByteToInt(bufferData) // 분 (0~59) + diaconnG8Pump.second = getByteToInt(bufferData) // 초 (0~59) + + //4. pump system info + diaconnG8Pump.country = getByteToInt(bufferData).toChar().toString().toInt() // ASCII + diaconnG8Pump.productType = getByteToInt(bufferData).toChar().toString().toInt() // ASCII + diaconnG8Pump.makeYear = getByteToInt(bufferData) + diaconnG8Pump.makeMonth = getByteToInt(bufferData) + diaconnG8Pump.makeDay = getByteToInt(bufferData) + diaconnG8Pump.lotNo = getByteToInt(bufferData)// LOT NO + diaconnG8Pump.serialNo = getShortToInt(bufferData) + diaconnG8Pump.majorVersion = getByteToInt(bufferData) + diaconnG8Pump.minorVersion = getByteToInt(bufferData) + + sp.putString(resourceHelper.gs(R.string.pumpversion), diaconnG8Pump.majorVersion.toString() + "." + diaconnG8Pump.minorVersion.toString()) + + // 5. pump log status + diaconnG8Pump.pumpLastLogNum = getShortToInt(bufferData) // last saved log no + diaconnG8Pump.pumpWrappingCount = getByteToInt(bufferData) // wrapping count + + // 6. bolus speed status. + diaconnG8Pump.speed = getByteToInt(bufferData) // 식사주입속도 + + // 7. Tempbasal status + diaconnG8Pump.tbStatus = getByteToInt(bufferData) // 임시기저 상태 + diaconnG8Pump.tbTime = getByteToInt(bufferData) // 임시기저시간 + diaconnG8Pump.tbInjectRateRatio = getShortToInt(bufferData) //임시기저 주입량/률 + diaconnG8Pump.tbElapsedTime = getShortToInt(bufferData) // 임시기저 경과시간 + + // 8. Basal status + diaconnG8Pump.baseStatus = getByteToInt(bufferData) // 기저주입 상태 + diaconnG8Pump.baseHour = getByteToInt(bufferData) // 현재 주입시간 + diaconnG8Pump.baseAmount = getShortToInt(bufferData) / 100.0 // 주입설정량 + diaconnG8Pump.baseInjAmount = getShortToInt(bufferData) / 100.0 // 현재 주입량 + + // 9. meal bolus status + diaconnG8Pump.mealKind = getByteToInt(bufferData) //식사주입 종류 + diaconnG8Pump.mealStartTime = getIntToInt(bufferData) // 주입시작시간 + diaconnG8Pump.mealStatus = getByteToInt(bufferData) // 주입상태 + diaconnG8Pump.mealAmount = getShortToInt(bufferData) / 100.0 // 주입설정량 + diaconnG8Pump.mealInjAmount = getShortToInt(bufferData) / 100.0 // 주입량 + diaconnG8Pump.mealSpeed = getByteToInt(bufferData) // 주입속도 + + // 10. snack bolus status + diaconnG8Pump.snackStatus = getByteToInt(bufferData) //주입상태 + diaconnG8Pump.snackAmount = getShortToInt(bufferData) / 100.0 // 주입설정량 + diaconnG8Pump.snackInjAmount = getShortToInt(bufferData) / 100.0 // 현재주입량 + diaconnG8Pump.snackSpeed = getByteToInt(bufferData) //주입속도 + + // 11. square(extended) bolus status + diaconnG8Pump.squareStatus = getByteToInt(bufferData) // 주입상태 + diaconnG8Pump.squareTime = getShortToInt(bufferData) // 설정 주입시간(10~300분) + diaconnG8Pump.squareInjTime = getShortToInt(bufferData) // 경과 주입시간(10~300분) + diaconnG8Pump.squareAmount = getShortToInt(bufferData) / 100.0 // 주입 설정량 + diaconnG8Pump.squareInjAmount = getShortToInt(bufferData) / 100.0 // 현재 주입량 + + // 12. daul bolus status + diaconnG8Pump.dualStatus = getByteToInt(bufferData) // 주입상태 + diaconnG8Pump.dualAmount = getShortToInt(bufferData) / 100.0 // 일반주입 설정량 + diaconnG8Pump.dualInjAmount = getShortToInt(bufferData) / 100.0 // 일반주입량 + diaconnG8Pump.dualSquareTime = getShortToInt(bufferData) // 스퀘어주입 설정시간(10~300분) + diaconnG8Pump.dualInjSquareTime = getShortToInt(bufferData) // 스퀘어주입 경과시간(10~300분) + diaconnG8Pump.dualSquareAmount = getShortToInt(bufferData) / 100.0 // 스퀘어주입 설정량 + diaconnG8Pump.dualInjSquareAmount = getShortToInt(bufferData) / 100.0 // 스퀘어주입량 + + // 13. last injection status + diaconnG8Pump.recentKind1 = getByteToInt(bufferData) // 최근-1 주입 종류(1=식사, 2=일반간식, 3=스퀘어회식, 4=더블회식) + diaconnG8Pump.recentTime1 = getIntToInt(bufferData) // 최근-1 주입 시간 + diaconnG8Pump.recentAmount1 = getShortToInt(bufferData) / 100.0 // 최근-1 주입량 + diaconnG8Pump.recentKind2 = getByteToInt(bufferData) // 최근-2 주입 종류(1=식사, 2=일반간식, 3=스퀘어회식, 4=더블회식) + diaconnG8Pump.recentTime2 = getIntToInt(bufferData) // 최근-2 주입 시간 + diaconnG8Pump.recentAmount2 = getShortToInt(bufferData) / 100.0 // 최근-2 주입량 + + // 14. daily injection status + diaconnG8Pump.todayBaseAmount = getShortToInt(bufferData) / 100.0 // 기저주입 총량 + diaconnG8Pump.todayMealAmount = getShortToInt(bufferData) / 100.0 // 식사주입 총량 + diaconnG8Pump.todaySnackAmount = getShortToInt(bufferData) / 100.0 // 회식주입 총량 + + // 15. meat setting status + diaconnG8Pump.morningHour = getByteToInt(bufferData) // 아침 개시 시간(0~23) + diaconnG8Pump.morningAmount = getShortToInt(bufferData) / 100.0 // 아침 식전량 + diaconnG8Pump.lunchHour = getByteToInt(bufferData) // 점심 개시 시간(0~23) + diaconnG8Pump.lunchAmount = getShortToInt(bufferData) / 100.0 // 점심 식전량 + diaconnG8Pump.dinnerHour = getByteToInt(bufferData) // 저녁 개시 시간(0~23) + diaconnG8Pump.dinnerAmount = getShortToInt(bufferData) / 100.0 // 저녁 식전량 + + // 16. basal injection status at this hour + diaconnG8Pump.currentBasePattern = getByteToInt(bufferData) // 패턴 종류 (1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2) + diaconnG8Pump.currentBaseHour = getByteToInt(bufferData) // 현재주입시간(0~23) + diaconnG8Pump.currentBaseTbBeforeAmount = getShortToInt(bufferData) / 100.0 // 해당시간의 임시기저 계산 전 기저주입량: 기저주입막힘 발생 시 기저주입 막힘량 제외, 기저정지로 인해 주입되지 않은 량 제외, 리셋으로 인해 주입되지 않은 량 제외(47.5=4750) + diaconnG8Pump.currentBaseTbAfterAmount = getShortToInt(bufferData)/ 100.0 // 해당시간의 임시기저 계산 후 기저주입량: 기저주입막힘 발생 시 기저주입 막힘량 제외, 기저정지로 인해 주입되지 않은 량 제외, 리셋으로 인해 주입되지 않은 량 제외(47.5=4750) + + // 17. saved basal pattern status + diaconnG8Pump.baseAmount1 = getShortToInt(bufferData) / 100.0 // 주입량 1(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount2 = getShortToInt(bufferData) / 100.0 // 주입량 2(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount3 = getShortToInt(bufferData) / 100.0 // 주입량 3(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount4 = getShortToInt(bufferData) / 100.0 // 주입량 4(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount5 = getShortToInt(bufferData) / 100.0 // 주입량 5(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount6 = getShortToInt(bufferData) / 100.0 // 주입량 6(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount7 = getShortToInt(bufferData) / 100.0 // 주입량 7(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount8 = getShortToInt(bufferData) / 100.0 // 주입량 8(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount9 = getShortToInt(bufferData) / 100.0 // 주입량 9(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount10 = getShortToInt(bufferData) / 100.0 // 주입량 10(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount11 = getShortToInt(bufferData) / 100.0 // 주입량 11(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount12 = getShortToInt(bufferData) / 100.0 // 주입량 12(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount13 = getShortToInt(bufferData) / 100.0 // 주입량 13(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount14 = getShortToInt(bufferData) / 100.0 // 주입량 14(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount15 = getShortToInt(bufferData) / 100.0 // 주입량 15(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount16 = getShortToInt(bufferData) / 100.0 // 주입량 16(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount17 = getShortToInt(bufferData) / 100.0 // 주입량 17(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount18 = getShortToInt(bufferData) / 100.0 // 주입량 18(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount19 = getShortToInt(bufferData) / 100.0 // 주입량 19(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount20 = getShortToInt(bufferData) / 100.0 // 주입량 20(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount21 = getShortToInt(bufferData) / 100.0 // 주입량 21(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount22 = getShortToInt(bufferData) / 100.0 // 주입량 22(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount23 = getShortToInt(bufferData) / 100.0 // 주입량 23(량*100, 23.25->2325, 15.2->1520) + diaconnG8Pump.baseAmount24 = getShortToInt(bufferData) / 100.0 // 주입량 24(량*100, 23.25->2325, 15.2->1520) + + // tempbasal setting status + diaconnG8Pump.isTempBasalInProgress = diaconnG8Pump.tbStatus == 1 + aapsLogger.debug(LTag.PUMPCOMM, "isTempBasalInProgress > " + diaconnG8Pump.isTempBasalInProgress) + + // if rate type is percent + if (diaconnG8Pump.tbInjectRateRatio >= 50000) { + diaconnG8Pump.tempBasalPercent = diaconnG8Pump.tbInjectRateRatio - 50000 + + var absoluteValue = diaconnG8Pump.baseAmount * (diaconnG8Pump.tempBasalPercent / 100.0) + absoluteValue = pumpDesc.pumpType.determineCorrectBasalSize(absoluteValue) + diaconnG8Pump.tempBasalAbsoluteRate = absoluteValue + } + + // if rate type is absolute + if(diaconnG8Pump.tbInjectRateRatio in 1000..1600) { + diaconnG8Pump.tbInjectAbsoluteValue = (diaconnG8Pump.tbInjectRateRatio -1000) / 100.0 + diaconnG8Pump.tempBasalAbsoluteRate = diaconnG8Pump.tbInjectAbsoluteValue + } + + // extended bolus status + diaconnG8Pump.isExtendedInProgress = diaconnG8Pump.squareStatus == 1 || diaconnG8Pump.dualStatus == 1 + if(diaconnG8Pump.squareStatus == 1) { //square + diaconnG8Pump.extendedBolusMinutes = diaconnG8Pump.squareTime + diaconnG8Pump.extendedBolusAbsoluteRate = diaconnG8Pump.squareAmount + diaconnG8Pump.extendedBolusPassedMinutes = diaconnG8Pump.squareInjTime + diaconnG8Pump.extendedBolusRemainingMinutes = diaconnG8Pump.squareTime - diaconnG8Pump.squareInjTime + diaconnG8Pump.extendedBolusDeliveredSoFar = diaconnG8Pump.squareInjAmount + } else if (diaconnG8Pump.dualStatus == 1) { //dual + diaconnG8Pump.extendedBolusMinutes = diaconnG8Pump.dualSquareTime + diaconnG8Pump.extendedBolusAbsoluteRate = diaconnG8Pump.dualSquareAmount + diaconnG8Pump.extendedBolusPassedMinutes = diaconnG8Pump.dualInjSquareTime + diaconnG8Pump.extendedBolusRemainingMinutes = diaconnG8Pump.dualSquareTime - diaconnG8Pump.dualInjSquareTime + diaconnG8Pump.extendedBolusDeliveredSoFar = diaconnG8Pump.dualInjSquareAmount + } + + // pump time setting 'yyyy-MM-dd'T'HH:mm:ssZ' “2019-07-04T12:30:30+0530” + val time = DateTime(diaconnG8Pump.year, diaconnG8Pump.month, diaconnG8Pump.day, diaconnG8Pump.hour, diaconnG8Pump.minute, diaconnG8Pump.second) + diaconnG8Pump.setPumpTime(time.millis) + aapsLogger.debug(LTag.PUMPCOMM, "Pump time " + dateUtil.dateAndTimeString(time.millis)) + + // basal pattern from pump + diaconnG8Pump.pumpProfiles = Array(4) { Array(24) { 0.0 } } + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][0] = diaconnG8Pump.baseAmount1 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][1] = diaconnG8Pump.baseAmount2 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][2] = diaconnG8Pump.baseAmount3 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][3] = diaconnG8Pump.baseAmount4 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][4] = diaconnG8Pump.baseAmount5 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][5] = diaconnG8Pump.baseAmount6 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][6] = diaconnG8Pump.baseAmount7 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][7] = diaconnG8Pump.baseAmount8 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][8] = diaconnG8Pump.baseAmount9 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][9] = diaconnG8Pump.baseAmount10 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][10] = diaconnG8Pump.baseAmount11 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][11] = diaconnG8Pump.baseAmount12 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][12] = diaconnG8Pump.baseAmount13 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][13] = diaconnG8Pump.baseAmount14 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][14] = diaconnG8Pump.baseAmount15 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][15] = diaconnG8Pump.baseAmount16 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][16] = diaconnG8Pump.baseAmount17 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][17] = diaconnG8Pump.baseAmount18 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][18] = diaconnG8Pump.baseAmount19 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][19] = diaconnG8Pump.baseAmount20 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][20] = diaconnG8Pump.baseAmount21 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][21] = diaconnG8Pump.baseAmount22 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][22] = diaconnG8Pump.baseAmount23 + diaconnG8Pump.pumpProfiles!![diaconnG8Pump.activeProfile][23] = diaconnG8Pump.baseAmount24 + + //incarnation no 처리 + diaconnG8Pump.isPumpVersionGe2_63 = PumplogUtil.isPumpVersionGe(sp.getString(resourceHelper.gs(R.string.pumpversion), ""),2, 63) + + aapsLogger.debug(LTag.PUMPCOMM, "result > " + diaconnG8Pump.result) + aapsLogger.debug(LTag.PUMPCOMM, "systemRemainInsulin > " + diaconnG8Pump.systemRemainInsulin) + aapsLogger.debug(LTag.PUMPCOMM, "systemRemainBattery > " + diaconnG8Pump.systemRemainBattery) + aapsLogger.debug(LTag.PUMPCOMM, "systemBasePattern > " + diaconnG8Pump.systemBasePattern) + aapsLogger.debug(LTag.PUMPCOMM, "systemTbStatus > " + diaconnG8Pump.systemTbStatus) + aapsLogger.debug(LTag.PUMPCOMM, "systemInjectionMealStatus > " + diaconnG8Pump.systemInjectionMealStatus) + aapsLogger.debug(LTag.PUMPCOMM, "systemInjectionSnackStatus > " + diaconnG8Pump.systemInjectionSnackStatus) + aapsLogger.debug(LTag.PUMPCOMM, "systemInjectionSquareStatue > " + diaconnG8Pump.systemInjectionSquareStatue) + aapsLogger.debug(LTag.PUMPCOMM, "systemInjectionDualStatus > " + diaconnG8Pump.systemInjectionDualStatus) + aapsLogger.debug(LTag.PUMPCOMM, "basePauseStatus > " + diaconnG8Pump.basePauseStatus) + aapsLogger.debug(LTag.PUMPCOMM, "year > " + diaconnG8Pump.year) + aapsLogger.debug(LTag.PUMPCOMM, "month > " + diaconnG8Pump.month) + aapsLogger.debug(LTag.PUMPCOMM, "day > " + diaconnG8Pump.day) + aapsLogger.debug(LTag.PUMPCOMM, "hour > " + diaconnG8Pump.hour) + aapsLogger.debug(LTag.PUMPCOMM, "minute > " + diaconnG8Pump.minute) + aapsLogger.debug(LTag.PUMPCOMM, "second > " + diaconnG8Pump.second) + aapsLogger.debug(LTag.PUMPCOMM, "country > " + diaconnG8Pump.country) + aapsLogger.debug(LTag.PUMPCOMM, "productType > " + diaconnG8Pump.productType) + aapsLogger.debug(LTag.PUMPCOMM, "makeYear > " + diaconnG8Pump.makeYear) + aapsLogger.debug(LTag.PUMPCOMM, "makeMonth > " + diaconnG8Pump.makeMonth) + aapsLogger.debug(LTag.PUMPCOMM, "makeDay > " + diaconnG8Pump.makeDay) + aapsLogger.debug(LTag.PUMPCOMM, "lotNo > " + diaconnG8Pump.lotNo) + aapsLogger.debug(LTag.PUMPCOMM, "serialNo > " + diaconnG8Pump.serialNo) + aapsLogger.debug(LTag.PUMPCOMM, "majorVersion > " + diaconnG8Pump.majorVersion) + aapsLogger.debug(LTag.PUMPCOMM, "minorVersion > " + diaconnG8Pump.minorVersion) + aapsLogger.debug(LTag.PUMPCOMM, "lastNum > " + diaconnG8Pump.pumpLastLogNum) + aapsLogger.debug(LTag.PUMPCOMM, "wrappingCount > " + diaconnG8Pump.pumpWrappingCount) + aapsLogger.debug(LTag.PUMPCOMM, "speed > " + diaconnG8Pump.speed) + aapsLogger.debug(LTag.PUMPCOMM, "tbStatus > " + diaconnG8Pump.tbStatus) + aapsLogger.debug(LTag.PUMPCOMM, "tbTime> " + diaconnG8Pump.tbTime) + aapsLogger.debug(LTag.PUMPCOMM, "tbInjectRateRatio > " + diaconnG8Pump.tbInjectRateRatio) + aapsLogger.debug(LTag.PUMPCOMM, "tbElapsedTime > " + diaconnG8Pump.tbElapsedTime) + aapsLogger.debug(LTag.PUMPCOMM, "baseStatus > " + diaconnG8Pump.baseStatus) + aapsLogger.debug(LTag.PUMPCOMM, "baseHour > " + diaconnG8Pump.baseHour) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount > " + diaconnG8Pump.baseAmount) + aapsLogger.debug(LTag.PUMPCOMM, "baseInjAmount > " + diaconnG8Pump.baseInjAmount) + aapsLogger.debug(LTag.PUMPCOMM, "mealKind > " + diaconnG8Pump.mealKind) + aapsLogger.debug(LTag.PUMPCOMM, "mealStartTime > " + diaconnG8Pump.mealStartTime) + aapsLogger.debug(LTag.PUMPCOMM, "mealStatus > " + diaconnG8Pump.mealStatus) + aapsLogger.debug(LTag.PUMPCOMM, "mealAmount > " + diaconnG8Pump.mealAmount) + aapsLogger.debug(LTag.PUMPCOMM, "mealInjAmount > " + diaconnG8Pump.mealInjAmount) + aapsLogger.debug(LTag.PUMPCOMM, "mealSpeed > " + diaconnG8Pump.mealSpeed) + aapsLogger.debug(LTag.PUMPCOMM, "snackStatus > " + diaconnG8Pump.snackStatus) + aapsLogger.debug(LTag.PUMPCOMM, "snackAmount > " + diaconnG8Pump.snackAmount) + aapsLogger.debug(LTag.PUMPCOMM, "snackInjAmount > " + diaconnG8Pump.snackInjAmount) + aapsLogger.debug(LTag.PUMPCOMM, "snackSpeed > " + diaconnG8Pump.snackSpeed) + aapsLogger.debug(LTag.PUMPCOMM, "squareStatus > " + diaconnG8Pump.squareStatus) + aapsLogger.debug(LTag.PUMPCOMM, "squareTime > " + diaconnG8Pump.squareTime) + aapsLogger.debug(LTag.PUMPCOMM, "squareInjTime > " + diaconnG8Pump.squareInjTime) + aapsLogger.debug(LTag.PUMPCOMM, "squareAmount > " + diaconnG8Pump.squareAmount) + aapsLogger.debug(LTag.PUMPCOMM, "squareInjAmount > " + diaconnG8Pump.squareInjAmount) + aapsLogger.debug(LTag.PUMPCOMM, "dualStatus > " + diaconnG8Pump.dualStatus) + aapsLogger.debug(LTag.PUMPCOMM, "dualAmount > " + diaconnG8Pump.dualAmount) + aapsLogger.debug(LTag.PUMPCOMM, "dualInjAmount > " + diaconnG8Pump.dualInjAmount) + aapsLogger.debug(LTag.PUMPCOMM, "dualSquareTime > " + diaconnG8Pump.dualSquareTime) + aapsLogger.debug(LTag.PUMPCOMM, "dualInjSquareTime > " + diaconnG8Pump.dualInjSquareTime) + aapsLogger.debug(LTag.PUMPCOMM, "dualSquareAmount > " + diaconnG8Pump.dualSquareAmount) + aapsLogger.debug(LTag.PUMPCOMM, "dualInjSquareAmount> " + diaconnG8Pump.dualInjSquareAmount) + aapsLogger.debug(LTag.PUMPCOMM, "recentKind1 > " + diaconnG8Pump.recentKind1) + aapsLogger.debug(LTag.PUMPCOMM, "recentTime1 > " + diaconnG8Pump.recentTime1) + aapsLogger.debug(LTag.PUMPCOMM, "recentAmount1 > " + diaconnG8Pump.recentAmount1) + aapsLogger.debug(LTag.PUMPCOMM, "recentKind2 > " + diaconnG8Pump.recentKind2) + aapsLogger.debug(LTag.PUMPCOMM, "recentTime2 > " + diaconnG8Pump.recentTime2) + aapsLogger.debug(LTag.PUMPCOMM, "recentAmount2 > " + diaconnG8Pump.recentAmount2) + aapsLogger.debug(LTag.PUMPCOMM, "todayBaseAmount > " + diaconnG8Pump.todayBaseAmount) + aapsLogger.debug(LTag.PUMPCOMM, "todayMealAmount > " + diaconnG8Pump.todayMealAmount) + aapsLogger.debug(LTag.PUMPCOMM, "todaySnackAmount > " + diaconnG8Pump.todaySnackAmount) + aapsLogger.debug(LTag.PUMPCOMM, "morningHour > " + diaconnG8Pump.morningHour) + aapsLogger.debug(LTag.PUMPCOMM, "morningAmount > " + diaconnG8Pump.morningAmount) + aapsLogger.debug(LTag.PUMPCOMM, "lunchHour > " + diaconnG8Pump.lunchHour) + aapsLogger.debug(LTag.PUMPCOMM, "lunchAmount > " + diaconnG8Pump.lunchAmount) + aapsLogger.debug(LTag.PUMPCOMM, "dinnerHour > " + diaconnG8Pump.dinnerHour) + aapsLogger.debug(LTag.PUMPCOMM, "dinnerAmount > " + diaconnG8Pump.dinnerAmount) + aapsLogger.debug(LTag.PUMPCOMM, "currentBasePattern > " + diaconnG8Pump.currentBasePattern) + aapsLogger.debug(LTag.PUMPCOMM, "currentBaseHour > " + diaconnG8Pump.currentBaseHour) + aapsLogger.debug(LTag.PUMPCOMM, "currentBaseTbBeforeAmount > " + diaconnG8Pump.currentBaseTbBeforeAmount) + aapsLogger.debug(LTag.PUMPCOMM, "currentBaseTbAfterAmount > " + diaconnG8Pump.currentBaseTbAfterAmount) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount1 > " + diaconnG8Pump.baseAmount1) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount2 > " + diaconnG8Pump.baseAmount2) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount3 > " + diaconnG8Pump.baseAmount3) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount4 > " + diaconnG8Pump.baseAmount4) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount5 > " + diaconnG8Pump.baseAmount5) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount6 > " + diaconnG8Pump.baseAmount6) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount7 > " + diaconnG8Pump.baseAmount7) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount8 > " + diaconnG8Pump.baseAmount8) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount9 > " + diaconnG8Pump.baseAmount9) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount10 > " + diaconnG8Pump.baseAmount10) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount11 > " + diaconnG8Pump.baseAmount11) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount12 > " + diaconnG8Pump.baseAmount12) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount13 > " + diaconnG8Pump.baseAmount13) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount14 > " + diaconnG8Pump.baseAmount14) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount15 > " + diaconnG8Pump.baseAmount15) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount16 > " + diaconnG8Pump.baseAmount16) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount17 > " + diaconnG8Pump.baseAmount17) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount18 > " + diaconnG8Pump.baseAmount18) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount19 > " + diaconnG8Pump.baseAmount19) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount20 > " + diaconnG8Pump.baseAmount20) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount21 > " + diaconnG8Pump.baseAmount21) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount22 > " + diaconnG8Pump.baseAmount22) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount23 > " + diaconnG8Pump.baseAmount23) + aapsLogger.debug(LTag.PUMPCOMM, "baseAmount24 > " + diaconnG8Pump.baseAmount24) + } + + override fun getFriendlyName(): String { + return "PUMP_BIG_MAIN_INFO_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquirePacket.kt new file mode 100644 index 0000000000..085bc5c294 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquirePacket.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BolusSpeedInquirePacket + */ +class BolusSpeedInquirePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x45.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedInquirePacket init ") + } + + override fun encode(msgSeq:Int): ByteArray { + return suffixEncode(prefixEncode(msgType, msgSeq, MSG_CON_END)) + } + + override fun getFriendlyName(): String { + return "PUMP_BOLUS_SPEED_INQUIRE" + + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquireResponsePacket.kt new file mode 100644 index 0000000000..ccf9be256a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedInquireResponsePacket.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Inject + +/** + * BolusSpeedInquireResponsePacket + */ +class BolusSpeedInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var sp: SP + + init { + msgType = 0x85.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectResult = defect(data) + if (defectResult != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result = getByteToInt(bufferData) + + if(!isSuccInquireResponseResult(result)) { + failed = true + return + } + + diaconnG8Pump.speed = getByteToInt(bufferData) //주입속도 + sp.putString("g8_bolusspeed", diaconnG8Pump.speed.toString()) + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") + aapsLogger.debug(LTag.PUMPCOMM, "bolusSpeed > " + diaconnG8Pump.speed) + } + + override fun getFriendlyName(): String { + return "PUMP_BOLUS_SPEED_INQUIRE_RESPONSE" + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingPacket.kt new file mode 100644 index 0000000000..ff4005a937 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingPacket.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BolusSpeedSettingPacket + */ +class BolusSpeedSettingPacket( + injector: HasAndroidInjector, + private var type: Int +) : DiaconnG8Packet(injector) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x05 + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingPacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.put(type.toByte()) // 명령코드 + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_BOLUS_SPEED_SETTING_PACKET" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingReportPacket.kt new file mode 100644 index 0000000000..6008c76d12 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingReportPacket.kt @@ -0,0 +1,40 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Inject + +/** + * BolusSpeedSettingReportPacket + */ +class BolusSpeedSettingReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var sp: SP + init { + msgType = 0xC5.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingReportPacket Report Packet Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.speed = getByteToInt(bufferData) // speed result + sp.putBoolean("diaconn_g8_isbolusspeedsync", true) + aapsLogger.debug(LTag.PUMPCOMM, "bolusSpeed --> ${diaconnG8Pump.speed }") + } + + override fun getFriendlyName(): String { + return "PUMP_BOLUS_SPEED_SETTING_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingResponsePacket.kt new file mode 100644 index 0000000000..efc55b2a49 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BolusSpeedSettingResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * BolusSpeedSettingResponsePacket + */ +class BolusSpeedSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x85.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "BolusSpeedSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_BOLUS_SPEED_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/ConfirmReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/ConfirmReportPacket.kt new file mode 100644 index 0000000000..cb516e30fa --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/ConfirmReportPacket.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * ConfirmReportPacket + */ +class ConfirmReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var reqMsgType:Int? = null + init { + msgType = 0xE8.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "ConfirmReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "ConfirmReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + reqMsgType = getByteToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Pump Report Confirm reqMsgType --> ${reqMsgType}") + } + + override fun getFriendlyName(): String { + return "PUMP_CONFIRM_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8Packet.java b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8Packet.java new file mode 100644 index 0000000000..54bb487fd3 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8Packet.java @@ -0,0 +1,300 @@ +package info.nightscout.androidaps.diaconn.packet; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.utils.DateUtil; + +public class DiaconnG8Packet { + + @Inject AAPSLogger aapsLogger; + @Inject DateUtil dateUtil; + + protected HasAndroidInjector injector; + private boolean received; + public boolean failed; + public byte msgType; + + public static final int MSG_LEN = 20; // 메시지 길이(20바이트 패킷) + public static final int MSG_LEN_BIG = 182; // 메시지 길이(182바이트 대량패킷) + public static final byte SOP = (byte) 0xef; // 패킷 시작 바이트(20바이트 패킷) + public static final byte SOP_BIG = (byte) 0xed; // 대량 패킷 시작 바이트(182바이트 대량패킷) + public static final byte MSG_TYPE_LOC = 1; // 메시지 종류 위치 + public static final byte MSG_SEQ_LOC = 2; // 메시지 시퀀스번호 위치 + public static final byte BT_MSG_DATA_LOC = 4; // 데이터 위치 + public static final byte MSG_PAD = (byte) 0xff; // 메시지 뒷부분 빈공간을 채우는 값 + public static final byte MSG_CON_END = (byte) 0x00; // 패킷 내용 끝 + public static final byte MSG_CON_CONTINUE = (byte) 0x01; // 패킷 내용 계속 + + /** + * CRC 정보 + */ + private static final byte[] crc_table = { + (byte) 0x00, (byte) 0x25, (byte) 0x4A, (byte) 0x6F, (byte) 0x94, (byte) 0xB1, (byte) 0xDE, (byte) 0xFB, + (byte) 0x0D, (byte) 0x28, (byte) 0x47, (byte) 0x62, (byte) 0x99, (byte) 0xBC, (byte) 0xD3, (byte) 0xF6, + (byte) 0x1A, (byte) 0x3F, (byte) 0x50, (byte) 0x75, (byte) 0x8E, (byte) 0xAB, (byte) 0xC4, (byte) 0xE1, + (byte) 0x17, (byte) 0x32, (byte) 0x5D, (byte) 0x78, (byte) 0x83, (byte) 0xA6, (byte) 0xC9, (byte) 0xEC, + (byte) 0x34, (byte) 0x11, (byte) 0x7E, (byte) 0x5B, (byte) 0xA0, (byte) 0x85, (byte) 0xEA, (byte) 0xCF, + (byte) 0x39, (byte) 0x1C, (byte) 0x73, (byte) 0x56, (byte) 0xAD, (byte) 0x88, (byte) 0xE7, (byte) 0xC2, + (byte) 0x2E, (byte) 0x0B, (byte) 0x64, (byte) 0x41, (byte) 0xBA, (byte) 0x9F, (byte) 0xF0, (byte) 0xD5, + (byte) 0x23, (byte) 0x06, (byte) 0x69, (byte) 0x4C, (byte) 0xB7, (byte) 0x92, (byte) 0xFD, (byte) 0xD8, + (byte) 0x68, (byte) 0x4D, (byte) 0x22, (byte) 0x07, (byte) 0xFC, (byte) 0xD9, (byte) 0xB6, (byte) 0x93, + (byte) 0x65, (byte) 0x40, (byte) 0x2F, (byte) 0x0A, (byte) 0xF1, (byte) 0xD4, (byte) 0xBB, (byte) 0x9E, + (byte) 0x72, (byte) 0x57, (byte) 0x38, (byte) 0x1D, (byte) 0xE6, (byte) 0xC3, (byte) 0xAC, (byte) 0x89, + (byte) 0x7F, (byte) 0x5A, (byte) 0x35, (byte) 0x10, (byte) 0xEB, (byte) 0xCE, (byte) 0xA1, (byte) 0x84, + (byte) 0x5C, (byte) 0x79, (byte) 0x16, (byte) 0x33, (byte) 0xC8, (byte) 0xED, (byte) 0x82, (byte) 0xA7, + (byte) 0x51, (byte) 0x74, (byte) 0x1B, (byte) 0x3E, (byte) 0xC5, (byte) 0xE0, (byte) 0x8F, (byte) 0xAA, + (byte) 0x46, (byte) 0x63, (byte) 0x0C, (byte) 0x29, (byte) 0xD2, (byte) 0xF7, (byte) 0x98, (byte) 0xBD, + (byte) 0x4B, (byte) 0x6E, (byte) 0x01, (byte) 0x24, (byte) 0xDF, (byte) 0xFA, (byte) 0x95, (byte) 0xB0, + (byte) 0xD0, (byte) 0xF5, (byte) 0x9A, (byte) 0xBF, (byte) 0x44, (byte) 0x61, (byte) 0x0E, (byte) 0x2B, + (byte) 0xDD, (byte) 0xF8, (byte) 0x97, (byte) 0xB2, (byte) 0x49, (byte) 0x6C, (byte) 0x03, (byte) 0x26, + (byte) 0xCA, (byte) 0xEF, (byte) 0x80, (byte) 0xA5, (byte) 0x5E, (byte) 0x7B, (byte) 0x14, (byte) 0x31, + (byte) 0xC7, (byte) 0xE2, (byte) 0x8D, (byte) 0xA8, (byte) 0x53, (byte) 0x76, (byte) 0x19, (byte) 0x3C, + (byte) 0xE4, (byte) 0xC1, (byte) 0xAE, (byte) 0x8B, (byte) 0x70, (byte) 0x55, (byte) 0x3A, (byte) 0x1F, + (byte) 0xE9, (byte) 0xCC, (byte) 0xA3, (byte) 0x86, (byte) 0x7D, (byte) 0x58, (byte) 0x37, (byte) 0x12, + (byte) 0xFE, (byte) 0xDB, (byte) 0xB4, (byte) 0x91, (byte) 0x6A, (byte) 0x4F, (byte) 0x20, (byte) 0x05, + (byte) 0xF3, (byte) 0xD6, (byte) 0xB9, (byte) 0x9C, (byte) 0x67, (byte) 0x42, (byte) 0x2D, (byte) 0x08, + (byte) 0xB8, (byte) 0x9D, (byte) 0xF2, (byte) 0xD7, (byte) 0x2C, (byte) 0x09, (byte) 0x66, (byte) 0x43, + (byte) 0xB5, (byte) 0x90, (byte) 0xFF, (byte) 0xDA, (byte) 0x21, (byte) 0x04, (byte) 0x6B, (byte) 0x4E, + (byte) 0xA2, (byte) 0x87, (byte) 0xE8, (byte) 0xCD, (byte) 0x36, (byte) 0x13, (byte) 0x7C, (byte) 0x59, + (byte) 0xAF, (byte) 0x8A, (byte) 0xE5, (byte) 0xC0, (byte) 0x3B, (byte) 0x1E, (byte) 0x71, (byte) 0x54, + (byte) 0x8C, (byte) 0xA9, (byte) 0xC6, (byte) 0xE3, (byte) 0x18, (byte) 0x3D, (byte) 0x52, (byte) 0x77, + (byte) 0x81, (byte) 0xA4, (byte) 0xCB, (byte) 0xEE, (byte) 0x15, (byte) 0x30, (byte) 0x5F, (byte) 0x7A, + (byte) 0x96, (byte) 0xB3, (byte) 0xDC, (byte) 0xF9, (byte) 0x02, (byte) 0x27, (byte) 0x48, (byte) 0x6D, + (byte) 0x9B, (byte) 0xBE, (byte) 0xD1, (byte) 0xF4, (byte) 0x0F, (byte) 0x2A, (byte) 0x45, (byte) 0x60 + }; + + public DiaconnG8Packet(HasAndroidInjector injector) { + this.received = false; + this.failed = false; + this.injector = injector; + injector.androidInjector().inject(this); + } + + public boolean success() { + return !failed; + } + public void setReceived() { + received = true; + } + + public boolean isReceived() { + return received; + } + + // 패킷 인코딩 앞부분 + public ByteBuffer prefixEncode(byte msgType, int msgSeq, byte msgConEnd) { + ByteBuffer buffer = ByteBuffer.allocate(MSG_LEN); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.put(SOP); + buffer.put(msgType); + buffer.put((byte) msgSeq); + buffer.put(msgConEnd); + return buffer; + } + + // 패킷 인코딩 뒷부분 + public byte[] suffixEncode(ByteBuffer buffer) { + int remainSize = MSG_LEN - buffer.position() - 1; + for (int i = 0; i < remainSize; i++) { + buffer.put(MSG_PAD); + } + byte crc = getCRC(buffer.array(), MSG_LEN - 1); + buffer.put(crc); + return buffer.array(); + } + + // 패킷 디코딩 앞부분 + protected static ByteBuffer prefixDecode(byte[] bytes) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.position(BT_MSG_DATA_LOC); + return buffer; + } + + public int getType(byte[] bytes) { + return (bytes[MSG_TYPE_LOC] & 0xC0) >> 6; + } //상위 2비트 획득 + + public int getCmd(byte[] bytes) { + return bytes[MSG_TYPE_LOC]; + } + + public int getSeq(byte[] bytes) { + return bytes[MSG_SEQ_LOC]; + } + + public static int getByteToInt(ByteBuffer buffer) { + return buffer.get() & 0xff; + } + + public static int getShortToInt(ByteBuffer buffer) { + return buffer.getShort() & 0xffff; + } + + public static int getIntToInt(ByteBuffer buffer) { + return buffer.getInt(); + } + + public static byte[] getBytes(ByteBuffer buffer, int limit) { + ByteBuffer data = ByteBuffer.allocate(MSG_LEN); + int orgPos = buffer.position(); + int orgLimit = buffer.limit(); + buffer.limit(buffer.position() + limit); + data.put(buffer); + buffer.position(orgPos); + buffer.limit(orgLimit); + return data.array(); + } + + // CRC 체크 + static byte getCRC(byte[] data, int length) { + int i = 0; + byte crc = 0; + while (length-- != 0) { + crc = crc_table[(crc ^ data[i]) & 0xFF]; + i++; + } + return crc; + } + + // 패킷 결함 체크 + public static int defect(byte[] bytes) { + int result = 0; + if (bytes[0] != SOP && bytes[0] != SOP_BIG) { + // Start Code Check + result = 98; + } else if ((bytes[0] == SOP && bytes.length != MSG_LEN) || + (bytes[0] == SOP_BIG && bytes.length != MSG_LEN_BIG)) { + // 패킷 길이 체크 + result = 97; + } else if (bytes[bytes.length - 1] != getCRC(bytes, bytes.length - 1)) { + // CRC 체크 + result = 99; + } + return result; + } + + public byte[] encode(int msgSeq) { return new byte[0]; } + + + public static String toHex(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (final byte b : bytes) + sb.append(String.format("%02x ", b & 0xff)); + return sb.toString(); + } + + public static String toNarrowHex(byte[] packet) { + StringBuilder sb = new StringBuilder(); + for (final byte b : packet) + sb.append(String.format("%02x", b & 0xff)); + return sb.toString(); + } + + public void handleMessage(byte[] data) { } + + public String getFriendlyName() { + return "UNKNOWN_PACKET"; + } + + public Boolean isSuccInquireResponseResult(int result) { + boolean isSuccess = false; + switch (result) { + case 16 : + isSuccess = true; + break; + case 17 : + aapsLogger.error(LTag.PUMPCOMM, "Packet CRC error"); + break; + + case 18 : + aapsLogger.error(LTag.PUMPCOMM, "Parameter error."); + break; + + case 19 : + aapsLogger.error(LTag.PUMPCOMM, "Protocol specification error."); + break; + + default: + aapsLogger.error(LTag.PUMPCOMM, "System error."); + break; + } + return isSuccess; + } + + public Boolean isSuccSettingResponseResult(int result) { + boolean isSuccess = false; + switch (result) { + case 0: + isSuccess = true; + break; + case 1: + aapsLogger.error(LTag.PUMPCOMM, "Packet CRC error"); + break; + + case 2: + aapsLogger.error(LTag.PUMPCOMM, "Parameter error."); + break; + + case 3: + aapsLogger.error(LTag.PUMPCOMM, "Protocol specification error."); + break; + + case 4: + aapsLogger.error(LTag.PUMPCOMM, "Eating timeout, not injectable."); + break; + + case 6: + aapsLogger.error(LTag.PUMPCOMM, "Pump canceled it."); + break; + + case 7: + aapsLogger.error(LTag.PUMPCOMM, "In the midst of other operations, limited app setup capabilities"); + break; + + case 8: + aapsLogger.error(LTag.PUMPCOMM, "During another bolus injection, injection is restricted"); + break; + + case 9: + aapsLogger.error(LTag.PUMPCOMM, "Basal release is required."); + break; + + case 10: + aapsLogger.error(LTag.PUMPCOMM, "Pump canceled due to non-response."); + break; + + case 11: + aapsLogger.error(LTag.PUMPCOMM, "Injection is not possible due to low battery."); + break; + + case 12: + aapsLogger.error(LTag.PUMPCOMM, "Injection is not possible due to low insulin. "); + break; + + case 13: + aapsLogger.error(LTag.PUMPCOMM, "Can't inject due to 1 time limit exceeded."); + break; + + case 14: + aapsLogger.error(LTag.PUMPCOMM, "It cannot be injected due to an excess of injection volume today"); + break; + + case 15: + aapsLogger.error(LTag.PUMPCOMM, "After base setting is completed, base injection can be made."); + break; + + default: + aapsLogger.error(LTag.PUMPCOMM, "It cannot be set to a system error."); + break; + + } + return isSuccess; + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8ResponseMessageHashTable.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8ResponseMessageHashTable.kt new file mode 100644 index 0000000000..84f008d57b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8ResponseMessageHashTable.kt @@ -0,0 +1,52 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import java.util.* +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class DiaconnG8ResponseMessageHashTable @Inject constructor(val injector: HasAndroidInjector) { + var messages: HashMap = HashMap() + + fun put(message: DiaconnG8Packet) { + messages[message.msgType.toInt()] = message + } + + fun findMessage(command: Int): DiaconnG8Packet { + return messages[command] ?: DiaconnG8Packet(injector) + } + + init { + put(BigMainInfoInquireResponsePacket(injector)) + put(BigLogInquireResponsePacket(injector)) + put(InjectionSnackInquireResponsePacket(injector)) + put(SneckLimitInquireResponsePacket(injector)) + put(BasalLimitInquireResponsePacket(injector)) + put(TempBasalInquireResponsePacket(injector)) + put(TimeInquirePacket(injector)) + put(TimeInquireResponsePacket(injector)) + put(TimeReportPacket(injector)) + put(LogStatusInquireResponsePacket(injector)) + put(IncarnationInquireResponsePacket(injector)) + put(BolusSpeedInquireResponsePacket(injector)) + put(SoundInquireResponsePacket(injector)) + put(DisplayTimeInquireResponsePacket(injector)) + put(LanguageInquireResponsePacket(injector)) + + + // Report Packet + put(BasalPauseReportPacket(injector)) + put(BasalSettingReportPacket(injector)) + put(ConfirmReportPacket(injector)) + put(InjectionBasalReportPacket(injector)) + put(RejectReportPacket(injector)) + put(TempBasalReportPacket(injector)) + put(InjectionSnackResultReportPacket(injector)) + put(InjectionExtendedBolusResultReportPacket(injector)) + put(InsulinLackReportPacket(injector)) + put(BatteryWarningReportPacket(injector)) + put(InjectionBlockReportPacket(injector)) + put(BolusSpeedSettingReportPacket(injector)) + } +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8SettingResponseMessageHashTable.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8SettingResponseMessageHashTable.kt new file mode 100644 index 0000000000..cd2d32a293 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8SettingResponseMessageHashTable.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import java.util.* +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class DiaconnG8SettingResponseMessageHashTable @Inject constructor(val injector: HasAndroidInjector) { + var messages: HashMap = HashMap() + + fun put(message: DiaconnG8Packet) { + messages[message.msgType.toInt()] = message + } + + fun findMessage(command: Int): DiaconnG8Packet { + return messages[command] ?: DiaconnG8Packet(injector) + } + + init { + put(AppCancelSettingResponsePacket(injector)) + put(AppConfirmSettingResponsePacket(injector)) + put(BasalPauseSettingResponsePacket(injector)) + put(BasalSettingResponsePacket(injector)) + put(TempBasalSettingResponsePacket(injector)) + put(TimeSettingResponsePacket(injector)) + put(InjectionBasalSettingResponsePacket(injector)) + put(InjectionSnackSettingResponsePacket(injector)) + put(InjectionExtendedBolusSettingResponsePacket(injector)) + put(InjectionCancelSettingResponsePacket(injector)) + put(SoundSettingResponsePacket(injector)) + put(DisplayTimeoutSettingResponsePacket(injector)) + put(LanguageSettingResponsePacket(injector)) + put(BolusSpeedSettingResponsePacket(injector)) + } +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquirePacket.kt new file mode 100644 index 0000000000..9c0692ab45 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquirePacket.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * DisplayTimeInquirePacket + */ +class DisplayTimeInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x4E.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "DisplayTimeInquirePacket request") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_DISPLAY_TIME_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquireResponsePacket.kt new file mode 100644 index 0000000000..5d1b7df047 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeInquireResponsePacket.kt @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * DisplayTimeInquireResponsePacket + */ +class DisplayTimeInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x8E.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "DisplayTimeInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "DisplayTimeInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + + diaconnG8Pump.lcdOnTimeSec = getByteToInt(bufferData) + + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") + aapsLogger.debug(LTag.PUMPCOMM, "lcdOnTimeSec --> ${diaconnG8Pump.lcdOnTimeSec}") + } + + override fun getFriendlyName(): String { + return "PUMP_DISPLAY_TIME_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingPacket.kt new file mode 100644 index 0000000000..bbd462cc0c --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingPacket.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * DisplayTimeoutSettingPacket + */ +class DisplayTimeoutSettingPacket( + injector: HasAndroidInjector, + private var type: Int +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x0E + aapsLogger.debug(LTag.PUMPCOMM, "DisplayTimeoutSettingPacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.put(type.toByte()) // cmd + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_DISPLAY_TIMEOUT_SETTING_PACKET" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingResponsePacket.kt new file mode 100644 index 0000000000..9582da53e5 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DisplayTimeoutSettingResponsePacket.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * DisplayTimeoutSettingResponsePacket + */ +class DisplayTimeoutSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x8E.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "DisplayTimeoutSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "DisplayTimeoutSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_DISPLAY_TIMEOUT_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquirePacket.kt new file mode 100644 index 0000000000..34f99c6ff6 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquirePacket.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + + * IncarnationInquirePacket + */ +class IncarnationInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x7A + aapsLogger.debug(LTag.PUMPCOMM, "IncarnationInquirePacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_INCARNATION_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt new file mode 100644 index 0000000000..55aedbcf05 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt @@ -0,0 +1,50 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Inject + +/** + * IncarnationInquireResponsePacket + */ +open class IncarnationInquireResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var sp: SP + @Inject lateinit var resourceHelper: ResourceHelper + + var result = 0 + init { + msgType = 0xBA.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "IncarnationInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "IncarnationInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result)) { + failed = true + return + } + // 5. 로그상태 조회 + diaconnG8Pump.pumpIncarnationNum = getShortToInt(bufferData) // 펌프 Incarnation 번호 + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "pumpIncarnationNum > " + diaconnG8Pump.pumpIncarnationNum) + } + + override fun getFriendlyName(): String { + return "PUMP_INCARNATION_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalReportPacket.kt new file mode 100644 index 0000000000..503c5bacb1 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalReportPacket.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionBasalReportPacket + */ +class InjectionBasalReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0xCC.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBasalReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBasalReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.systemBasePattern = getByteToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Pump Report BasalPattern --> ${diaconnG8Pump.systemBasePattern} (1:basic, 2: life1 , 3: life2 , 4: life3 , 5:dr1, 6:dr2) ") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_BASAL_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingPacket.kt new file mode 100644 index 0000000000..4e9cbf546b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingPacket.kt @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionBasalSettingPacket + */ +class InjectionBasalSettingPacket( + injector: HasAndroidInjector, + private val pattern:Int +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x0C.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBasalSettingPacket init ") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + buffer.put(pattern.toByte()) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_BASAL_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingResponsePacket.kt new file mode 100644 index 0000000000..c9912472ce --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBasalSettingResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionBasalSettingResponsePacket + */ +class InjectionBasalSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x8C.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBasalSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBasalSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_BASAL_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBlockReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBlockReportPacket.kt new file mode 100644 index 0000000000..0ff1cd6181 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionBlockReportPacket.kt @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionBlockReportPacket + */ +class InjectionBlockReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0xD8.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBlockReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionBasalReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.injectionBlockGrade = getByteToInt(bufferData) + diaconnG8Pump.injectionBlockProcess = getByteToInt(bufferData) + diaconnG8Pump.injectionBlockRemainAmount = getShortToInt(bufferData) / 100.0 + diaconnG8Pump.injectionBlockType = getByteToInt(bufferData) + + aapsLogger.debug(LTag.PUMPCOMM, "injectionBlockGrade --> ${diaconnG8Pump.injectionBlockGrade} (1:info, 2: warning , 3: major , 4: critical)") + aapsLogger.debug(LTag.PUMPCOMM, "injectionBlockProcess --> ${diaconnG8Pump.injectionBlockProcess} (1:skip, 2: stop , 3: ignore ) ") + aapsLogger.debug(LTag.PUMPCOMM, "injectionBlockReaminAmount --> ${diaconnG8Pump.injectionBlockRemainAmount} ") + aapsLogger.debug(LTag.PUMPCOMM, "injectionBlockType --> ${diaconnG8Pump.injectionBlockType} (1:basal, 2: meal , 3: normal , 4: square , 5:dual, 6:tube, 7:needle) ") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_BLOCK_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingPacket.kt new file mode 100644 index 0000000000..bfab75fe6a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingPacket.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionCancelSettingPacket + */ +class InjectionCancelSettingPacket( + injector: HasAndroidInjector, + private var reqMsgType: Byte, // 명령코드 +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x2B + aapsLogger.debug(LTag.PUMPCOMM, "InjectionCancelSettingPacket INIT") + } + + override fun encode(msgSeq:Int): ByteArray { + var buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.put(reqMsgType) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_CANCEL_SETTING_REQUEST" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingResponsePacket.kt new file mode 100644 index 0000000000..9099e5ba0c --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionCancelSettingResponsePacket.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionCancelSettingResponsePacket + */ +class InjectionCancelSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0xAB.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionCancelSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionCancelSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_CANCEL_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt new file mode 100644 index 0000000000..8f196a4713 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt @@ -0,0 +1,59 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +/** + * InjectionExtendedBolusResultReportPacket + */ +class InjectionExtendedBolusResultReportPacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var resourceHelper: ResourceHelper + + init { + msgType = 0xe5.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionExtendedBolusResultReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionExtendedBolusResultReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + + val result = getByteToInt(bufferData) // 0: success , 1: user stop, 2:fail + val settingMinutes = getShortToInt(bufferData) + val elapsedTime = getShortToInt(bufferData) + val bolusAmountToBeDelivered = getShortToInt(bufferData) / 100.0 + val deliveredBolusAmount = getShortToInt(bufferData) / 100.0 + + diaconnG8Pump.isExtendedInProgress = result == 0 + diaconnG8Pump.extendedBolusMinutes = settingMinutes + diaconnG8Pump.extendedBolusAbsoluteRate = bolusAmountToBeDelivered + diaconnG8Pump.extendedBolusPassedMinutes = elapsedTime + diaconnG8Pump.extendedBolusRemainingMinutes = settingMinutes - elapsedTime + diaconnG8Pump.extendedBolusDeliveredSoFar = deliveredBolusAmount + + aapsLogger.debug(LTag.PUMPCOMM, "Result: $result") + aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + diaconnG8Pump.isExtendedInProgress) + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + diaconnG8Pump.extendedBolusAbsoluteRate + " U/h") + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus duration: " + diaconnG8Pump.extendedBolusMinutes + " min") + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far: " + diaconnG8Pump.extendedBolusSoFarInMinutes + " min") + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus remaining minutes: " + diaconnG8Pump.extendedBolusRemainingMinutes + " min") + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus delivered so far: " + diaconnG8Pump.extendedBolusDeliveredSoFar + " U") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_EXTENDED_BOLUS_RESULT_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingPacket.kt new file mode 100644 index 0000000000..e9f119862a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingPacket.kt @@ -0,0 +1,35 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionExtendedBolusSettingPacket + */ +class InjectionExtendedBolusSettingPacket( + injector: HasAndroidInjector, + private val amount: Int, + private val minutes: Int, + private val bcDttm:Long +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x08.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionExtendedBolusSettingPacket init ") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.putShort(minutes.toShort()) + buffer.putShort(amount.toShort()) + buffer.putInt(bcDttm.toInt()) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_EXTENDED_BOLUS_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingResponsePacket.kt new file mode 100644 index 0000000000..a17ecd3bfb --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusSettingResponsePacket.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionExtendedBolusSettingResponsePacket + */ +class InjectionExtendedBolusSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x88.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionExtendedBolusSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionExtendedBolusSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_EXTENDED_BOLUS_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingPacket.kt new file mode 100644 index 0000000000..ed901b9187 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingPacket.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionMealSettingPacket + */ +class InjectionMealSettingPacket( + injector: HasAndroidInjector, + private val amount:Int, + private val bcDttm:Long +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x06.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionMealSettingPacket init ") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + buffer.putShort(amount.toShort()) + buffer.putLong(bcDttm) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_MEAL_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingResponsePacket.kt new file mode 100644 index 0000000000..7e30ef8c3c --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionMealSettingResponsePacket.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionMealSettingResponsePacket + */ +class InjectionMealSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x86.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionMealSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionMealSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_MEAL_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquirePacket.kt new file mode 100644 index 0000000000..a9e82f1953 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquirePacket.kt @@ -0,0 +1,26 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionSneckInquirePacket + */ +class InjectionSnackInquirePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x47.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackInquirePacket init ") + } + + override fun encode(msgSeq:Int): ByteArray { + return suffixEncode(prefixEncode(msgType, msgSeq, MSG_CON_END)) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_SNACK_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquireResponsePacket.kt new file mode 100644 index 0000000000..4ff2b27c9e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackInquireResponsePacket.kt @@ -0,0 +1,51 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionSnackInquireResponsePacket + */ +class InjectionSnackInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x87.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + + diaconnG8Pump.snackStatus = getByteToInt(bufferData) //주입상태 + diaconnG8Pump.snackAmount = getShortToInt(bufferData) / 100.0 // 주입설정량 + diaconnG8Pump.snackInjAmount = getShortToInt(bufferData) / 100.0 // 현재주입량 + diaconnG8Pump.snackSpeed = getByteToInt(bufferData) //주입속도 + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result2") + aapsLogger.debug(LTag.PUMPCOMM, "snackStatus > " + diaconnG8Pump.snackStatus) + aapsLogger.debug(LTag.PUMPCOMM, "snackAmount > " + diaconnG8Pump.snackAmount) + aapsLogger.debug(LTag.PUMPCOMM, "snackInjAmount > " + diaconnG8Pump.snackInjAmount) + aapsLogger.debug(LTag.PUMPCOMM, "snackSpeed > " + diaconnG8Pump.snackSpeed) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_SNACK_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt new file mode 100644 index 0000000000..a85c35002b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject + +/** + * InjectionSnackResultReportPacket + */ +class InjectionSnackResultReportPacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var resourceHelper: ResourceHelper + + init { + msgType = 0xe4.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackResultReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackResultReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result = getByteToInt(bufferData) + val bolusAmountToBeDelivered = getShortToInt(bufferData)/100.0 + val deliveredBolusAmount = getShortToInt(bufferData)/100.0 + + diaconnG8Pump.bolusAmountToBeDelivered = bolusAmountToBeDelivered + diaconnG8Pump.lastBolusAmount = deliveredBolusAmount + diaconnG8Pump.lastBolusTime = dateUtil.now() + diaconnG8Pump.bolusingTreatment?.insulin = deliveredBolusAmount + + if(result == 1) { + diaconnG8Pump.bolusStopped = true // 주입 중 취소 처리! + } + diaconnG8Pump.bolusDone = true // 주입완료 처리! + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "bolusAmountToBeDelivered --> ${diaconnG8Pump.bolusAmountToBeDelivered}") + aapsLogger.debug(LTag.PUMPCOMM, "lastBolusAmount --> ${diaconnG8Pump.lastBolusAmount}") + aapsLogger.debug(LTag.PUMPCOMM, "lastBolusTime --> ${diaconnG8Pump.lastBolusTime}") + aapsLogger.debug(LTag.PUMPCOMM, "diaconnG8Pump.bolusingTreatment?.insulin --> ${diaconnG8Pump.bolusingTreatment?.insulin}") + aapsLogger.debug(LTag.PUMPCOMM, "bolusDone --> ${diaconnG8Pump.bolusDone}") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_SNACK_REPORT" + + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingPacket.kt new file mode 100644 index 0000000000..5312aa348e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingPacket.kt @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionSnackSettingPacket + */ +class InjectionSnackSettingPacket( + injector: HasAndroidInjector, + private val amount:Int +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x07.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingPacket init ") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + buffer.putShort(amount.toShort()) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_SNACK_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingResponsePacket.kt new file mode 100644 index 0000000000..dec3271e47 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackSettingResponsePacket.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InjectionSnackSettingResponsePacket + */ +class InjectionSnackSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x87.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InjectionSnackSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_SNACK_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InsulinLackReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InsulinLackReportPacket.kt new file mode 100644 index 0000000000..8fd6da5981 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InsulinLackReportPacket.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * InsulinLackReportPacket + */ +class InsulinLackReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0xD8.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "InsulinLackReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "InsulinLackReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.insulinWarningGrade = getByteToInt(bufferData) + diaconnG8Pump.insulinWarningProcess = getByteToInt(bufferData) + diaconnG8Pump.insulinWarningRemain = getByteToInt(bufferData) + + aapsLogger.debug(LTag.PUMPCOMM, "insulinWarningGrade --> ${diaconnG8Pump.insulinWarningGrade} (1:info, 2: warning , 3: major , 4: critical)") + aapsLogger.debug(LTag.PUMPCOMM, "insulinWarningProcess --> ${diaconnG8Pump.insulinWarningProcess} (1:skip, 2: stop , 3: ignore ) ") + aapsLogger.debug(LTag.PUMPCOMM, "insulinWarningRemain --> ${diaconnG8Pump.insulinWarningRemain} (0~100%) ") + + } + + override fun getFriendlyName(): String { + return "PUMP_INJECTION_LACK_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquirePacket.kt new file mode 100644 index 0000000000..7bca3e499b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquirePacket.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * LanguageInquirePacket + */ +class LanguageInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x60.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquirePacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_LANGUAGE_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquireResponsePacket.kt new file mode 100644 index 0000000000..6c493ca145 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageInquireResponsePacket.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * LanguageInquireResponsePacket + */ +class LanguageInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0xA0.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "LanguageInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + diaconnG8Pump.selectedLanguage = getByteToInt(bufferData) + + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") + aapsLogger.debug(LTag.PUMPCOMM, "selectedLanguage --> ${diaconnG8Pump.selectedLanguage}") + } + + override fun getFriendlyName(): String { + return "PUMP_LANGUAGE_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingPacket.kt new file mode 100644 index 0000000000..fd0f35f1cc --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingPacket.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * LanguageSettingPacket + */ +class LanguageSettingPacket( + injector: HasAndroidInjector, + private var type: Int +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x20 + aapsLogger.debug(LTag.PUMPCOMM, "LanguageSettingPacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.put(type.toByte()) // 명령코드 + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_LANGUAGE_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingResponsePacket.kt new file mode 100644 index 0000000000..91a29ddae7 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LanguageSettingResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * LanguageSettingResponsePacket + */ +class LanguageSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0xA0.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "LanguageSettingResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "LanguageSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_LANGUAGE_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquirePacket.kt new file mode 100644 index 0000000000..21e0431d66 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquirePacket.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * LogStatusInquirePacket + */ +class LogStatusInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + init { + msgType = 0x56 + aapsLogger.debug(LTag.PUMPCOMM, "LogStatusInquirePacket INIT") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_OG_STATUS_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquireResponsePacket.kt new file mode 100644 index 0000000000..441afe753e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/LogStatusInquireResponsePacket.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * LogStatusInquireResponsePacket + */ +open class LogStatusInquireResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + var result = 0 + init { + msgType = 0x96.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "LogStatusInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "LogStatusInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result)) { + failed = true + return + } + // 5. 로그상태 조회 + diaconnG8Pump.pumpLastLogNum = getShortToInt(bufferData) // 마지막 저장로그번호 + diaconnG8Pump.pumpWrappingCount = getByteToInt(bufferData) // wrapping 카운트 + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "pumpLastLogNum > " + diaconnG8Pump.pumpLastLogNum) + aapsLogger.debug(LTag.PUMPCOMM, "pumpWrappingCount> " + diaconnG8Pump.pumpWrappingCount) + } + + override fun getFriendlyName(): String { + return "PUMP_LOG_STATUS_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/RejectReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/RejectReportPacket.kt new file mode 100644 index 0000000000..7c8871b0f6 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/RejectReportPacket.kt @@ -0,0 +1,41 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * RejectReportPacket + */ +class RejectReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var reqMsgType:Int? = null + var reason:Int? = null + init { + msgType = 0xE2.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "RejectReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "RejectReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + reqMsgType = getByteToInt(bufferData) + reason = getByteToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "reqMsgType --> $reqMsgType") + aapsLogger.debug(LTag.PUMPCOMM, "Reject Reason --> $reason (6:cancel, 10:timeout) ") + } + + override fun getFriendlyName(): String { + return "PUMP_REJECT_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquirePacket.kt new file mode 100644 index 0000000000..983887eccb --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquirePacket.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * SneckLimitInquirePacket + */ +class SneckLimitInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x50.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "SneckLimitInquirePacket limit request") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_SNECK_LIMIT_REQUEST" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquireResponsePacket.kt new file mode 100644 index 0000000000..4dccca9ab1 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SneckLimitInquireResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * SneckLimitInquireResponsePacket + */ +class SneckLimitInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x90.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "SneckLimitInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "SneckLimitInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + + diaconnG8Pump.maxBolus = getShortToInt(bufferData).toDouble() / 100 + diaconnG8Pump.maxBolusePerDay = getShortToInt(bufferData).toDouble() / 100 + + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") + aapsLogger.debug(LTag.PUMPCOMM, "maxBolusePerDay --> ${diaconnG8Pump.maxBolusePerDay}") + aapsLogger.debug(LTag.PUMPCOMM, "maxBolus --> ${diaconnG8Pump.maxBolus}") + } + + override fun getFriendlyName(): String { + return "PUMP_SNACK_LIMIT_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquirePacket.kt new file mode 100644 index 0000000000..790523aff9 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquirePacket.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * SoundInquirePacket + */ +class SoundInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x4D.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "SoundInquirePacket request") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_SOUND_INQUIRE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquireResponsePacket.kt new file mode 100644 index 0000000000..c42a20e835 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundInquireResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * SoundInquireResponsePacket + */ +class SoundInquireResponsePacket(injector: HasAndroidInjector) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x8D.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "SoundInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "SoundInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result2)) { + failed = true + return + } + + diaconnG8Pump.beepAndAlarm = getByteToInt(bufferData) -1 + diaconnG8Pump.alarmIntesity = getByteToInt(bufferData) -1 + + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> ${diaconnG8Pump.result}") + aapsLogger.debug(LTag.PUMPCOMM, "beepAndAlarm --> ${diaconnG8Pump.beepAndAlarm}") + aapsLogger.debug(LTag.PUMPCOMM, "alarmIntesity --> ${diaconnG8Pump.alarmIntesity}") + } + + override fun getFriendlyName(): String { + return "PUMP_SOUND_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingPacket.kt new file mode 100644 index 0000000000..cadb110435 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingPacket.kt @@ -0,0 +1,34 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * SoundSettingPacket + */ +class SoundSettingPacket( + injector: HasAndroidInjector, + private var type: Int, // + private var intensity: Int // +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x0D + aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingPacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + buffer.put(type.toByte()) // 명령코드 + buffer.put(intensity.toByte()) // 명령코드 + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_SOUND_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingResponsePacket.kt new file mode 100644 index 0000000000..474dc3997c --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/SoundSettingResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * SoundSettingResponsePacket + */ +class SoundSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x8D.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "SoundSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_SOUND_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquirePacket.kt new file mode 100644 index 0000000000..db1da7fc5a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquirePacket.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TempBasalInquirePacket + */ +class TempBasalInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x4A + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalInquirePacket Init") + } + + override fun encode(msgSeq:Int): ByteArray { + return suffixEncode(prefixEncode(msgType, msgSeq, MSG_CON_END)) + } + + override fun getFriendlyName(): String { + return "PUMP_TEMP_BASAL_INQUIRE_REQUEST" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquireResponsePacket.kt new file mode 100644 index 0000000000..5f45ab3abd --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquireResponsePacket.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TempBasalInquireResponsePacket + */ +open class TempBasalInquireResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + var result = 0 + init { + msgType = 0x8A.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result)) { + failed = true + return + } + + diaconnG8Pump.tbStatus = getByteToInt(bufferData) // 임시기저 상태 + diaconnG8Pump.tbTime = getByteToInt(bufferData) // 임시기저시간 + diaconnG8Pump.tbInjectRateRatio = getShortToInt(bufferData) //임시기저 주입량/률 + diaconnG8Pump.tbElapsedTime = getShortToInt(bufferData) // 임시기저 경과시간 + + diaconnG8Pump.isTempBasalInProgress = diaconnG8Pump.tbStatus == 1 + if (diaconnG8Pump.tbInjectRateRatio >= 50000) { + diaconnG8Pump.tempBasalPercent = diaconnG8Pump.tbInjectRateRatio - 50000 + } + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "tbStatus > " + diaconnG8Pump.tbStatus) + aapsLogger.debug(LTag.PUMPCOMM, "tbTime> " + diaconnG8Pump.tbTime) + aapsLogger.debug(LTag.PUMPCOMM, "tbInjectRateRatio > " + diaconnG8Pump.tbInjectRateRatio) + aapsLogger.debug(LTag.PUMPCOMM, "tbElapsedTime > " + diaconnG8Pump.tbElapsedTime) + } + + override fun getFriendlyName(): String { + return "PUMP_TEMP_BASAL_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalReportPacket.kt new file mode 100644 index 0000000000..73fa041172 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalReportPacket.kt @@ -0,0 +1,58 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TempBasalReportPacket + */ +class TempBasalReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0xCA.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalReportPacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.tbStatus = getByteToInt(bufferData) + diaconnG8Pump.isTempBasalInProgress = diaconnG8Pump.tbStatus == 1 + + // 응답받은 임시기저 상태가 주입중이면, pump객체에 정보를 갱신. + if(diaconnG8Pump.isTempBasalInProgress) { + diaconnG8Pump.tbTime = getByteToInt(bufferData) + diaconnG8Pump.tbInjectRateRatio = getShortToInt(bufferData) + if (diaconnG8Pump.tbInjectRateRatio >= 50000) { + diaconnG8Pump.tempBasalPercent = diaconnG8Pump.tbInjectRateRatio - 50000 + } + + if(diaconnG8Pump.tbInjectRateRatio in 1000..1600) { + diaconnG8Pump.tbInjectAbsoluteValue = (diaconnG8Pump.tbInjectRateRatio -1000) / 100.0 + diaconnG8Pump.tempBasalAbsoluteRate = diaconnG8Pump.tbInjectAbsoluteValue + } + } + aapsLogger.debug(LTag.PUMPCOMM, "tbStatus > " + diaconnG8Pump.tbStatus) + aapsLogger.debug(LTag.PUMPCOMM, "tbTime> " + diaconnG8Pump.tbTime) + aapsLogger.debug(LTag.PUMPCOMM, "tbInjectRateRatio > " + diaconnG8Pump.tbInjectRateRatio) + + } + + override fun getFriendlyName(): String { + return "PUMP_TEMP_BASAL_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingPacket.kt new file mode 100644 index 0000000000..b935ce2a94 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingPacket.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TempBasalSettingPacket + */ +class TempBasalSettingPacket( + injector: HasAndroidInjector, + private var status: Int, // (1:tempbasal running, 2:tempbasal dismissed) + private var time: Int, //hour group (1=00~05, 2=06~11, 3=12~17, 4=18~23) + private var injectRateRatio: Int +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x0A + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalSettingPacket Init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END) + val apsSecond = 946652400L //fixed value 2000-01-01 00:00:00 (second) + buffer.put(status.toByte()) // status + buffer.put(time.toByte()) + buffer.putShort(injectRateRatio.toShort()) // 임시기저 주입량/률 1000(0.00U)~1600(6.00U), 50000(0%)~50200(200%), 50000이상이면 주입률로 판정 + buffer.putLong(apsSecond) // TB_DTTM + + aapsLogger.debug(LTag.PUMPCOMM, " status --> ${status.toByte()} (1:tempbasal running, 2:tempbasal dismissed)") + aapsLogger.debug(LTag.PUMPCOMM, " time --> ${time.toByte()} ( value : 2~96 ( 2:30min, 3:45min....96:1440min ) 30min ~ 24 hour, step 15min ) ") + aapsLogger.debug(LTag.PUMPCOMM, "injectRateRatio --> $injectRateRatio , toShort = ${injectRateRatio.toShort()}") + aapsLogger.debug(LTag.PUMPCOMM, " tbDttm --> $apsSecond ") + + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_TEMP_BASAL_SETTING" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingResponsePacket.kt new file mode 100644 index 0000000000..843f245e96 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalSettingResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TempBasalSettingResponsePacket + */ +class TempBasalSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x8A.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalSettingResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "TempBasalSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_TEMP_BASAL_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquirePacket.kt new file mode 100644 index 0000000000..722e2030d2 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquirePacket.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TimeInquirePacket + */ +class TimeInquirePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x4F.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TimeInquirePacket init") + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_TIME_REQUEST" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquireResponsePacket.kt new file mode 100644 index 0000000000..86b1f3befd --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeInquireResponsePacket.kt @@ -0,0 +1,41 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TimeInquireResponsePacket + */ +class TimeInquireResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x50.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TimeInquireResponsePacket init") + } + + override fun handleMessage(data: ByteArray?) { + val result = defect(data) + if (result != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "TimeInquireResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + val result2 = getByteToInt(bufferData) + if(!isSuccInquireResponseResult(result2)) { + failed = true + return; + } + } + + override fun getFriendlyName(): String { + return "PUMP_TIME_INQUIRE_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeReportPacket.kt new file mode 100644 index 0000000000..2a284defe8 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeReportPacket.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TimeReportPacket + */ +class TimeReportPacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result =0 + init { + msgType = 0xCF.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TimeReportPacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "TimeReportPacket Report Packet Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + diaconnG8Pump.year = getByteToInt(bufferData) // yyyy + diaconnG8Pump.month = getByteToInt(bufferData) // month + diaconnG8Pump.day = getByteToInt(bufferData) // day + diaconnG8Pump.hour = getByteToInt(bufferData) // hour + diaconnG8Pump.minute = getByteToInt(bufferData) // min + diaconnG8Pump.second = getByteToInt(bufferData) // second + + aapsLogger.debug(LTag.PUMPCOMM, "year --> ${diaconnG8Pump.year }") + aapsLogger.debug(LTag.PUMPCOMM, "month --> ${diaconnG8Pump.month }") + aapsLogger.debug(LTag.PUMPCOMM, "day --> ${diaconnG8Pump.day }") + aapsLogger.debug(LTag.PUMPCOMM, "hour --> ${diaconnG8Pump.hour }") + aapsLogger.debug(LTag.PUMPCOMM, "minute --> ${diaconnG8Pump.minute}") + aapsLogger.debug(LTag.PUMPCOMM, "second --> ${diaconnG8Pump.second}") + } + + override fun getFriendlyName(): String { + return "PUMP_TIME_REPORT" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingPacket.kt new file mode 100644 index 0000000000..ad158bb211 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingPacket.kt @@ -0,0 +1,43 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import org.joda.time.DateTime +import org.joda.time.DateTimeZone +import javax.inject.Inject + +/** + * TimeSettingPacket Request Packet + */ +class TimeSettingPacket( + injector: HasAndroidInjector, + private var time: Long = 0, + private var offset:Int = 0 +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + + init { + msgType = 0x0F + aapsLogger.debug(LTag.PUMPCOMM, "Time Sync between Phone and Pump") + + } + + override fun encode(msgSeq:Int): ByteArray { + val buffer = prefixEncode(msgType, msgSeq, MSG_CON_END); + val date = DateTime(time).withZone(DateTimeZone.UTC) + buffer.put((date.year - 2000 and 0xff).toByte()) + buffer.put((date.monthOfYear and 0xff).toByte()) + buffer.put((date.dayOfMonth and 0xff).toByte()) + buffer.put((date.hourOfDay + offset and 0xff).toByte()) + buffer.put((date.minuteOfHour and 0xff).toByte()) + buffer.put((date.secondOfMinute and 0xff).toByte()) + + return suffixEncode(buffer) + } + + override fun getFriendlyName(): String { + return "PUMP_TIME_SETTING_REQUEST" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingResponsePacket.kt new file mode 100644 index 0000000000..ef78bf735f --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TimeSettingResponsePacket.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.diaconn.packet + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.logging.LTag +import javax.inject.Inject + +/** + * TimeSettingResponsePacket + */ +class TimeSettingResponsePacket( + injector: HasAndroidInjector +) : DiaconnG8Packet(injector ) { + + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + var result = 0 + init { + msgType = 0x8F.toByte() + aapsLogger.debug(LTag.PUMPCOMM, "TimeSettingResponsePacket init ") + } + + override fun handleMessage(data: ByteArray?) { + val defectCheck = defect(data) + if (defectCheck != 0) { + aapsLogger.debug(LTag.PUMPCOMM, "TimeSettingResponsePacket Got some Error") + failed = true + return + } else failed = false + + val bufferData = prefixDecode(data) + result = getByteToInt(bufferData) + + if(!isSuccSettingResponseResult(result)) { + diaconnG8Pump.bolusStartErrorCode = result + failed = true + return + } + diaconnG8Pump.otpNumber = getIntToInt(bufferData) + + aapsLogger.debug(LTag.PUMPCOMM, "Result --> $result") + aapsLogger.debug(LTag.PUMPCOMM, "otpNumber --> ${diaconnG8Pump.otpNumber}") + } + + override fun getFriendlyName(): String { + return "PUMP_TIME_SETTING_RESPONSE" + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BATTERY.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BATTERY.kt new file mode 100644 index 0000000000..db44c69fb3 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BATTERY.kt @@ -0,0 +1,53 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* Battery Shortage Alarm Log +*/ +class LOG_ALARM_BATTERY private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 1=INFO, 2=WARNING, 3=MAJOR, 4=CRITICAL + private val alarmLevel: Byte, // 1=OCCUR, 2=STOP + private val ack: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_ALARM_BATTERY{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", alarmLevel=").append(alarmLevel.toInt()) + sb.append(", ack=").append(ack.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x28 + fun parse(data: String): LOG_ALARM_BATTERY { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_ALARM_BATTERY( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BLOCK.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BLOCK.kt new file mode 100644 index 0000000000..29b827e01e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_BLOCK.kt @@ -0,0 +1,59 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* Injection Blocked Alarm Log +*/ +class LOG_ALARM_BLOCK private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 1=INFO, 2=WARNING, 3=MAJOR, 4=CRITICAL + val alarmLevel: Byte, // 1=OCCUR + val ack: Byte, + val amount: Short, // 1=BASE, 2=Meal, 3=snack , 4=square, 5=dual, 6=tube change, 7=needle change, 8=insulin change + val reason: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_ALARM_BLOCK{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", alarmLevel=").append(alarmLevel.toInt()) + sb.append(", ack=").append(ack.toInt()) + sb.append(", amount=").append(amount.toInt()) + sb.append(", reason=").append(reason.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x29 + fun parse(data: String): LOG_ALARM_BLOCK { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_ALARM_BLOCK( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_SHORTAGE.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_SHORTAGE.kt new file mode 100644 index 0000000000..4d3acfbab4 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_ALARM_SHORTAGE.kt @@ -0,0 +1,56 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* Insulin shortage alarm +*/ +class LOG_ALARM_SHORTAGE private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 1=INFO, 2=WARNING, 3=MAJOR, 4=CRITICAL + val alarmLevel: Byte, // 1=OCCUR, 2=STOP + val ack: Byte, // (1~100U) + val remain: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_ALARM_SHORTAGE{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", alarmLevel=").append(alarmLevel.toInt()) + sb.append(", ack=").append(ack.toInt()) + sb.append(", remain=").append(remain.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x2A + fun parse(data: String): LOG_ALARM_SHORTAGE { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_ALARM_SHORTAGE( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_INJECTOR_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_INJECTOR_SUCCESS.kt new file mode 100644 index 0000000000..d5702c0e5b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_INJECTOR_SUCCESS.kt @@ -0,0 +1,53 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 주사기 교체 성공 +*/ +class LOG_CHANGE_INJECTOR_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val primeAmount: Short, // 47.5=4750 + val remainAmount: Short, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_CHANGE_INJECTOR_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", primeAmount=").append(primeAmount.toInt()) + sb.append(", remainAmount=").append(remainAmount.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x1A + fun parse(data: String): LOG_CHANGE_INJECTOR_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_CHANGE_INJECTOR_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_NEEDLE_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_NEEDLE_SUCCESS.kt new file mode 100644 index 0000000000..556b5d33d9 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_NEEDLE_SUCCESS.kt @@ -0,0 +1,53 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 바늘 공기빼기 성공 +*/ +class LOG_CHANGE_NEEDLE_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val primeAmount: Short, // 47.5=4750 + val remainAmount: Short, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_CHANGE_NEEDLE_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", primeAmount=").append(primeAmount.toInt()) + sb.append(", remainAmount=").append(remainAmount.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x1C + fun parse(data: String): LOG_CHANGE_NEEDLE_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_CHANGE_NEEDLE_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_TUBE_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_TUBE_SUCCESS.kt new file mode 100644 index 0000000000..ae97bddcce --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_CHANGE_TUBE_SUCCESS.kt @@ -0,0 +1,53 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 튜브 공기빼기 성공 +*/ +class LOG_CHANGE_TUBE_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val primeAmount: Short, // 47.5=4750 + val remainAmount: Short, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_CHANGE_TUBE_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", primeAmount=").append(primeAmount.toInt()) + sb.append(", remainAmount=").append(remainAmount.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x18 + fun parse(data: String): LOG_CHANGE_TUBE_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_CHANGE_TUBE_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY.kt new file mode 100644 index 0000000000..e7768b2e00 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY.kt @@ -0,0 +1,53 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 당일 주입 총량 (식사, 추가) +*/ +class LOG_INJECTION_1DAY private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 당일 식사주입 총량 47.5=4750 + val mealAmount: Short, // 당일 추가주입 총량 47.5=4750 + val extAmount: Short, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECTION_1DAY{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", mealAmount=").append(mealAmount.toInt()) + sb.append(", extAmount=").append(extAmount.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x2F + fun parse(data: String): LOG_INJECTION_1DAY { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECTION_1DAY( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY_BASAL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY_BASAL.kt new file mode 100644 index 0000000000..1740d54276 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY_BASAL.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 당일 주입 총량 (기저) +*/ +class LOG_INJECTION_1DAY_BASAL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + // 당일 기저주입 총량 47.5=4750 + val amount: Short, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECTION_1DAY_BASAL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", amount=").append(amount.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + const val LOG_KIND: Byte = 0x2E + fun parse(data: String): LOG_INJECTION_1DAY_BASAL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECTION_1DAY_BASAL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer) + ) + } + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1HOUR_BASAL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1HOUR_BASAL.kt new file mode 100644 index 0000000000..f8acab887f --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1HOUR_BASAL.kt @@ -0,0 +1,61 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 1시간 단위 기저 주입량 +*/ +class LOG_INJECTION_1HOUR_BASAL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + tbBeforeAmount: Short, + tbAfterAmount: Short, + val batteryRemain: Byte, + // 남은 전체 인슐린 량(47.5=4750) + private val remainTotalAmount: Short +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + val beforeAmount // 해당시간의 임시기저 계산 전 기저주입량: 기저주입막힘 발생 시 기저주입 막힘량 제외, 기저정지로 인해 주입되지 않은 량 제외, 리셋으로 인해 주입되지 않은 량 제외(47.5=4750) + : Short = tbBeforeAmount + val afterAmount // 해당시간의 임시기저 계산 후 기저주입량: 기저주입막힘 발생 시 기저주입 막힘량 제외, 기저정지로 인해 주입되지 않은 량 제외, 리셋으로 인해 주입되지 않은 량 제외(47.5=4750) + : Short = tbAfterAmount + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECTION_1HOUR_BASAL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", tbBeforeAmount=").append(beforeAmount.toInt()) + sb.append(", tbAfterAmount=").append(afterAmount.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append(", remainTotalAmount=").append(remainTotalAmount.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x2C + fun parse(data: String): LOG_INJECTION_1HOUR_BASAL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECTION_1HOUR_BASAL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_DUAL_NORMAL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_DUAL_NORMAL.kt new file mode 100644 index 0000000000..d46ee4790a --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_DUAL_NORMAL.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 듀얼(일반) 주입량: 듀얼(일반) 주입 완료 시 기록하는 방식 +*/ +class LOG_INJECTION_DUAL_NORMAL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 설정량 47.5=4750 + val setAmount: Short, // 주입량 47.5=4750 + val injectAmount: Short, // 1분 단위 주입 시간 Ex) 124 = 124분 = 2시간 4분 + private val injectTime: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECTION_DUAL_NORMAL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setAmount=").append(setAmount.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x35 + fun parse(data: String): LOG_INJECTION_DUAL_NORMAL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECTION_DUAL_NORMAL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_FAIL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_FAIL.kt new file mode 100644 index 0000000000..bafaea8de9 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_FAIL.kt @@ -0,0 +1,64 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* Dual Injection Fail Log +*/ +class LOG_INJECT_DUAL_FAIL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val injectNormAmount: Short, // 47.5=4750 + val injectSquareAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + private val injectTime: Byte, // 1=주입막힘, 2=배터리잔량부족, 3=약물부족, 4=사용자중지, 5=시스템리셋, 6=기타, 7=긴급정지 + val reason: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_DUAL_FAIL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", injectNormAmount=").append(injectNormAmount.toInt()) + sb.append(", injectSquareAmount=").append(injectSquareAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", reason=").append(reason.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x11 + fun parse(data: String): LOG_INJECT_DUAL_FAIL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_DUAL_FAIL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_SUCCESS.kt new file mode 100644 index 0000000000..c6738c38b2 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_SUCCESS.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 듀얼주입 성공 +*/ +class LOG_INJECT_DUAL_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val injectNormAmount: Short, // 47.5=4750 + val injectSquareAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + private val injectTime: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_DUAL_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", injectNormAmount=").append(injectNormAmount.toInt()) + sb.append(", injectSquareAmount=").append(injectSquareAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x10 + fun parse(data: String): LOG_INJECT_DUAL_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_DUAL_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_FAIL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_FAIL.kt new file mode 100644 index 0000000000..bc667b28e9 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_FAIL.kt @@ -0,0 +1,64 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 식사주입 실패 +*/ +class LOG_INJECT_MEAL_FAIL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + private val setAmount: Short, // 47.5=4750 + val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + private val injectTime: Byte, // 아침=1, 점심=2, 저녁=3 + val time: Byte, // 1=주입막힘, 2=배터리잔량부족, 3=약물부족, 4=사용자중지, 5=시스템리셋, 6=기타, 7=긴급정지 + val reason: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_MEAL_FAIL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setAmount=").append(setAmount.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", time=").append(time.toInt()) + sb.append(", reason=").append(reason.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x09 + fun parse(data: String): LOG_INJECT_MEAL_FAIL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_MEAL_FAIL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_SUCCESS.kt new file mode 100644 index 0000000000..23e7f27b57 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_MEAL_SUCCESS.kt @@ -0,0 +1,64 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 식사주입 성공 +*/ +class LOG_INJECT_MEAL_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + private val setAmount: Short, // 47.5=4750 + val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + private val injectTime: Byte, // 아침=1, 점심=2, 저녁=3 + val time: Byte, + batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + val batteryRemain: Byte = batteryRemain + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_MEAL_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setAmount=").append(setAmount.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", time=").append(time.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x08 + fun parse(data: String): LOG_INJECT_MEAL_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_MEAL_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_FAIL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_FAIL.kt new file mode 100644 index 0000000000..2e9eb5fe0d --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_FAIL.kt @@ -0,0 +1,64 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 일반주입 실패 +*/ +class LOG_INJECT_NORMAL_FAIL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val setAmount: Short, // 47.5=4750 + val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + val injectTime: Byte, // 1=주입막힘, 2=배터리잔량부족, 3=약물부족, 4=사용자중지, 5=시스템리셋, 6=기타, 7=긴급정지 + val reason: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_NORMAL_FAIL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setAmount=").append(setAmount.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", reason=").append(reason.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x0B + fun parse(data: String): LOG_INJECT_NORMAL_FAIL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_NORMAL_FAIL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_SUCCESS.kt new file mode 100644 index 0000000000..be3804eb00 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_NORMAL_SUCCESS.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 일반주입 성공 +*/ +class LOG_INJECT_NORMAL_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val setAmount: Short, // 47.5=4750 + val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + val injectTime: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_NORMAL_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setAmount=").append(setAmount.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x0A + fun parse(data: String): LOG_INJECT_NORMAL_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_NORMAL_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_FAIL.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_FAIL.kt new file mode 100644 index 0000000000..b6a4d990f1 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_FAIL.kt @@ -0,0 +1,61 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 스퀘어주입 실패 +*/ +class LOG_INJECT_SQUARE_FAIL private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + private val injectTime: Byte, // 1=주입막힘, 2=배터리잔량부족, 3=약물부족, 4=사용자중지, 5=시스템리셋, 6=기타, 7=긴급정지 + val reason: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_SQUARE_FAIL{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", reason=").append(reason.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x0E + fun parse(data: String): LOG_INJECT_SQUARE_FAIL { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_SQUARE_FAIL( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_SUCCESS.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_SUCCESS.kt new file mode 100644 index 0000000000..168903de2b --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_SQUARE_SUCCESS.kt @@ -0,0 +1,57 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 스퀘어주입 성공 +*/ +class LOG_INJECT_SQUARE_SUCCESS private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val injectAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) + private val injectTime: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_INJECT_SQUARE_SUCCESS{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", injectAmount=").append(injectAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x0D + fun parse(data: String): LOG_INJECT_SQUARE_SUCCESS { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_INJECT_SQUARE_SUCCESS( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_RESET_SYS_V3.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_RESET_SYS_V3.kt new file mode 100644 index 0000000000..bc7a688382 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_RESET_SYS_V3.kt @@ -0,0 +1,56 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* + * System Reset Log + */ +class LOG_RESET_SYS_V3 private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + val batteryRemain: Byte, + val reason: Byte, // 사유(1:공장초기화 후 리셋, 2:긴급정지 해제 후 리셋, 3:사용자 배터리 교체 후 리셋, 4:캘리브레이션 후 리셋, 9:예상치 못한 시스템 리셋) + val rcon1: Short, // PIC 데이터 시트 내 정의된 2바이트 값 + val rcon2: Short // PIC 데이터 시트 내 정의된 2바이트 값 +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_RESET_SYS_V3{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append(", reason=").append(reason.toInt()) + sb.append(", rcon1=").append(rcon1.toInt()) + sb.append(", rcon2=").append(rcon2.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x01 + fun parse(data: String): LOG_RESET_SYS_V3 { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_RESET_SYS_V3( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_DUAL_INJECTION.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_DUAL_INJECTION.kt new file mode 100644 index 0000000000..2ff5212bfc --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_DUAL_INJECTION.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 듀얼주입 설정(시작) +*/ +class LOG_SET_DUAL_INJECTION private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + val setNormAmount: Short, // 47.5=4750 + val setSquareAmount: Short, // 47.5=4750 + private val injectTime: Byte, // 1~30( 1: 10min ) + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_SET_DUAL_INJECTION{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setNormAmount=").append(setNormAmount.toInt()) + sb.append(", setSquareAmount=").append(setSquareAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x0F + fun parse(data: String): LOG_SET_DUAL_INJECTION { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_SET_DUAL_INJECTION( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_SQUARE_INJECTION.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_SQUARE_INJECTION.kt new file mode 100644 index 0000000000..562172146e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SET_SQUARE_INJECTION.kt @@ -0,0 +1,57 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 스퀘어주입 설정(시작) +*/ +class LOG_SET_SQUARE_INJECTION private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 47.5=4750 + val setAmount: Short, // 1~30(10분 단위 값 의미) + private val injectTime: Byte, + val batteryRemain: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + fun getInjectTime(): Int { + return injectTime and 0xff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_SET_SQUARE_INJECTION{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", setAmount=").append(setAmount.toInt()) + sb.append(", injectTime=").append(injectTime and 0xff) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x0C + fun parse(data: String): LOG_SET_SQUARE_INJECTION { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_SET_SQUARE_INJECTION( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_RELEASE_V2.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_RELEASE_V2.kt new file mode 100644 index 0000000000..d27625fe8d --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_RELEASE_V2.kt @@ -0,0 +1,71 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 일시정지 중지 (기저정지 해제) +*/ +class LOG_SUSPEND_RELEASE_V2 private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + batteryRemain: Byte, + patternType: Byte +) { + + val type: Byte + val kind: Byte + val batteryRemain: Byte + val patternType // 1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2 + : Byte + + override fun toString(): String { + val sb = StringBuilder("LOG_SUSPEND_RELEASE_V2{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append(", patternType=").append(patternType.toInt()) + sb.append('}') + return sb.toString() + } + + fun getBasalPattern():String { + //1=Injection blockage, 2=Battery shortage, 3=Drug shortage, 4=User shutdown, 5=System reset, 6=Other, 7=Emergency shutdown + return when(patternType) { + 1.toByte() -> "Base" + 2.toByte() -> "Life1" + 3.toByte() -> "Life2" + 4.toByte() -> "Life3" + 5.toByte() -> "Dr1" + 6.toByte() -> "Dr2" + else -> "No Pattern" + } + } + companion object { + + const val LOG_KIND: Byte = 0x04 + fun parse(data: String): LOG_SUSPEND_RELEASE_V2 { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_SUSPEND_RELEASE_V2( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + + init { + type = PumplogUtil.getType(typeAndKind) + kind = PumplogUtil.getKind(typeAndKind) + this.batteryRemain = batteryRemain + this.patternType = patternType + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_V2.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_V2.kt new file mode 100644 index 0000000000..4f69dc4c89 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_V2.kt @@ -0,0 +1,63 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 일시정지 시작 (기저정지) +*/ +class LOG_SUSPEND_V2 private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + val batteryRemain: Byte, // 1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2 + val patternType: Byte +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + override fun toString(): String { + val sb = StringBuilder("LOG_SUSPEND_V2{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", batteryRemain=").append(batteryRemain.toInt()) + sb.append(", patternType=").append(patternType.toInt()) + sb.append('}') + return sb.toString() + } + + fun getBasalPattern(): String { + //1=Injection blockage, 2=Battery shortage, 3=Drug shortage, 4=User shutdown, 5=System reset, 6=Other, 7=Emergency shutdown + return when(patternType) { + 1.toByte() -> "Base" + 2.toByte() -> "Life1" + 3.toByte() -> "Life2" + 4.toByte() -> "Life3" + 5.toByte() -> "Dr1" + 6.toByte() -> "Dr2" + else -> "No Pattern" + } + } + + companion object { + + const val LOG_KIND: Byte = 0x03 + fun parse(data: String): LOG_SUSPEND_V2 { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_SUSPEND_V2( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_START_V3.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_START_V3.kt new file mode 100644 index 0000000000..029fe115e0 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_START_V3.kt @@ -0,0 +1,61 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import org.apache.commons.lang3.StringUtils +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 임시기저 설정(시작) +*/ +class LOG_TB_START_V3 private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, // 임시기저 시간(30분 ~ 24시간, 2 ~ 96, 1당 15분 단위 증감) + val tbTime: Byte, // 임시기저 주입량/률, Rate: 1000(0.00U) ~ 1600(6.00U), Ratio: 50000(0%) ~ 50200(200%), 50000이상이면 주입률로 판정, 별도 계산/역산식 참조 + private val tbInjectRateRatio: Short, + private val tbDttm: String // 앱에서 생성 전달한 임시기저 시작(요청) 시간 +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + fun getTbInjectRateRatio(): Int { + return tbInjectRateRatio and 0xffff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_TB_START_V3{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", tbTime=").append(tbTime.toInt()) + sb.append(", tbInjectRateRatio=").append(tbInjectRateRatio and 0xffff) + if (!StringUtils.equals(tbDttm, PumplogUtil.getDttm("ffffffff"))) { + sb.append(", tbDttm=").append(tbDttm) + } + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x12 + fun parse(data: String): LOG_TB_START_V3 { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_TB_START_V3( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getDttm(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_STOP_V3.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_STOP_V3.kt new file mode 100644 index 0000000000..f1dc88fb61 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_TB_STOP_V3.kt @@ -0,0 +1,64 @@ +package info.nightscout.androidaps.diaconn.pumplog + +import okhttp3.internal.and +import org.apache.commons.lang3.StringUtils +import java.nio.ByteBuffer +import java.nio.ByteOrder + +/* +* 임시기저 중지(완료) +*/ +class LOG_TB_STOP_V3 private constructor( + val data: String, + val dttm: String, + typeAndKind: Byte, + // 임시기저 주입량/률, Rate: 1000(0.00U) ~ 1600(6.00U), Ratio: 50000(0%) ~ 50200(200%), 50000이상이면 주입률로 판정, 별도 계산/역산식 참조 + private val tbInjectRateRatio: Short, + // 0=완료, 4=사용자중단, 6=기타, 7=긴급정지 + val reason: Byte, + // 앱에서 생성 전달한 임시기저 시작(요청) 시간 + private val tbDttm: String +) { + + val type: Byte = PumplogUtil.getType(typeAndKind) + val kind: Byte = PumplogUtil.getKind(typeAndKind) + + fun getTbInjectRateRatio(): Int { + return tbInjectRateRatio and 0xffff + } + + override fun toString(): String { + val sb = StringBuilder("LOG_TB_STOP_V3{") + sb.append("LOG_KIND=").append(LOG_KIND.toInt()) + sb.append(", data='").append(data).append('\'') + sb.append(", dttm='").append(dttm).append('\'') + sb.append(", type=").append(type.toInt()) + sb.append(", kind=").append(kind.toInt()) + sb.append(", tbInjectRateRatio=").append(tbInjectRateRatio and 0xffff) + sb.append(", reason=").append(reason.toInt()) + if (!StringUtils.equals(tbDttm, PumplogUtil.getDttm("ffffffff"))) { + sb.append(", tbDttm=").append(tbDttm) + } + sb.append('}') + return sb.toString() + } + + companion object { + + const val LOG_KIND: Byte = 0x13 + fun parse(data: String): LOG_TB_STOP_V3 { + val bytes = PumplogUtil.hexStringToByteArray(data) + val buffer = ByteBuffer.wrap(bytes) + buffer.order(ByteOrder.LITTLE_ENDIAN) + return LOG_TB_STOP_V3( + data, + PumplogUtil.getDttm(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getShort(buffer), + PumplogUtil.getByte(buffer), + PumplogUtil.getDttm(buffer) + ) + } + } + +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/PumplogUtil.java b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/PumplogUtil.java new file mode 100644 index 0000000000..edb6288c92 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/PumplogUtil.java @@ -0,0 +1,157 @@ +package info.nightscout.androidaps.diaconn.pumplog; + +import org.apache.commons.lang3.RegExUtils; +import org.apache.commons.lang3.StringUtils; + +import java.nio.ByteBuffer; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +/* + * 디아콘 G8 펌프 로그 유틸리티 클래스 + */ +public class PumplogUtil { + /* + * 바이트버퍼에서 4바이트 날짜를 구한다. + * @param buffer 바이트버퍼 + * @return GMT 날짜 문자열 + */ + public static String getDttm(ByteBuffer buffer) { + byte b0 = buffer.get(); + byte b1 = buffer.get(); + byte b2 = buffer.get(); + byte b3 = buffer.get(); + long pumpTime = Long.parseLong(String.format("%02x%02x%02x%02x", b3, b2, b1, b0), 16); + long epochTime = new Date(0).getTime(); // 1970-01-01 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UCT")); + return sdf.format(new Date(epochTime + pumpTime * 1000)); + } + + /* + * 바이트버퍼에서 4바이트 날짜를 구한다. + * @param data 로그데이터 + * @return GMT 날짜 문자열 + */ + public static String getDttm(String data) { + byte[] bytes = PumplogUtil.hexStringToByteArray(data); + byte b0 = bytes[0]; + byte b1 = bytes[1]; + byte b2 = bytes[2]; + byte b3 = bytes[3]; + long pumpTime = Long.parseLong(String.format("%02x%02x%02x%02x", b3, b2, b1, b0), 16); + long epochTime = new Date(0).getTime(); // 1970-01-01 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + return sdf.format(new Date(epochTime + pumpTime * 1000)); + } + + /* + * 바이트버퍼에서 1바이트를 구한다. + * @param buffer 바이트버퍼 + * @return byte + */ + public static byte getByte(ByteBuffer buffer) { + return buffer.get(); + } + + /* + * 바이트버퍼에서 2바이트를 구한다. + * @param buffer 바이트버퍼 + * @return short + */ + public static short getShort(ByteBuffer buffer) { + return buffer.getShort(); + } + + /* + * 바이트버퍼에서 4바이트를 구한다. + * @param buffer 바이트버퍼 + * @return int + */ + public static int getInt(ByteBuffer buffer) { + return buffer.getInt(); + } + + /* + * 로그데이터에서 로그 타입 바이트를 구한다. + * @param data 로그데이터 + * @return byte + */ + public static byte getType(String data) { + byte[] bytes = hexStringToByteArray(data); + return getType(bytes[4]); + } + + /* + * 로그데이터에서 로그 종류 바이트를 구한다. + * @param data 로그데이터 + * @return byte + */ + public static byte getKind(String data) { + byte[] bytes = hexStringToByteArray(data); + //System.out.println("byte=" + Arrays.toString(bytes)); + return getKind(bytes[4]); + } + + /* + * 바이트 데이터에서 로그 타입 부분을 추출 한다. + * @param b 바이트 + * @return byte + */ + public static byte getType(byte b) { + return (byte) ((b >> 6) & 0b00000011); // 상위 2비트 추출 + } + + /* + * 바이트 데이터에서 로그 종류 부분을 추출 한다. + * @param b 바이트 + * @return byte + */ + public static byte getKind(byte b) { + return (byte) (b & 0b00111111); // 하위 6비트 추출 + } + + /* + * 16진수 표기 문자열을 바이트 배열로 변환한다. + * @param s 16진수 표기 문자열 + * @return byte[] + */ + public static byte[] hexStringToByteArray(String s) { + int len = s.length(); + byte[] data = new byte[len / 2]; + for (int i = 0; i < len; i += 2) { + data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); + } + return data; + } + + /* + * 펌프 시간을 날짜 타입으로 변환한다.(펌프에서 GMT기준으로 초를 구하므로, Date 변환시 GMT 기준으로 구해야 한다. + * @param data 1970.1.1이후 경과한 초 + * @return 날짜(GMT기준) + */ + public static Date pumpTimeToGMTDate(Integer data) { + long epochTime = new Date(0).getTime(); // 1970-01-01 + long pumpTime = data.longValue() * 1000; // 초를 밀리초 단위로 변환 + int timeZoneOffset = TimeZone.getDefault().getRawOffset(); // GMT와 로컬 타임존 사이의 차이 + return new Date(epochTime + pumpTime - timeZoneOffset); + } + + /* + * 펌프 버전이 해당 버전보다 크거나 같은지 여부 확인(새로운 기능이 추가된 버전을 체크하기 위함) + */ + public static boolean isPumpVersionGe(String pump_version, int major, int minor) { + String version = RegExUtils.replaceAll(pump_version, "[^\\d\\.]", ""); + int pump_major = Integer.parseInt(StringUtils.split(version, ".")[0]); + int pump_minor = Integer.parseInt(StringUtils.split(version, ".")[1]); + if (pump_major > major) { // 메이저 버전이 클 때 + return true; + } else if (pump_major < major) { // 메이저 버전이 작을 때 + return false; + } else { // 메이저 버전이 같다면 마이너 버전이 같거나 클 때 + return pump_minor >= minor; + } + } +} \ No newline at end of file diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt new file mode 100644 index 0000000000..83b8475b9e --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt @@ -0,0 +1,367 @@ +package info.nightscout.androidaps.diaconn.service + +import android.bluetooth.* +import android.content.Context +import android.content.Intent +import android.os.SystemClock +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.packet.* +import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.extensions.notify +import info.nightscout.androidaps.extensions.waitMillis +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.utils.resources.ResourceHelper +import java.util.* +import java.util.concurrent.ScheduledFuture +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class BLECommonService @Inject internal constructor( + private val injector: HasAndroidInjector, + private val aapsLogger: AAPSLogger, + private val resourceHelper: ResourceHelper, + private val context: Context, + private val rxBus: RxBusWrapper, + private val diaconnG8ResponseMessageHashTable: DiaconnG8ResponseMessageHashTable, + private val diaconnG8SettingResponseMessageHashTable: DiaconnG8SettingResponseMessageHashTable, + private val diaconnG8Pump: DiaconnG8Pump, +){ + + companion object { + private const val WRITE_DELAY_MILLIS: Long = 50 + private const val INDICATION_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" + private const val WRITE_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" + private const val CHARACTERISTIC_CONFIG_UUID = "00002902-0000-1000-8000-00805f9b34fb" + } + + private var scheduledDisconnection: ScheduledFuture<*>? = null + private var processedMessage: DiaconnG8Packet? = null + private var processedMessageByte: ByteArray? = null + private val mSendQueue = ArrayList() + private var bluetoothManager: BluetoothManager? = null + private var bluetoothAdapter: BluetoothAdapter? = null + private var connectDeviceName: String? = null + private var bluetoothGatt: BluetoothGatt? = null + + + var isConnected = false + var isConnecting = false + private var uartIndicate: BluetoothGattCharacteristic? = null + private var uartWrite: BluetoothGattCharacteristic? = null + + private var mSequence : Int = 0 + + private fun getMsgSequence(): Int { + val seq = mSequence % 255 + mSequence++ + if (mSequence == 255) { + mSequence = 0 + } + return seq + } + + @Synchronized + fun connect(from: String, address: String?): Boolean { + aapsLogger.debug(LTag.PUMPBTCOMM, "Initializing Bluetooth ") + if (bluetoothManager == null) { + bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + if (bluetoothManager == null) { + aapsLogger.error("Unable to initialize BluetoothManager.") + return false + } + } + bluetoothAdapter = bluetoothManager?.adapter + if (bluetoothAdapter == null) { + aapsLogger.error("Unable to obtain a BluetoothAdapter.") + return false + } + + if (address == null) { + aapsLogger.error("unspecified address.") + return false + } + + val device = bluetoothAdapter?.getRemoteDevice(address) + if (device == null) { + aapsLogger.error("Device not found. Unable to connect from: $from") + return false + } + aapsLogger.debug(LTag.PUMPBTCOMM, "Trying to create a new connection from: $from") + connectDeviceName = device.name + bluetoothGatt = device.connectGatt(context, false, mGattCallback) + + isConnected = false + isConnecting = true + return true + } + + @Synchronized + fun stopConnecting() { + isConnecting = false + } + + @Synchronized + fun disconnect(from: String) { + aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from") + + // cancel previous scheduled disconnection to prevent closing upcoming connection + scheduledDisconnection?.cancel(false) + scheduledDisconnection = null + + if (bluetoothAdapter == null || bluetoothGatt == null) { + aapsLogger.error("disconnect is not possible: (mBluetoothAdapter == null) " + (bluetoothAdapter == null)) + aapsLogger.error("disconnect is not possible: (mBluetoothGatt == null) " + (bluetoothGatt == null)) + return + } + bluetoothGatt?.setCharacteristicNotification(uartIndicate, false) + bluetoothGatt?.disconnect() + isConnected = false + SystemClock.sleep(2000) + } + + @Synchronized + fun close() { + aapsLogger.debug(LTag.PUMPBTCOMM, "BluetoothAdapter close") + bluetoothGatt?.close() + bluetoothGatt = null + } + + private val mGattCallback: BluetoothGattCallback = object : BluetoothGattCallback() { + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { + onConnectionStateChangeSynchronized(gatt, newState) // call it synchronized + } + + override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { + aapsLogger.debug(LTag.PUMPBTCOMM, "onServicesDiscovered") + if (status == BluetoothGatt.GATT_SUCCESS) { + findCharacteristic() + } + } + + override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { + aapsLogger.debug(LTag.PUMPBTCOMM, "(응답) onCharacteristicChanged: " + DiaconnG8Packet.toHex(characteristic.value)) + // 대량로그응답 처리. + if(characteristic.value[1] == 0xb2.toByte()) { + aapsLogger.debug(LTag.PUMPBTCOMM, "(대량 로그 처리 응답) onCharacteristicChanged: " + DiaconnG8Packet.toHex(characteristic.value)) + val message = BigLogInquireResponsePacket(injector) + message.handleMessage(characteristic.value) + + // 초기화 + mSendQueue.clear() + } else { + processResponseMessage(characteristic.value) + } + } + + override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { + aapsLogger.debug(LTag.PUMPBTCOMM, "(요청) onCharacteristicWrite: " + DiaconnG8Packet.toHex(characteristic.value)) + } + } + + @Synchronized + private fun writeCharacteristicNoResponse(characteristic: BluetoothGattCharacteristic, data: ByteArray) { + Thread(Runnable { + SystemClock.sleep(WRITE_DELAY_MILLIS) + if (bluetoothAdapter == null || bluetoothGatt == null) { + aapsLogger.error("BluetoothAdapter not initialized_ERROR") + isConnecting = false + isConnected = false + return@Runnable + } + characteristic.value = data + characteristic.writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE + bluetoothGatt?.writeCharacteristic(characteristic) + }).start() + SystemClock.sleep(50) + } + + // private val uartIndicateBTGattChar: BluetoothGattCharacteristic + // get() = uartIndicate + // ?: BluetoothGattCharacteristic(UUID.fromString(INDICATION_UUID), BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0).also { uartIndicate = it } + + private val uartWriteBTGattChar: BluetoothGattCharacteristic + get() = uartWrite + ?: BluetoothGattCharacteristic(UUID.fromString(WRITE_UUID), BluetoothGattCharacteristic.PROPERTY_WRITE or BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, 0).also { uartWrite = it } + + private fun getSupportedGattServices(): List? { + aapsLogger.debug(LTag.PUMPBTCOMM, "getSupportedGattServices") + if (bluetoothAdapter == null || bluetoothGatt == null) { + aapsLogger.error("BluetoothAdapter not initialized_ERROR") + isConnecting = false + isConnected = false + return null + } + return bluetoothGatt?.services + } + + private fun findCharacteristic() { + val gattServices = getSupportedGattServices() ?: return + var uuid: String + for (gattService in gattServices) { + val gattCharacteristics = gattService.characteristics + for (gattCharacteristic in gattCharacteristics) { + uuid = gattCharacteristic.uuid.toString() + if (INDICATION_UUID == uuid) { + uartIndicate = gattCharacteristic + //setCharacteristicNotification(uartIndicate, true) + bluetoothGatt?.setCharacteristicNotification(uartIndicate, true) + // nRF Connect 참고하여 추가함 + val descriptor: BluetoothGattDescriptor = uartIndicate!!.getDescriptor(UUID.fromString(CHARACTERISTIC_CONFIG_UUID)) + descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE + bluetoothGatt!!.writeDescriptor(descriptor) + } + if (WRITE_UUID == uuid) { + uartWrite = gattCharacteristic + } + } + } + } + + @Synchronized + private fun onConnectionStateChangeSynchronized(gatt: BluetoothGatt, newState: Int) { + aapsLogger.debug(LTag.PUMPBTCOMM, "onConnectionStateChange newState : $newState") + if (newState == BluetoothProfile.STATE_CONNECTED) { + gatt.discoverServices() + isConnected = true + isConnecting = false + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED)) + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + close() + isConnected = false + isConnecting = false + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)) + aapsLogger.debug(LTag.PUMPBTCOMM, "Device was disconnected " + gatt.device.name) //Device was disconnected + } + } + + // the rest of packets + fun sendMessage(message: DiaconnG8Packet, waitMillis: Long) { + // 펌프로 요청하기전 변수에 담기. 마지막 요청정보 확인용. + processedMessage = message + val sequence = getMsgSequence() + aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.friendlyName + " Sequence >>" + sequence) + // 요청 + val bytes = message.encode(sequence) + processedMessageByte = bytes + + aapsLogger.debug(LTag.PUMPBTCOMM, "sendMessage() before mSendQueue.size :: ${mSendQueue.size}") + // 펌프에 요청 보내기. + writeCharacteristicNoResponse(uartWriteBTGattChar, bytes) + // 요청 큐에 요청할 바이트 정보 담기. + synchronized(mSendQueue) { + if(mSendQueue.size > 10) mSendQueue.clear() + mSendQueue.add(bytes) + } + aapsLogger.debug(LTag.PUMPBTCOMM, "sendMessage() after mSendQueue.size :: ${mSendQueue.size}") + + // 메시지동기화 + synchronized(message) { + try { + message.waitMillis(waitMillis) //0.5초 대기. + } catch (e: InterruptedException) { + aapsLogger.error("sendMessage InterruptedException", e) + } + } + } + + // process common packet response + private fun processResponseMessage(data: ByteArray) { + isConnected = true + + //요청정보 + val originalMessageSeq = processedMessage?.getSeq(processedMessageByte) + + // 응답정보 + val receivedCommand = DiaconnG8Packet(injector).getCmd(data) + val receivedSeq = DiaconnG8Packet(injector).getSeq(data) + val receivedType = DiaconnG8Packet(injector).getType(data) + + aapsLogger.debug(LTag.PUMPBTCOMM, "originalMessageSeq :: $originalMessageSeq, receivedSeq :: $receivedSeq") + aapsLogger.debug(LTag.PUMPBTCOMM, "receivedCommand :: $receivedCommand") + + // 응답메시지가 조회응답인지. 설정응답인지 구분해야됨. + var message:DiaconnG8Packet? = null + // 요청시퀀스와 응답의 시퀀스가 동일한 경우에만 처리. + // 펌프로부터 받은 보고응답의 경우 처리 + if(receivedType == 3) { + message = diaconnG8ResponseMessageHashTable.findMessage(receivedCommand) + // injection Blocked Report + if(message is InjectionBlockReportPacket ) { + message.handleMessage(data) + diaconnG8Pump.bolusBlocked = true + val i = Intent(context, ErrorHelperActivity::class.java) + i.putExtra("soundid", R.raw.boluserror) + i.putExtra("status", resourceHelper.gs(R.string.injectionblocked)) + i.putExtra("title", resourceHelper.gs(R.string.injectionblocked)) + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(i) + return + } + // battery warning report + if(message is BatteryWarningReportPacket ) { + message.handleMessage(data) + val i = Intent(context, ErrorHelperActivity::class.java) + i.putExtra("soundid", R.raw.boluserror) + i.putExtra("status", resourceHelper.gs(R.string.needbatteryreplace)) + i.putExtra("title", resourceHelper.gs(R.string.batterywarning)) + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(i) + return + } + + // insulin lack warning report + if(message is InsulinLackReportPacket ) { + message.handleMessage(data) + val i = Intent(context, ErrorHelperActivity::class.java) + i.putExtra("soundid", R.raw.boluserror) + i.putExtra("status", resourceHelper.gs(R.string.needinsullinreplace)) + i.putExtra("title", resourceHelper.gs(R.string.insulinlackwarning)) + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(i) + return + } + + } else { + // 큐에 담긴 명령 대기중에 있는 것 조회 처리. + synchronized(mSendQueue) { + val sendQueueSize = mSendQueue.size + if (sendQueueSize > 0) { + for (i in sendQueueSize-1 downTo 0 ) { + val sendQueueSeq = DiaconnG8Packet(injector).getSeq(mSendQueue[i]) + val sendQueueType = DiaconnG8Packet(injector).getType(mSendQueue[i]) + if (sendQueueSeq == receivedSeq) { + // 설정명령에 대한 응답 + if (sendQueueType == 0) { + message = diaconnG8SettingResponseMessageHashTable.findMessage(receivedCommand) + + // 조회명령에 대한 응답 + } else if (sendQueueType == 1) { + message = diaconnG8ResponseMessageHashTable.findMessage(receivedCommand) + } + // 처리 후 큐에서 삭제. + mSendQueue.removeAt(i) + break + } + } + } + } + } + + if (message != null) { + aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< " + message!!.friendlyName + " " + DiaconnG8Packet.toHex(data)) + // process received data + message!!.handleMessage(data) + message!!.setReceived() + synchronized(message!!) { + // notify to sendMessage + message!!.notify() + } + } else aapsLogger.error("Unknown message received " + DiaconnG8Packet.toHex(data)) + } +} diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt new file mode 100644 index 0000000000..611f8fef23 --- /dev/null +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt @@ -0,0 +1,641 @@ +package info.nightscout.androidaps.diaconn.service + +import android.app.Service +import android.content.Context +import android.content.Intent +import android.os.Binder +import android.os.IBinder +import android.os.SystemClock +import dagger.android.DaggerService +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.diaconn.DiaconnG8Plugin +import info.nightscout.androidaps.diaconn.DiaconnG8Pump +import info.nightscout.androidaps.diaconn.R +import info.nightscout.androidaps.diaconn.events.EventDiaconnG8NewStatus +import info.nightscout.androidaps.diaconn.packet.* +import info.nightscout.androidaps.dialogs.BolusProgressDialog +import info.nightscout.androidaps.events.EventAppExit +import info.nightscout.androidaps.events.EventInitializationChanged +import info.nightscout.androidaps.events.EventProfileSwitchChanged +import info.nightscout.androidaps.events.EventPumpStatusChanged +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.Profile +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.interfaces.PumpSync +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.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.common.defs.PumpType +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.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import org.joda.time.DateTime +import org.joda.time.DateTimeZone +import java.util.concurrent.TimeUnit +import javax.inject.Inject +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.min + +class DiaconnG8Service : DaggerService() { + @Inject lateinit var injector: HasAndroidInjector + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var sp: SP + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var context: Context + @Inject lateinit var diaconnG8Plugin : DiaconnG8Plugin + @Inject lateinit var diaconnG8Pump: DiaconnG8Pump + @Inject lateinit var diaconnG8ResponseMessageHashTable: DiaconnG8ResponseMessageHashTable + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var constraintChecker: ConstraintChecker + @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage + @Inject lateinit var bleCommonService: BLECommonService + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var pumpSync: PumpSync + @Inject lateinit var dateUtil: DateUtil + + private val disposable = CompositeDisposable() + private val mBinder: IBinder = LocalBinder() + private var lastApproachingDailyLimit: Long = 0 + + override fun onCreate() { + super.onCreate() + disposable.add(rxBus + .toObservable(EventAppExit::class.java) + .observeOn(Schedulers.io()) + .subscribe({ stopSelf() }) { fabricPrivacy.logException(it) } + ) + } + + inner class LocalBinder : Binder() { + val serviceInstance: DiaconnG8Service + get() = this@DiaconnG8Service + } + + override fun onBind(intent: Intent): IBinder { + return mBinder + } + + override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { + return Service.START_STICKY + } + + override fun onDestroy() { + disposable.clear() + super.onDestroy() + } + + val isConnected: Boolean + get() = bleCommonService.isConnected + + val isConnecting: Boolean + get() = bleCommonService.isConnecting + + fun connect(from: String, address: String): Boolean { + return bleCommonService.connect(from, address) + } + + fun stopConnecting() { + bleCommonService.stopConnecting() + } + + fun disconnect(from: String) { + bleCommonService.disconnect(from) + } + + fun sendMessage(message: DiaconnG8Packet, waitMillis: Long) { + bleCommonService.sendMessage(message, waitMillis) + } + + private fun sendMessage(message: DiaconnG8Packet) { + bleCommonService.sendMessage(message, 500) + } + + fun readPumpStatus() { + try { + val pump = activePlugin.activePump + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) + sendMessage(BasalLimitInquirePacket(injector), 2000) // basal Limit + sendMessage(SneckLimitInquirePacket(injector), 2000) // bolus Limit + sendMessage(BigMainInfoInquirePacket(injector), 2000) // Pump Main Info + sendMessage(SoundInquirePacket(injector), 2000) // sounds + sendMessage(DisplayTimeInquirePacket(injector), 2000) // display + sendMessage(LanguageInquirePacket(injector), 2000) // language + + diaconnG8Pump.lastConnection = System.currentTimeMillis() + + val profile = profileFunction.getProfile() + if (profile != null && abs(diaconnG8Pump.baseAmount - profile.getBasal()) >= pump.pumpDescription.basalStep) { + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) + + if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { + rxBus.send(EventProfileSwitchChanged()) + } + } + + // 시간 설정 + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))) + var timeDiff = (diaconnG8Pump.getPumpTime() - System.currentTimeMillis()) / 1000L + if (diaconnG8Pump.getPumpTime() == 0L) { + // initial handshake was not successful + // de-initialize pump + diaconnG8Pump.reset() + rxBus.send(EventDiaconnG8NewStatus()) + rxBus.send(EventInitializationChanged()) + return + } + aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds") + // phone timezone + val tz = DateTimeZone.getDefault() + val instant = DateTime.now().millis + val offsetInMilliseconds = tz.getOffset(instant).toLong() + val offset = TimeUnit.MILLISECONDS.toHours(offsetInMilliseconds).toInt() + if (abs(timeDiff) > 60) { + if (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 + ErrorHelperActivity.runAlarm(context, resourceHelper.gs(R.string.largetimediff), resourceHelper.gs(R.string.largetimedifftitle), R.raw.error) + + + //de-initialize pump + diaconnG8Pump.reset() + rxBus.send(EventDiaconnG8NewStatus()) + rxBus.send(EventInitializationChanged()) + return + } else { + // 폰과 휴대폰의 시간 동기화 + // 임시기저가 진행 여부에 따른 시간설정 분기. + if(!diaconnG8Pump.isTempBasalInProgress) { + val msgPacket = TimeSettingPacket(injector, dateUtil.now(), offset) + sendMessage(msgPacket) + + // otp process + if(!processConfirm(msgPacket.msgType)) return + + timeDiff = (diaconnG8Pump.getPumpTime() - System.currentTimeMillis()) / 1000L + aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds") + } + } + } + loadHistory() + val eb = pumpSync.expectedPumpState().extendedBolus + diaconnG8Pump.fromExtendedBolus(eb) + val tbr = pumpSync.expectedPumpState().temporaryBasal + diaconnG8Pump.fromTemporaryBasal(tbr) + rxBus.send(EventDiaconnG8NewStatus()) + rxBus.send(EventInitializationChanged()) + //NSUpload.uploadDeviceStatus(); + if (diaconnG8Pump.dailyTotalUnits > diaconnG8Pump.maxDailyTotalUnits * Constants.dailyLimitWarning) { + aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + diaconnG8Pump.dailyTotalUnits + "/" + diaconnG8Pump.maxDailyTotalUnits) + if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { + val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT) + rxBus.send(EventNewNotification(reportFail)) + pumpSync.insertAnnouncement(resourceHelper.gs(R.string.approachingdailylimit) + ": " + diaconnG8Pump.dailyTotalUnits + "/" + diaconnG8Pump.maxDailyTotalUnits + "U", null, PumpType.DIACONN_G8, diaconnG8Pump.serialNo.toString()) + lastApproachingDailyLimit = System.currentTimeMillis() + } + } + } catch (e: Exception) { + aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e) + } + aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded") + } + + fun loadHistory(): PumpEnactResult { + if (!diaconnG8Plugin.isInitialized()) { + val result = PumpEnactResult(injector).success(false) + result.comment = "pump not initialized" + return result + } + sendMessage(LogStatusInquirePacket(injector), 1000) + + // pump version check + if(diaconnG8Pump.isPumpVersionGe2_63) { + sendMessage(IncarnationInquirePacket(injector), 1000) + } + + val result = PumpEnactResult(injector) + + // pump log status + val pumpLastNum = diaconnG8Pump.pumpLastLogNum + val pumpWrappingCount = diaconnG8Pump.pumpWrappingCount + val apsIncarnationNum = sp.getInt(resourceHelper.gs(R.string.apsIncarnationNo), 65536) + // aps last log num + val pumpSerialNo = sp.getInt(resourceHelper.gs(R.string.pumpserialno), 0) + val apsWrappingCount = sp.getInt(resourceHelper.gs(R.string.apsWrappingCount), 0) + val apsLastLogNum = sp.getInt(resourceHelper.gs(R.string.apslastLogNum), 0) + + // if first install app + if(apsWrappingCount == 0 && apsLastLogNum == 0 ) { + pumpLogDefaultSetting() + } + + // if pump reset + if(apsIncarnationNum != diaconnG8Pump.pumpIncarnationNum) { + pumpLogDefaultSetting() + sp.putInt(resourceHelper.gs(R.string.apsIncarnationNo), diaconnG8Pump.pumpIncarnationNum) + } + + // if another pump + if(pumpSerialNo != diaconnG8Pump.serialNo) { + pumpLogDefaultSetting() + sp.putInt(resourceHelper.gs(R.string.pumpserialno), diaconnG8Pump.serialNo) + } + + val apsLastNum = apsWrappingCount * 10000 + apsLastLogNum + if((pumpWrappingCount * 10000 + pumpLastNum) < apsLastLogNum ) { + pumpLogDefaultSetting() + } + + val start:Int? // log sync startNo + val end:Int? // log sync endNo + if (((pumpWrappingCount * 10000 + pumpLastNum) - apsLastNum) > 10000) { + start = pumpLastNum + end = 10000 + } else if (pumpWrappingCount > apsWrappingCount && apsLastLogNum < 9999) { + start = apsLastLogNum + 1 + end = 10000 + } else if (pumpWrappingCount > apsWrappingCount && apsLastLogNum >= 9999) { + start = 0 + end = pumpLastNum + } else { + start = apsLastLogNum + 1 + end = pumpLastNum + } + + // pump log loop size + val pumpLogPageSize = 11 + val loopCount: Int = ceil (((end - start) / 11.0)).toInt() + + // log sync start! + if (loopCount > 0) { + diaconnG8Pump.isProgressPumpLogSync = true + + for (i in 0 until loopCount) { + val startLogNo: Int = start + i * pumpLogPageSize + val endLogNo: Int = startLogNo + min(end - startLogNo, pumpLogPageSize) + val msg = BigLogInquirePacket(injector, startLogNo, endLogNo, 100) + sendMessage(msg) + } + diaconnG8Pump.historyDoneReceived = true + while (!diaconnG8Pump.historyDoneReceived && bleCommonService.isConnected) { + SystemClock.sleep(100) + } + result.success(true) + diaconnG8Pump.lastConnection = System.currentTimeMillis() + } + return result + } + + fun setUserSettings(): PumpEnactResult { + val result = PumpEnactResult(injector) + + val msg: DiaconnG8Packet = when(diaconnG8Pump.setUserOptionType) { + DiaconnG8Pump.ALARM -> SoundSettingPacket(injector, diaconnG8Pump.beepAndAlarm, diaconnG8Pump.alarmIntesity) + DiaconnG8Pump.LCD -> DisplayTimeoutSettingPacket(injector, diaconnG8Pump.lcdOnTimeSec) + DiaconnG8Pump.LANG -> LanguageSettingPacket(injector, diaconnG8Pump.selectedLanguage) + DiaconnG8Pump.BOLUS_SPEED -> BolusSpeedSettingPacket(injector, diaconnG8Pump.bolusSpeed) + else -> null + } ?: return result.success(false) + + sendMessage(msg, 2000) + + + + // pump confirm + if(diaconnG8Pump.otpNumber == 0) { + aapsLogger.error(LTag.PUMPCOMM, "otp is not received yet") + result.success(false) + result.comment("펌프와 연결 상태를 확인해주세요.") + return result + } + + sendMessage(AppConfirmSettingPacket(injector, msg.msgType, diaconnG8Pump.otpNumber)) + + diaconnG8Pump.otpNumber = 0 + SystemClock.sleep(100) + return result.success(true) + } + + fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: EventOverviewBolusProgress.Treatment): Boolean { + if (!isConnected) return false + if (BolusProgressDialog.stopPressed) return false + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))) + + // bolus speed setting + val apsPrefBolusSpeed = sp.getInt("g8_bolusspeed", 5) + val isSpeedSyncToPump = sp.getBoolean("diaconn_g8_isbolusspeedsync", false) + + // aps speed check + if(!isSpeedSyncToPump) { + val msg = BolusSpeedSettingPacket(injector, apsPrefBolusSpeed) + sendMessage(msg, 2000) + sendMessage(AppConfirmSettingPacket(injector, msg.msgType, diaconnG8Pump.otpNumber)) + diaconnG8Pump.otpNumber = 0 + } + + // pump bolus speed inquire + sendMessage(BolusSpeedInquirePacket(injector), 1000) + diaconnG8Pump.bolusDone = false + diaconnG8Pump.bolusingTreatment = t + diaconnG8Pump.bolusAmountToBeDelivered = insulin + diaconnG8Pump.bolusStopped = false + diaconnG8Pump.bolusStopForced = false + diaconnG8Pump.bolusProgressLastTimeStamp = dateUtil.now() + val start = InjectionSnackSettingPacket(injector, (insulin * 100).toInt()) + if (carbs > 0) { + pumpSync.syncCarbsWithTimestamp(carbTime, carbs.toDouble(), null, PumpType.DIACONN_G8, diaconnG8Pump.serialNo.toString()) + } + val bolusStart = System.currentTimeMillis() + if (insulin > 0) { + if (!diaconnG8Pump.bolusStopped) { + sendMessage(start, 1000) + // otp process + if(!processConfirm(start.msgType)) return false + } else { + t.insulin = 0.0 + return false + } + } + val bolusingEvent = EventOverviewBolusProgress + bolusingEvent.t = t + bolusingEvent.percent = 99 + //diaconnG8Pump.bolusingTreatment = null + var speed = 12 + when (diaconnG8Pump.speed) { + 1 -> speed = 60 + 2 -> speed = 30 + 3 -> speed = 20 + 4 -> speed = 15 + 5 -> speed = 12 + 6 -> speed = 10 + 7 -> speed = 9 + 8 -> speed = 8 + } + + val bolusDurationInMSec = (insulin * speed * 1000).toLong() + val expectedEnd = bolusStart + bolusDurationInMSec + 7500L + val totalwaitTime = (expectedEnd - System.currentTimeMillis()) /1000 + while (!diaconnG8Pump.bolusDone) { + val waitTime = (expectedEnd - System.currentTimeMillis()) / 1000 + bolusingEvent.status = String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), if(waitTime < 0) 0 else waitTime) + var progressPecent = 0 + if(totalwaitTime > waitTime) { + progressPecent = ((totalwaitTime - waitTime) * 100 / totalwaitTime).toInt() + } + bolusingEvent.percent = min(progressPecent, 100) + rxBus.send(bolusingEvent) + SystemClock.sleep(200) + } + + // do not call loadHistory() directly, reconnection may be needed + commandQueue.loadEvents(object : Callback() { + override fun run() { + // reread bolus status + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) + sendMessage(InjectionSnackInquirePacket(injector), 1000) // last bolus + // 볼러스 결과 보고패킷에서 처리함. + bolusingEvent.percent = 100 + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))) + } + }) + return !start.failed + } + + fun bolusStop() { + val stop = InjectionCancelSettingPacket(injector, 0x07.toByte()) + + diaconnG8Pump.bolusStopForced = true + if (isConnected) { + sendMessage(stop,2000) + // otp process + if(!processConfirm(stop.msgType)) return + while (!diaconnG8Pump.bolusStopped) { + SystemClock.sleep(200) + } + } else { + diaconnG8Pump.bolusStopped = true + } + } + + fun tempBasal(absoluteRate: Double, durationInHours: Int): Boolean { + if (!isConnected) return false + if (diaconnG8Pump.isTempBasalInProgress) { + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio) + // tempbasal stop + sendMessage(msgPacket, 2000) + // otp process + if(!processConfirm(msgPacket.msgType)) return false + diaconnG8Pump.tempBasalStart= dateUtil.now() + } + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + val tbInjectRate = ((absoluteRate*100) + 1000).toInt() + val msgTBR = TempBasalSettingPacket(injector, 1, (durationInHours * 60) / 15, tbInjectRate) + sendMessage(msgTBR, 2000) + // otp process + if(!processConfirm(msgTBR.msgType)) return false + // pump tempbasal status inquire + sendMessage(TempBasalInquirePacket(injector)) + loadHistory() + val tbr = pumpSync.expectedPumpState().temporaryBasal + diaconnG8Pump.fromTemporaryBasal(tbr) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return msgTBR.success() + } + + fun highTempBasal(absoluteRate: Double): Boolean { + if (diaconnG8Pump.isTempBasalInProgress) { + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio) + // tempbasal stop + sendMessage(msgPacket, 2000) + // otp process + if(!processConfirm(msgPacket.msgType)) return false + diaconnG8Pump.tempBasalStart= dateUtil.now() + // SystemClock.sleep(500) + } + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + + + val tbTime = 2 // 2: 30min, 3:45min, 4:60min + var newAbsoluteRate = absoluteRate + if (absoluteRate < 0.0) newAbsoluteRate = 0.0 + if (absoluteRate > 6.0) newAbsoluteRate = 6.0 // pump Temp Max percent = 200 + + aapsLogger.debug(LTag.PUMPCOMM, "APS Temp basal start absoluteRate: $newAbsoluteRate duration 30 min") + val tbInjectRate = absoluteRate * 100 + 1000 + val msgTBR = TempBasalSettingPacket(injector, 1, tbTime, tbInjectRate.toInt()) + sendMessage(msgTBR, 2000) + // otp process + if(!processConfirm(msgTBR.msgType)) return false + sendMessage(TempBasalInquirePacket(injector)) + SystemClock.sleep(500) + loadHistory() + val tbr = pumpSync.expectedPumpState().temporaryBasal + diaconnG8Pump.fromTemporaryBasal(tbr) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return true + } + + fun tempBasalShortDuration(absoluteRate: Double, durationInMinutes: Int): Boolean { + if (durationInMinutes != 15 && durationInMinutes != 30) { + aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param") + return false + } + if (diaconnG8Pump.isTempBasalInProgress) { + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio) + // tempbasal stop + sendMessage(msgPacket, 2000) + // otp process + if(!processConfirm(msgPacket.msgType)) return false + SystemClock.sleep(500) + } + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) + val tbInjectRate = absoluteRate * 100 + 1000 + val msgTBR = TempBasalSettingPacket(injector, 1, 2, tbInjectRate.toInt()) + sendMessage(msgTBR, 2000) + // otp process + if(!processConfirm(msgTBR.msgType)) return false + sendMessage(TempBasalInquirePacket(injector)) + loadHistory() + val tbr = pumpSync.expectedPumpState().temporaryBasal + diaconnG8Pump.fromTemporaryBasal(tbr) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return msgTBR.success() + } + + fun tempBasalStop(): Boolean { + if (!isConnected) return false + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) + val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio) + // tempbasal stop + sendMessage(msgPacket, 2000) + // otp process + if(!processConfirm(msgPacket.msgType)) return false + SystemClock.sleep(500) + if(diaconnG8Pump.isTempBasalInProgress) { + sendMessage(TempBasalInquirePacket(injector), 2000) + } + loadHistory() + val tbr = pumpSync.expectedPumpState().temporaryBasal + diaconnG8Pump.fromTemporaryBasal(tbr) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return msgPacket.success() + } + + fun extendedBolus(insulin: Double, durationInMinutes: Int): Boolean { + if (!isConnected) return false + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))) + aapsLogger.error(LTag.PUMPCOMM, "insulin: $insulin durationInMinutes: $durationInMinutes") + + val msgExtended = InjectionExtendedBolusSettingPacket(injector, (insulin * 100).toInt(), durationInMinutes, dateUtil.now()) + sendMessage(msgExtended, 2000) + // otp process + if(!processConfirm(msgExtended.msgType)) return false + + loadHistory() + val eb = pumpSync.expectedPumpState().extendedBolus + diaconnG8Pump.fromExtendedBolus(eb) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return msgExtended.success() + } + + fun extendedBolusStop(): Boolean { + if (!isConnected) return false + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))) + val msgStop = InjectionCancelSettingPacket(injector, 0x08.toByte()) + sendMessage(msgStop, 2000) + // otp process + if(!processConfirm(msgStop.msgType)) return false + loadHistory() + val eb = pumpSync.expectedPumpState().extendedBolus + diaconnG8Pump.fromExtendedBolus(eb) + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return msgStop.success() + } + + fun updateBasalsInPump(profile: Profile): Boolean { + if (!isConnected) return false + rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))) + val basalList = diaconnG8Pump.buildDiaconnG8ProfileRecord(profile) + + val requestReqPacket1 = BasalSettingPacket( + injector, 1, 1, (basalList[0] * 100).toInt(), (basalList[1] * 100).toInt(), (basalList[2] * 100).toInt(), (basalList[3] * 100).toInt(), (basalList[4] * 100).toInt(), (basalList[5] * 100).toInt() + ) + val requestReqPacket2= BasalSettingPacket( + injector, 1, 2, (basalList[6] * 100).toInt(), (basalList[7] * 100).toInt(), (basalList[8] * 100).toInt(), (basalList[9] * 100).toInt(), (basalList[10] * 100).toInt(), (basalList[11] * 100).toInt() + ) + val requestReqPacket3= BasalSettingPacket( + injector, 1, 3, (basalList[12] * 100).toInt(), (basalList[13] * 100).toInt(), (basalList[14] * 100).toInt(), (basalList[15] * 100).toInt(), (basalList[16] * 100).toInt(), (basalList[17] * 100).toInt() + ) + val requestReqPacket4= BasalSettingPacket( + injector, 1, 4, (basalList[18] * 100).toInt(), (basalList[19] * 100).toInt(), (basalList[20] * 100).toInt(), (basalList[21] * 100).toInt(), (basalList[22] * 100).toInt(), (basalList[23] * 100).toInt() + ) + // setting basal pattern 1,2,3,4 + sendMessage(requestReqPacket1) + sendMessage(requestReqPacket2) + sendMessage(requestReqPacket3) + sendMessage(requestReqPacket4) + + // otp process + if(!processConfirm(0x0B)) return false + // pump saving time about 30 second + aapsLogger.debug(LTag.PUMPCOMM, "30 seconds Waiting!!") + SystemClock.sleep(30000) + + val msgPacket = InjectionBasalSettingPacket(injector, 1) + sendMessage(msgPacket, 2000) + // otp process + if(!processConfirm(msgPacket.msgType)) return false + readPumpStatus() + rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) + return requestReqPacket4.success() + } + + private fun pumpLogDefaultSetting() { + val apsWrappingCount = diaconnG8Pump.pumpWrappingCount + val apsLastLogNum = if(diaconnG8Pump.pumpLastLogNum - 1 < 0 ) 0 else diaconnG8Pump.pumpLastLogNum - 1 + sp.putInt(resourceHelper.gs(R.string.apslastLogNum), apsLastLogNum) + sp.putInt(resourceHelper.gs(R.string.apsWrappingCount), apsWrappingCount) + } + + private fun processConfirm(msgType:Byte) : Boolean { + // pump confirm + if(diaconnG8Pump.otpNumber == 0) { + aapsLogger.error(LTag.PUMPCOMM, "otp is not received yet") + + // Comments are made as dialogs are exposed twice each in the event of an error. + // Thread { + // val i = Intent(context, ErrorHelperActivity::class.java) + // i.putExtra("soundid", R.raw.boluserror) + // i.putExtra("status", resourceHelper.gs(R.string.diaconn_g8_errotpreceivedyet)) + // i.putExtra("title", resourceHelper.gs(R.string.pumperror)) + // i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + // context.startActivity(i) + // }.start() + + return false + } + sendMessage(AppConfirmSettingPacket(injector, msgType, diaconnG8Pump.otpNumber), 2000) + diaconnG8Pump.otpNumber = 0 + return true + } +} \ No newline at end of file diff --git a/diaconn/src/main/res/drawable/ic_diaconn_g8.xml b/diaconn/src/main/res/drawable/ic_diaconn_g8.xml new file mode 100644 index 0000000000..d98c6c2109 --- /dev/null +++ b/diaconn/src/main/res/drawable/ic_diaconn_g8.xml @@ -0,0 +1,6100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/diaconn/src/main/res/layout/diaconn_g8_blescanner_activity.xml b/diaconn/src/main/res/layout/diaconn_g8_blescanner_activity.xml new file mode 100644 index 0000000000..86b6406ee1 --- /dev/null +++ b/diaconn/src/main/res/layout/diaconn_g8_blescanner_activity.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + diff --git a/diaconn/src/main/res/layout/diaconn_g8_blescanner_item.xml b/diaconn/src/main/res/layout/diaconn_g8_blescanner_item.xml new file mode 100644 index 0000000000..9a39302163 --- /dev/null +++ b/diaconn/src/main/res/layout/diaconn_g8_blescanner_item.xml @@ -0,0 +1,27 @@ + + + + + + + \ No newline at end of file diff --git a/diaconn/src/main/res/layout/diaconn_g8_fragment.xml b/diaconn/src/main/res/layout/diaconn_g8_fragment.xml new file mode 100644 index 0000000000..43b11361ec --- /dev/null +++ b/diaconn/src/main/res/layout/diaconn_g8_fragment.xml @@ -0,0 +1,714 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +