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..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)
@@ -182,7 +185,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/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt
index 0065e19a96..1404dad118 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
@@ -58,7 +59,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/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 89ca553091..64cbcf3ab3 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
@@ -25,7 +26,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
@@ -42,13 +42,11 @@ 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.dash.OmnipodDashPumpPlugin
-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
@@ -150,17 +148,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(155)
- abstract fun bindOmnipodErosPumpPlugin(plugin: OmnipodErosPumpPlugin): PluginBase
+ @IntKey(150)
+ abstract fun bindMedtronicPumpPlugin(plugin: MedtronicPumpPlugin): PluginBase
@Binds
@PumpDriver
@@ -168,6 +160,12 @@ abstract class PluginsModule {
@IntKey(156)
abstract fun bindOmnipodDashPumpPlugin(plugin: OmnipodDashPumpPlugin): PluginBase
+ @Binds
+ @PumpDriver
+ @IntoMap
+ @IntKey(155)
+ abstract fun bindDiaconnG8Plugin(plugin: DiaconnG8Plugin): PluginBase
+
@Binds
@NotNSClient
@IntoMap
@@ -210,12 +208,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/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt
index f9cf203e5e..398eca586f 100644
--- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt
+++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt
@@ -191,7 +191,7 @@ class FillDialog : DialogFragmentWithDate() {
commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
}
}
})
diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt
index 8d55d861a6..12d14ef265 100644
--- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt
+++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt
@@ -224,7 +224,7 @@ class InsulinDialog : DialogFragmentWithDate() {
commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
}
}
})
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..493656f1cf 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,11 +320,11 @@ 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) {
- ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
}
}
})
@@ -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
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt
index 10df72c584..f5c02a69d4 100644
--- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt
+++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt
@@ -119,7 +119,7 @@ class TempBasalDialog : DialogFragmentWithDate() {
val callback: Callback = object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
}
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt
index a76863bce2..060eaff132 100644
--- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt
+++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt
@@ -174,7 +174,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(ctx, result.comment, resourceHelper.gs(R.string.treatmentdeliveryerror), R.raw.boluserror)
}
}
})
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/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt
index b2a13d8386..82a7713b5d 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
@@ -311,15 +330,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)
@@ -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
@@ -441,7 +459,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
@@ -613,7 +631,7 @@ open class LoopPlugin @Inject constructor(
commandQueue.tempBasalAbsolute(0.0, durationInMinutes, true, profile, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND, object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
}
}
})
@@ -621,7 +639,7 @@ open class LoopPlugin @Inject constructor(
commandQueue.tempBasalPercent(0, durationInMinutes, true, profile, PumpSync.TemporaryBasalType.EMULATED_PUMP_SUSPEND, object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
}
}
})
@@ -630,7 +648,7 @@ open class LoopPlugin @Inject constructor(
commandQueue.cancelExtended(object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.extendedbolusdeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.extendedbolusdeliveryerror), R.raw.boluserror)
}
}
})
@@ -648,7 +666,7 @@ open class LoopPlugin @Inject constructor(
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (!result.success) {
- ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), info.nightscout.androidaps.dana.R.raw.boluserror)
+ ErrorHelperActivity.runAlarm(context, result.comment, resourceHelper.gs(R.string.tempbasaldeliveryerror), R.raw.boluserror)
}
}
})
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..dce8c55206 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 "") +
@@ -135,7 +134,12 @@ class ConfigBuilderPlugin @Inject constructor(
// Ask when switching to physical pump plugin
fun switchAllowed(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
- if (changedPlugin.getType() == PluginType.PUMP && changedPlugin.name != resourceHelper.gs(R.string.virtualpump)) confirmPumpPluginActivation(changedPlugin, newState, activity, type) else performPluginSwitch(changedPlugin, newState, type)
+ if (changedPlugin.getType() == PluginType.PUMP && changedPlugin.name != resourceHelper.gs(R.string.virtualpump))
+ confirmPumpPluginActivation(changedPlugin, newState, activity, type)
+ else if (changedPlugin.getType() == PluginType.PUMP) {
+ performPluginSwitch(changedPlugin, newState, type)
+ pumpSync.connectNewPump()
+ } else performPluginSwitch(changedPlugin, newState, type)
}
private fun confirmPumpPluginActivation(changedPlugin: PluginBase, newState: Boolean, activity: FragmentActivity?, type: PluginType) {
@@ -185,7 +189,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/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt
index 26a478240a..3de63dbbd5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt
@@ -67,14 +67,15 @@ class ProfileFunctionImplementation @Inject constructor(
override fun getProfile(): Profile? =
getProfile(dateUtil.now())
+ @Synchronized
override fun getProfile(time: Long): Profile? {
val rounded = time - time % 1000
val cached = cache[rounded]
if (cached != null) {
-// aapsLogger.debug("XXXXXXXXXXXXXXX HIT getProfile for $time $rounded")
+// aapsLogger.debug("HIT getProfile for $time $rounded")
return cached
}
-// aapsLogger.debug("XXXXXXXXXXXXXXX getProfile called for $time")
+// aapsLogger.debug("getProfile called for $time")
val ps = repository.getEffectiveProfileSwitchActiveAt(time).blockingGet()
if (ps is ValueWrapper.Existing) {
val sealed = ProfileSealed.EPS(ps.value)
@@ -116,9 +117,27 @@ class ProfileFunctionImplementation @Inject constructor(
}
override fun createProfileSwitch(durationInMinutes: Int, percentage: Int, timeShiftInHours: Int) {
- val profileStore = activePlugin.activeProfileSource.profile ?: return
- val profileName = activePlugin.activeProfileSource.profile?.getDefaultProfileName()
- ?: return
- createProfileSwitch(profileStore, profileName, durationInMinutes, percentage, timeShiftInHours, dateUtil.now())
+ val profile = repository.getPermanentProfileSwitch(dateUtil.now())
+ ?: throw InvalidParameterSpecException("No active ProfileSwitch")
+ val ps = ProfileSwitch(
+ timestamp = dateUtil.now(),
+ basalBlocks = profile.basalBlocks,
+ isfBlocks = profile.isfBlocks,
+ icBlocks = profile.icBlocks,
+ targetBlocks = profile.targetBlocks,
+ glucoseUnit = profile.glucoseUnit,
+ profileName = profile.profileName,
+ timeshift = T.hours(timeShiftInHours.toLong()).msecs(),
+ percentage = percentage,
+ duration = T.mins(durationInMinutes.toLong()).msecs(),
+ insulinConfiguration = activePlugin.activeInsulin.insulinConfiguration
+ )
+ disposable += repository.runTransactionForResult(InsertOrUpdateProfileSwitch(ps))
+ .subscribe({ result ->
+ result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted ProfileSwitch $it") }
+ result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated ProfileSwitch $it") }
+ }, {
+ aapsLogger.error(LTag.DATABASE, "Error while saving ProfileSwitch", it)
+ })
}
}
\ No newline at end of file
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/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/general/maintenance/ImportExportPrefsImpl.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt
index bf83f2c5bc..908d801137 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt
@@ -363,7 +363,7 @@ class ImportExportPrefsImpl @Inject constructor(
override fun exportUserEntriesCsv(activity: FragmentActivity, singleEntries: Single>) {
val entries = singleEntries.blockingGet()
prefFileList.ensureExportDirExists()
- val newFile = prefFileList.newExportXmlFile()
+ val newFile = prefFileList.newExportCsvFile()
try {
classicPrefsFormat.saveCsv(newFile, entries)
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..a78575151c 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
@@ -16,11 +16,13 @@ import info.nightscout.androidaps.events.EventNewBG
import info.nightscout.androidaps.insight.database.InsightDatabase
import info.nightscout.androidaps.interfaces.DataSyncSelector
import info.nightscout.androidaps.interfaces.ImportExportPrefs
+import info.nightscout.androidaps.interfaces.IobCobCalculator
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity
+import info.nightscout.androidaps.plugins.general.overview.OverviewData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
@@ -44,6 +46,8 @@ class MaintenanceFragment : DaggerFragment() {
@Inject lateinit var uel: UserEntryLogger
@Inject lateinit var dataSyncSelector: DataSyncSelector
@Inject lateinit var pumpSync: PumpSync
+ @Inject lateinit var iobCobCalculator: IobCobCalculator
+ @Inject lateinit var overviewData: OverviewData
private val compositeDisposable = CompositeDisposable()
@@ -63,7 +67,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 ->
@@ -75,6 +81,9 @@ class MaintenanceFragment : DaggerFragment() {
insightDatabase.clearAllTables()
dataSyncSelector.resetToNextFullSync()
pumpSync.connectNewPump()
+ overviewData.reset()
+ iobCobCalculator.ads.reset()
+ iobCobCalculator.clearCache()
}
.subscribeOn(aapsSchedulers.io)
.observeOn(aapsSchedulers.main)
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..deb2d9e7e8 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
@@ -8,8 +8,8 @@ import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreference
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig
-import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.R
+import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
@@ -35,17 +35,19 @@ 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)
- .fragmentClass(MaintenanceFragment::class.java.name)
- .alwaysVisible(false)
- .alwaysEnabled(true)
- .pluginIcon(R.drawable.ic_maintenance)
- .pluginName(R.string.maintenance)
- .shortName(R.string.maintenance_shortname)
- .preferencesId(R.xml.pref_maintenance)
- .description(R.string.description_maintenance),
+) : PluginBase(
+ PluginDescription()
+ .mainType(PluginType.GENERAL)
+ .fragmentClass(MaintenanceFragment::class.java.name)
+ .alwaysVisible(false)
+ .alwaysEnabled(true)
+ .pluginIcon(R.drawable.ic_maintenance)
+ .pluginName(R.string.maintenance)
+ .shortName(R.string.maintenance_shortname)
+ .preferencesId(R.xml.pref_maintenance)
+ .description(R.string.description_maintenance),
aapsLogger, resourceHelper, injector
) {
@@ -53,11 +55,12 @@ 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.ensureTempDirExists()
val zipFile = File(zipDir, constructName())
aapsLogger.debug("zipFile: ${zipFile.absolutePath}")
val zip = zipLogs(zipFile, logs)
- val attachmentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", zip)
+ val attachmentUri =
+ FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", zip)
val emailIntent: Intent = this.sendMail(attachmentUri, recipient, "Log Export")
aapsLogger.debug("sending emailIntent")
context.startActivity(emailIntent)
@@ -65,14 +68,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) }
+ Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) }
var delFiles = listOf(*files)
- val amount = sp.getInt(R.string.key_logshipper_amount, 2)
+ 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 +83,7 @@ class MaintenancePlugin @Inject constructor(
file.delete()
}
}
- val exportDir = File(loggerUtils.logDirectory, "exports")
+ val exportDir = fileListProvider.ensureTempDirExists()
if (exportDir.exists()) {
val expFiles = exportDir.listFiles()
for (file in expFiles) {
@@ -192,7 +195,12 @@ class MaintenancePlugin @Inject constructor(
*
* @return
*/
- private fun sendMail(attachmentUri: Uri, recipient: String, subject: String, body: String): Intent {
+ private fun sendMail(
+ attachmentUri: Uri,
+ recipient: String,
+ subject: String,
+ body: String
+ ): Intent {
aapsLogger.debug("sending email to $recipient with subject $subject")
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "text/plain"
@@ -207,8 +215,9 @@ class MaintenancePlugin @Inject constructor(
override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) {
super.preprocessPreferences(preferenceFragment)
- val encryptSwitch = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_maintenance_encrypt_exported_prefs)) as SwitchPreference?
- ?: return
+ val encryptSwitch =
+ preferenceFragment.findPreference(resourceHelper.gs(R.string.key_maintenance_encrypt_exported_prefs)) as SwitchPreference?
+ ?: return
encryptSwitch.isVisible = buildHelper.isEngineeringMode()
encryptSwitch.isEnabled = buildHelper.isEngineeringMode()
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt
index c5a41f057a..a164ab6ab9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/DataSyncSelectorImplementation.kt
@@ -360,10 +360,10 @@ class DataSyncSelectorImplementation @Inject constructor(
when {
// without nsId = create new
te.first.interfaceIDs.nightscoutId == null ->
- nsClientPlugin.nsClientService?.dbAdd("treatments", te.first.toJson(true), DataSyncSelector.PairTherapyEvent(te.first, te.second), "$startId/$lastDbId")
+ nsClientPlugin.nsClientService?.dbAdd("treatments", te.first.toJson(true, dateUtil), DataSyncSelector.PairTherapyEvent(te.first, te.second), "$startId/$lastDbId")
// nsId = update
te.first.interfaceIDs.nightscoutId != null ->
- nsClientPlugin.nsClientService?.dbUpdate("treatments", te.first.interfaceIDs.nightscoutId, te.first.toJson(false), DataSyncSelector.PairTherapyEvent(te.first, te.second), "$startId/$lastDbId")
+ nsClientPlugin.nsClientService?.dbUpdate("treatments", te.first.interfaceIDs.nightscoutId, te.first.toJson(false, dateUtil), DataSyncSelector.PairTherapyEvent(te.first, te.second), "$startId/$lastDbId")
}
return true
}
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 ->
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..dd31516ac3 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
@@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.nsclient.services
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
+import android.content.pm.ResolveInfo
import android.os.*
import androidx.work.OneTimeWorkRequest
import com.google.common.base.Charsets
@@ -16,7 +17,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 +71,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 +198,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"
@@ -488,7 +487,7 @@ class NSClientService : DaggerService() {
val intent = Intent(Intents.ACTION_NEW_PROFILE)
intent.putExtras(bundle)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
- sendBroadcast(intent)
+ broadcast(intent)
}
}
}
@@ -516,7 +515,7 @@ class NSClientService : DaggerService() {
val intent = Intent(Intents.ACTION_REMOVED_TREATMENT)
intent.putExtras(bundle)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
- sendBroadcast(intent)
+ broadcast(intent)
}
}
if (addedOrUpdatedTreatments.length() > 0) {
@@ -533,7 +532,7 @@ class NSClientService : DaggerService() {
val intent = Intent(Intents.ACTION_CHANGED_TREATMENT)
intent.putExtras(bundle)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
- sendBroadcast(intent)
+ broadcast(intent)
}
}
}
@@ -581,7 +580,7 @@ class NSClientService : DaggerService() {
val intent = Intent(Intents.ACTION_NEW_SGV)
intent.putExtras(bundle)
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
- sendBroadcast(intent)
+ broadcast(intent)
}
}
}
@@ -721,6 +720,16 @@ class NSClientService : DaggerService() {
return ret
}
+ private fun broadcast(intent: Intent) {
+ val receivers: List = packageManager.queryBroadcastReceivers(intent, 0)
+ for (resolveInfo in receivers)
+ resolveInfo.activityInfo.packageName?.let {
+ intent.setPackage(it)
+ sendBroadcast(intent)
+ aapsLogger.debug(LTag.CORE, "Sending broadcast " + intent.action + " to: " + it)
+ }
+ }
+
init {
if (handler == null) {
val handlerThread = HandlerThread(NSClientService::class.java.simpleName + "Handler")
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/OverviewData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt
index 415ae58299..bf9803796d 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
@@ -71,6 +71,44 @@ class OverviewData @Inject constructor(
var fromTime: Long = 0
var endTime: Long = 0
+ fun reset() {
+ profile = null
+ profileName = null
+ profileNameWithRemainingTime = null
+ calcProgress = ""
+ lastBg = null
+ temporaryBasal = null
+ extendedBolus = null
+ bolusIob = null
+ basalIob = null
+ cobInfo = null
+ lastCarbsTime = 0L
+ temporaryTarget = null
+ lastAutosensData = null
+ bgReadingsArray = ArrayList()
+ bucketedGraphSeries = PointsWithLabelGraphSeries()
+ bgReadingGraphSeries = PointsWithLabelGraphSeries()
+ predictionsGraphSeries = PointsWithLabelGraphSeries()
+ baseBasalGraphSeries = LineGraphSeries()
+ tempBasalGraphSeries = LineGraphSeries()
+ basalLineGraphSeries = LineGraphSeries()
+ absoluteBasalGraphSeries = LineGraphSeries()
+ activitySeries = FixedLineGraphSeries()
+ activityPredictionSeries = FixedLineGraphSeries()
+ iobSeries = FixedLineGraphSeries()
+ absIobSeries = FixedLineGraphSeries()
+ iobPredictions1Series = PointsWithLabelGraphSeries()
+ iobPredictions2Series = PointsWithLabelGraphSeries()
+ minusBgiSeries = FixedLineGraphSeries()
+ minusBgiHistSeries = FixedLineGraphSeries()
+ cobSeries = FixedLineGraphSeries()
+ cobMinFailOverSeries = PointsWithLabelGraphSeries()
+ deviationsSeries = BarGraphSeries()
+ ratioSeries = LineGraphSeries()
+ dsMaxSeries = LineGraphSeries()
+ dsMinSeries = LineGraphSeries()
+ }
+
fun initRange() {
rangeToDisplay = sp.getInt(R.string.key_rangetodisplay, 6)
@@ -187,7 +225,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()
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/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/plugins/general/smsCommunicator/AuthRequest.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt
index 7d19bed23d..a8e22abdf2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt
@@ -1,13 +1,16 @@
package info.nightscout.androidaps.plugins.general.smsCommunicator
+import android.os.SystemClock
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
+import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
-import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult
+import info.nightscout.androidaps.utils.DateUtil
+import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
@@ -23,6 +26,7 @@ class AuthRequest internal constructor(
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var otp: OneTimePassword
@Inject lateinit var dateUtil: DateUtil
+ @Inject lateinit var commandQueue: CommandQueueProvider
private var date = 0L
private var processed = false
@@ -49,6 +53,19 @@ class AuthRequest internal constructor(
}
if (dateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
processed = true
+ if (action.pumpCommand) {
+ val start = dateUtil.now()
+ //wait for empty queue
+ while (start + T.mins(3).msecs() > dateUtil.now()) {
+ if (commandQueue.size() == 0) break
+ SystemClock.sleep(100)
+ }
+ if (commandQueue.size() != 0) {
+ aapsLogger.debug(LTag.SMS, "Command timed out: " + requester.text)
+ smsCommunicatorPlugin.sendSMS(Sms(requester.phoneNumber, resourceHelper.gs(R.string.sms_timeout_while_wating)))
+ return
+ }
+ }
aapsLogger.debug(LTag.SMS, "Processing confirmed SMS: " + requester.text)
action.run()
return
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt
index 98c892d918..a38d9858c1 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt
@@ -1,37 +1,37 @@
package info.nightscout.androidaps.plugins.general.smsCommunicator
-abstract class SmsAction : Runnable {
+abstract class SmsAction(val pumpCommand: Boolean) : Runnable {
+
var aDouble: Double? = null
var anInteger: Int? = null
var secondInteger: Int? = null
var secondLong: Long? = null
var aString: String? = null
- internal constructor()
- internal constructor(aDouble: Double) {
+ internal constructor(pumpCommand: Boolean, aDouble: Double) : this(pumpCommand) {
this.aDouble = aDouble
}
- internal constructor(aDouble: Double, secondInteger: Int) {
+ internal constructor(pumpCommand: Boolean, aDouble: Double, secondInteger: Int) : this(pumpCommand) {
this.aDouble = aDouble
this.secondInteger = secondInteger
}
- internal constructor(aString: String, secondInteger: Int) {
+ internal constructor(pumpCommand: Boolean, aString: String, secondInteger: Int) : this(pumpCommand) {
this.aString = aString
this.secondInteger = secondInteger
}
- internal constructor(anInteger: Int) {
+ internal constructor(pumpCommand: Boolean, anInteger: Int) : this(pumpCommand) {
this.anInteger = anInteger
}
- internal constructor(anInteger: Int, secondInteger: Int) {
+ internal constructor(pumpCommand: Boolean, anInteger: Int, secondInteger: Int) : this(pumpCommand) {
this.anInteger = anInteger
this.secondInteger = secondInteger
}
- internal constructor(anInteger: Int, secondLong: Long) {
+ internal constructor(pumpCommand: Boolean, anInteger: Int, secondLong: Long) : this(pumpCommand) {
this.anInteger = anInteger
this.secondLong = secondLong
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt
index e8ecaf6238..ac70ef612f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt
@@ -94,8 +94,8 @@ class SmsCommunicatorPlugin @Inject constructor(
private val disposable = CompositeDisposable()
var allowedNumbers: MutableList = ArrayList()
- var messageToConfirm: AuthRequest? = null
- var lastRemoteBolusTime: Long = 0
+ @Volatile var messageToConfirm: AuthRequest? = null
+ @Volatile var lastRemoteBolusTime: Long = 0
var messages = ArrayList()
val commands = mapOf(
@@ -278,6 +278,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
"BOLUS" ->
if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed)))
+ else if (commandQueue.bolusInQueue()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_another_bolus_in_queue)))
else if (divided.size == 2 && dateUtil.now() - lastRemoteBolusTime < minDistance) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotebolusnotallowed)))
else if (divided.size == 2 && pump.isSuspended()) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.pumpsuspended)))
else if (divided.size == 2 || divided.size == 3) processBOLUS(divided, receivedSms)
@@ -303,9 +304,13 @@ class SmsCommunicatorPlugin @Inject constructor(
else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
else ->
if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) {
- messageToConfirm?.action(divided[0])
+ val execute = messageToConfirm
messageToConfirm = null
- } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_unknowncommand)))
+ execute?.action(divided[0])
+ } else {
+ messageToConfirm = null
+ sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_unknowncommand)))
+ }
}
}
rxBus.send(EventSmsCommunicatorUpdateGui())
@@ -344,7 +349,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopdisablereplywithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
uel.log(Action.LOOP_DISABLED, Sources.SMS)
loop.enabled = false
@@ -368,10 +373,10 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopenablereplywithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
uel.log(Action.LOOP_ENABLED, Sources.SMS)
- loop.enabled= true
+ loop.enabled = true
sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled)))
rxBus.send(EventRefreshOverview("SMS_LOOP_START"))
}
@@ -395,7 +400,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopresumereplywithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.RESUME, Sources.SMS)
disposable += repository.runTransactionForResult(CancelCurrentOfflineEventIfAnyTransaction(dateUtil.now()))
@@ -432,7 +437,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(duration) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, duration) {
override fun run() {
uel.log(Action.SUSPEND, Sources.SMS)
commandQueue.cancelTempBasal(true, object : Callback() {
@@ -478,7 +483,7 @@ class SmsCommunicatorPlugin @Inject constructor(
@kotlin.ExperimentalStdlibApi
private fun processHELP(divided: Array, receivedSms: Sms) {
when {
- divided.size == 1 -> {
+ divided.size == 1 -> {
sendSMS(Sms(receivedSms.phoneNumber, commands.keys.toString().replace("[", "").replace("]", "")))
receivedSms.processed = true
}
@@ -490,7 +495,7 @@ class SmsCommunicatorPlugin @Inject constructor(
}
}
- else -> sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
+ else -> sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat)))
}
}
@@ -513,7 +518,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpconnectwithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.RECONNECT, Sources.SMS)
commandQueue.cancelTempBasal(true, object : Callback() {
@@ -546,7 +551,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpdisconnectwithcode), duration, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
uel.log(Action.DISCONNECT, Sources.SMS)
val profile = profileFunction.getProfile() ?: return
@@ -601,7 +606,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_profilereplywithcode), list[pIndex - 1], percentage, passCode)
receivedSms.processed = true
val finalPercentage = percentage
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(list[pIndex - 1] as String, finalPercentage) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, list[pIndex - 1] as String, finalPercentage) {
override fun run() {
profileFunction.createProfileSwitch(store, list[pIndex - 1] as String, 0, finalPercentage, 0, dateUtil.now())
val replyText = resourceHelper.gs(R.string.profileswitchcreated)
@@ -622,7 +627,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalstopreplywithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
@@ -657,7 +662,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(tempBasalPct, duration) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasalPct, duration) {
override fun run() {
commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() {
@@ -701,7 +706,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(tempBasal, duration) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, tempBasal, duration) {
override fun run() {
commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, PumpSync.TemporaryBasalType.NORMAL, object : Callback() {
override fun run() {
@@ -739,7 +744,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true) {
override fun run() {
commandQueue.cancelExtended(object : Callback() {
override fun run() {
@@ -769,7 +774,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(extended, duration) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, extended, duration) {
override fun run() {
commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() {
override fun run() {
@@ -815,7 +820,7 @@ class SmsCommunicatorPlugin @Inject constructor(
else
String.format(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(bolus) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, bolus) {
override fun run() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.insulin = aDouble()
@@ -917,7 +922,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode), grams, dateUtil.timeString(time), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(grams, time) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = true, grams, time) {
override fun run() {
val detailedBolusInfo = DetailedBolusInfo()
detailedBolusInfo.carbs = anInteger().toDouble()
@@ -954,7 +959,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetwithcode), divided[1].uppercase(Locale.getDefault()), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
val units = profileFunction.getUnits()
var keyDuration = 0
@@ -1016,7 +1021,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetcancel), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(dateUtil.now()))
.subscribe({ result ->
@@ -1041,7 +1046,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_stopsmswithcode), passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false) {
override fun run() {
sp.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)
val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_stoppedsms))
@@ -1059,7 +1064,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val passCode = generatePassCode()
val reply = String.format(resourceHelper.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode)
receivedSms.processed = true
- messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(cal) {
+ messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(pumpCommand = false, cal) {
override fun run() {
val result = xdripCalibrations.sendIntent(aDouble!!)
val replyText =
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt
index 6a0d5bb2de..eb834614c4 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt
@@ -130,7 +130,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
runCalculation(reason, System.currentTimeMillis(), bgDataReload = false, limitDataToOldestAvailable = true, cause = event)
}
- fun clearCache() {
+ override fun clearCache() {
synchronized(dataLock) {
aapsLogger.debug(LTag.AUTOSENS, "Clearing cached data.")
iobTable = LongSparseArray()
@@ -482,7 +482,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
for (pos in extendedBoluses.indices) {
val e = extendedBoluses[pos]
if (e.timestamp > toTime) continue
- if (e.end > now) e.end = now
+ if (e.end > now) e.duration = now - e.timestamp
val profile = profileFunction.getProfile(e.timestamp) ?: return total
val calc = e.iobCalc(toTime, profile, activePlugin.activeInsulin)
total.plus(calc)
@@ -551,7 +551,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val t = temporaryBasals[pos]
if (t.timestamp > toTime) continue
val profile = profileFunction.getProfile(t.timestamp) ?: continue
- if (t.end > now) t.end = now
+ if (t.end > now) t.duration = now - t.timestamp
val calc = t.iobCalc(toTime, profile, activePlugin.activeInsulin)
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basalIob);
total.plus(calc)
@@ -563,7 +563,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val e = extendedBoluses[pos]
if (e.timestamp > toTime) continue
val profile = profileFunction.getProfile(e.timestamp) ?: continue
- if (e.end > now) e.end = now
+ if (e.end > now) e.duration = now - e.timestamp
val calc = e.iobCalc(toTime, profile, activePlugin.activeInsulin)
totalExt.plus(calc)
}
@@ -586,7 +586,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val t = temporaryBasals[pos]
if (t.timestamp > toTime) continue
val profile = profileFunction.getProfile(t.timestamp) ?: continue
- if (t.end > now) t.end = now
+ if (t.end > now) t.duration = now - t.timestamp
val calc = t.iobCalc(toTime, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget, activePlugin.activeInsulin)
//log.debug("BasalIOB " + new Date(time) + " >>> " + calc.basalIob);
total.plus(calc)
@@ -598,7 +598,7 @@ open class IobCobCalculatorPlugin @Inject constructor(
val e = extendedBoluses[pos]
if (e.timestamp > toTime) continue
val profile = profileFunction.getProfile(e.timestamp) ?: continue
- if (e.end > now) e.end = now
+ if (e.end > now) e.duration = now - e.timestamp
val calc = e.iobCalc(toTime, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget, activePlugin.activeInsulin)
totalExt.plus(calc)
}
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..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
@@ -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
@@ -127,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/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/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt
index cdaba94dc6..2ade4058f4 100644
--- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt
+++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt
@@ -68,12 +68,12 @@ open class CommandQueue @Inject constructor(
private val disposable = CompositeDisposable()
private val queue = LinkedList()
- private var thread: QueueThread? = null
+ @Volatile private var thread: QueueThread? = null
- var performing: Command? = null
+ @Volatile var performing: Command? = null
init {
- disposable.add(rxBus
+ disposable += rxBus
.toObservable(EventProfileSwitchChanged::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
@@ -109,8 +109,6 @@ open class CommandQueue @Inject constructor(
})
}
}, fabricPrivacy::logException)
- )
-
}
private fun executingNowError(): PumpEnactResult =
@@ -197,16 +195,17 @@ open class CommandQueue @Inject constructor(
aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue")
val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, aapsSchedulers, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, dateUtil, repository, fabricPrivacy)
tempCommandQueue.readStatus(reason, callback)
+ tempCommandQueue.disposable.clear()
}
@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 +242,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/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/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/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/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/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/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/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-af-rZA/strings.xml b/app/src/main/res/values-af-rZA/strings.xml
index 7fdd0bc9b8..255884713c 100644
--- a/app/src/main/res/values-af-rZA/strings.xml
+++ b/app/src/main/res/values-af-rZA/strings.xml
@@ -75,8 +75,6 @@
Careportal
Pomp
Watter pomp wil jy gebruik met AndroidAPS?
- Behandelings
- Watter plugin moet gebruik word vir behandeling hantering?
Profiel
Watter profiel moet AndroidAPS gebruik?
APS
diff --git a/app/src/main/res/values-bg-rBG/strings.xml b/app/src/main/res/values-bg-rBG/strings.xml
index e7e28af80c..4cc954ceb3 100644
--- a/app/src/main/res/values-bg-rBG/strings.xml
+++ b/app/src/main/res/values-bg-rBG/strings.xml
@@ -81,8 +81,6 @@
Careportal
Помпа
Каква помпа използвате с AndroidAPS?
- Лечения
- Коя приставка да използваме за леченията?
Профил
Кой тип профил да използва AndroidAPS?
Алгоритъм за APS
diff --git a/app/src/main/res/values-cs-rCZ/strings.xml b/app/src/main/res/values-cs-rCZ/strings.xml
index da4afe91e2..7ad7205bc0 100644
--- a/app/src/main/res/values-cs-rCZ/strings.xml
+++ b/app/src/main/res/values-cs-rCZ/strings.xml
@@ -81,8 +81,6 @@
Péče
Pumpa
Jakou pumpu chcete používat s AndroidAPS?
- Ošetření
- Jaký plugin chcete používat pro ukládání informací?
Profil
Jaký profil má AndroidAPS používat?
APS
@@ -911,6 +909,8 @@
Přijmout dočasné cíle zadané prostřednictvím NS nebo NSClienta
Přijímat přepnutí profilu
Přijmout přepnutí profilu zadané prostřednictvím NS nebo NSClienta
+ Přijímat události APS offline
+ Přijmout APS offline události zadané prostřednictvím NS nebo NSClienta
Přijímat inzulín
Přijmout inzulín vložený přes NS nebo NSClient (není dodán, pouze započítán do IOB)
Přijímat sacharidy
@@ -919,4 +919,6 @@
Přijmout léčebné události (výměna setu, inzulínu, baterie atd.) zadané prostřednictvím NS nebo NSClienta
Přijímat/doplňovat glykémie
Přijmout CGM data z NS
+ Vypršel časový limit při čekání na dokončení předchozí komunikace s pumpou
+ Ve frontě je další bolus. Zkuste to znovu později.
diff --git a/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/values-de-rDE/strings.xml
index 86ba955765..343b658687 100644
--- a/app/src/main/res/values-de-rDE/strings.xml
+++ b/app/src/main/res/values-de-rDE/strings.xml
@@ -81,8 +81,6 @@
Careportal
Pumpe
Welche Pumpe möchtest Du mit AndroidAPS nutzen?
- Behandlungen
- Welches Plugin soll zum Verarbeiten von Behandlungen genutzt werden?
Profil
Welches Profil soll AndroidAPS nutzen?
APS
@@ -918,4 +916,6 @@ Unerwartetes Verhalten.
Ereignisse (Kanülen-, Ampullen-, Batteriewechsel etc.) akzeptieren, die in NS oder NSClient eingegeben wurden
Historische CGM Daten ergänzen
CGM Daten von NS akzeptieren
+ Zeitüberschreitung beim Warten auf das Ende der vorherigen Kommunikation mit der Pumpe
+ In der Warteschlange befindet sich ein weiterer Bolus. Bitte später erneut versuchen.
diff --git a/app/src/main/res/values-el-rGR/strings.xml b/app/src/main/res/values-el-rGR/strings.xml
index 6917843c6d..3969bec2de 100644
--- a/app/src/main/res/values-el-rGR/strings.xml
+++ b/app/src/main/res/values-el-rGR/strings.xml
@@ -77,8 +77,6 @@
Φροντίδα
Αντλία
Ποια αντλία θα θέλατε να χρησιμοποιήσετε με το AndroidAPS;
- Θεραπείες
- Ποια προσθήκη πρέπει να χρησιμοποιηθεί για το χειρισμό της θεραπείας;
Προφίλ
Ποιο προφίλ πρέπει να χρησιμοποιήσει το AndroidAPS;
APS
diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml
index 068c0dd9a3..68f73bddbd 100644
--- a/app/src/main/res/values-es-rES/strings.xml
+++ b/app/src/main/res/values-es-rES/strings.xml
@@ -81,8 +81,6 @@
Portal de Tratamientos
Bomba
¿Qué bomba quieres utilizar con AndroidAPS?
- Tratamientos
- ¿Que complemento quieres usar para el manejo del tratamiento?
Perfil
¿Qué perfil debe usar AndroidAPS?
APS
diff --git a/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml
index f35d33e14d..8d09db340b 100644
--- a/app/src/main/res/values-fr-rFR/strings.xml
+++ b/app/src/main/res/values-fr-rFR/strings.xml
@@ -81,8 +81,6 @@
Careportal
Pompe
Quelle pompe souhaitez-vous utiliser avec AndroidAPS ?
- Traitements
- Quel plugin doit être utilisé pour la gestion des traitements ?
Profil
Quel profil doit utiliser AndroidAPS ?
APS
@@ -96,7 +94,7 @@
APS
Après traitement des restrictions
Basal temporaire défini par la pompe
- Pas d\'APS séléctionné ou pas de résultat fourni
+ Pas d\'APS sélectionné ou pas de résultat fourni
Sécurité
Plugin désactivé
Violation des restrictions
@@ -732,7 +730,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
!!!!! Absorption lente des glucides détectée : %2$d%% du temps. Vérifiez de nouveau votre calcul. Les GA (Glucides Actifs) peuvent être surestimés et alors plus d\'insuline pourrait être délivré !!!!!]]>
Injecter cette partie de Bolus calculée par l’assistant [%]
L\'assistant Bolus effectue le calcul mais seulement cette partie de l\'insuline calculée est délivrée. Utile avec l\'algorithme SMB.
- Report alarme
+ Masquer
Augmentation de la valeur du débit Basal max parce que ce paramètre est inférieur au débit Basal max de votre profil
Message invalide
%1$s SI: %2$.1f
@@ -912,6 +910,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Accepter les cibles temporaires entrées via NS ou NSClient
Recevoir les changements de profil
Accepter les changements de profil entrés via NS ou NSClient
+ Recevoir les événements APS hors ligne
+ Accepter les événements APS hors ligne entrés via NS ou NSClient
Recevoir l\'insuline
Acceptez l\'insuline entrée via NS ou NSClient (elle n\'est pas injectée, uniquement pour le calcul pour IA)
Recevoir les glucides
@@ -920,4 +920,6 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Accepter les événements de thérapie (canule, insuline, changement de batterie, etc.) entrés via NS ou NSClient
Recevoir/remplir les anciennes données MGC
Accepter les données MGC de NS
+ Délai d\'attente pour finir la communication précédente avec la pompe
+ Un autre bolus est en file d\'attente. Réessayez plus tard.
diff --git a/app/src/main/res/values-ga-rIE/strings.xml b/app/src/main/res/values-ga-rIE/strings.xml
index 755334e67f..ed0ea2a53c 100644
--- a/app/src/main/res/values-ga-rIE/strings.xml
+++ b/app/src/main/res/values-ga-rIE/strings.xml
@@ -35,7 +35,6 @@
Deilte:
Cóireálacha
Caidéil
- Cóireálacha
Próifíl
APS
Ginearálta
diff --git a/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/values-it-rIT/strings.xml
index dae339b46c..c2e5b91a3e 100644
--- a/app/src/main/res/values-it-rIT/strings.xml
+++ b/app/src/main/res/values-it-rIT/strings.xml
@@ -81,8 +81,6 @@
Portale
Micro
Quale microinfusore desideri usare con AndroidAPS?
- Trattamenti
- Quale plugin dovrebbe essere usato per la gestione del trattamento?
Profilo
Quale profilo AndroidAPS dovrebbe usare?
APS
@@ -778,6 +776,7 @@
BG
Strumenti
Mostra calcolo
+ Mostra rimossi
Cancellare la coda? Tutti i dati in coda andranno persi!
L\'uso della funzione bolo esteso interromperà la modalità loop chiuso per il tempo di esecuzione del bolo esteso. Lo vuoi davvero?
Loop chiuso disabilitato a causa dell\'esecuzione di un bolo esteso
@@ -899,9 +898,27 @@
Valore max basale (profilo)
Valore basale corrente
Valore rapporto CHO (profilo)
+ Sincronizzazione completa
+ Caricamento
+ Sincronizzazione
+ Profili, boli, CHO, basali temporanee vengono caricati su NS
+ Carica dati su NS
+ Ricevi \"store\" profilo
+ Sincronizza i profili da NS al profilo locale
Ricevi target temporanei
+ Accetta target temporanei inseriti tramite NS o NSClient
Ricevi cambi profilo
+ Accetta cambi profilo inseriti tramite NS o NSClient
+ Ricevi eventi APS offline
+ Accetta eventi APS offline inseriti tramite NS o NSClient
Ricevi insulina
+ Accetta insulina inserita tramite NS o NSClient (non viene erogata, solo calcolata per IOB)
Ricevi CHO
+ Accetta CHO inseriti tramite NS o NSClient
+ Ricevi eventi terapia
+ Accetta eventi terapia (cambio cannula, insulina, batteria, ecc.) inseriti tramite NS o NSClient
+ Ricevi/riempi dati CGM
Accetta dati CGM da NS
+ Timeout nell\'attesa della fine della precedente comunicazione col micro.
+ C\'è un altro bolo in coda. Riprova più tardi.
diff --git a/app/src/main/res/values-iw-rIL/objectives.xml b/app/src/main/res/values-iw-rIL/objectives.xml
index 7ebba972a8..8cdc440a4e 100644
--- a/app/src/main/res/values-iw-rIL/objectives.xml
+++ b/app/src/main/res/values-iw-rIL/objectives.xml
@@ -1,7 +1,7 @@
התחל
- אמת
+ סיום
%1$d. משימה
מטרה %1$d לא החלה
משימה %1$d לא בוצעה במלואה
diff --git a/app/src/main/res/values-iw-rIL/strings.xml b/app/src/main/res/values-iw-rIL/strings.xml
index 63ac905f46..ee5889d917 100644
--- a/app/src/main/res/values-iw-rIL/strings.xml
+++ b/app/src/main/res/values-iw-rIL/strings.xml
@@ -81,8 +81,6 @@
פורטל טיפולים
משאבה
עם איזו משאבה אתם מעוניינים להשתמש ב-AndroidAPS?
- טיפולים
- איזה תוסף ישמש לתפעול הטיפולים?
פרופיל
באיזה פרופיל על AndroidAPS להשתמש?
APS
@@ -911,6 +909,8 @@
קבלת ערכי מטרה זמניים שהוגדרו בנייטסקאוט או ב-NSClient
קבלת החלפות פרופיל
קבלת החלפות פרופיל שהוגדרו בנייטסקאוט או ב-NSClient
+ אחזר אירועים לא מקוונים
+ קבל אירועים לא מקוונים שנרשמו דרך נייטסקאוט או NSClient
קבלת אינסולין
קבלת אינסולין שהוזן באמצעות נייטסקאוט או NSClient (הוא לא מוזרק, רק מחושב רק כאינסולין פעיל)
קבלת פחמימות
@@ -919,4 +919,6 @@
קבלת אירועי טיפול (צינורית, אינסולין, החלפת סוללה) שצוינו באמצעות נייטסקאוט או NSClient
קבלת\\טעינת נתוני סנסור
קבלת נתוני סנסור מנייטסקאוט
+ בהמתנה עד לסיום תקשורת קודמת עם המשאבה
+ ישנו בולוס נוסף בתור. נסו שוב מאוחר יותר.
diff --git a/app/src/main/res/values-ko-rKR/exam.xml b/app/src/main/res/values-ko-rKR/exam.xml
index a6f6b29bfe..bbd1b8fbb6 100644
--- a/app/src/main/res/values-ko-rKR/exam.xml
+++ b/app/src/main/res/values-ko-rKR/exam.xml
@@ -1,54 +1,215 @@
DIA에 대하여 올바른 것은?
+ 활성 인슐린 지속 시간 (DIA)
+ 프로파일에 DIA 값을 입력해야 합니다.
+ 허용되는 최소값은 5시간입니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Configuration/Config-Builder.html?#insulin
+ AndroidAPS를 사용하기 전에 펌프에서 사용했던 DIA 값이 잘 작동하여 만족했다면, looping을 시작하기 전에 이 값을 변경할 필요는 없습니다.
+ 적절한 DIA 값을 스스로 찾아야 합니다.
+ 저혈당 임시 목표
+ 저혈당 임시 목표를 설정하는 가장 중요한 이유는 무엇인가요?
+ 잘못된 basal 양 설정으로 인한 저혈당을 수정하기 위함.
+ 저혈당에 대한 처치로 빠르게 작용하는 탄수화물을 섭취하여 혈당 상승이 있을 때 AndoridAPS가 이를 과수정하는 것을 방지하기 위함.
+ 운동으로 인한 저혈당을 교정하기 위함.
+ 0% 임시 basal이 이미 적용되고 있는 상황에서 혈당이 낮아지는 것을 방지하기 위함.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/temptarget.html
어떤 프로파일이 오프라인에서 설정할 수 있습니까?
주제: 오프라인 프로파일
NS 프로파일이 사용될 수 있지만, 오프라인 상에서 설정할 수는 없습니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Configuration/Config-Builder.html#profile
+ AndroidAPS에서 \"펌프 연결 해제\"를 적용하는 이유들
펌프 일시중지할땐 무엇을 해야합니까?
+ 펌프가 물리적으로 연결되어 있지 않을 때에는 인슐린이 주입되지 않으므로 이 기능이 필요하지 않습니다.
+ 이 기능은 펌프가 물리적으로 떨어져 있는 동안에 주입되지 않은 인슐린을 AndroidAPS가 계산하지 않도록 합니다.
+ 펌프가 연결된 채로 있다면 이 기능은 인슐린 주입을 멈추지 않습니다.
+ 이 기능은 AndroidAPS를 open loop 모드로 전환합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Getting-Started/FAQ.html#other-settings
+ AndroidAPS 설정들
+ AndroidAPS 설정들
+ 설정을 백업하는 가장 좋은 방법은 무엇인가요?
+ 적용된 설정을 따로 기록해둔다면 설정값을 \"내보내기\" 하지 않아도 됩니다.
+ 목표를 보두 수행한 뒤 설정값을 \"내보내기\" 합니다.
+ 설정이 바뀐 부분이 있다면 설정값을 \"내보내기\" 합니다.
+ 초기 구성을 마치고, 개별 설정을 입력한 뒤 설정값을 \"내보내기\" 합니다.
+ 관리 메뉴에서 설정값을 현재 기기로 \"내보내기\" 합니다.
+ 핸드폰의 Internal Storage/AAPS/preferences 폴더에서 설정값을 찾을 수 있습니다.
+ 안전한 외부 기기 (예를 들어, 클라우드 드라이브, 컴퓨터에 케이블 연결, email, 등)에 설정 파일을 복사합니다.
+ 핸드폰을 잃어버렸거나 고장난 경우, 백업해놓지 않아도 설정값을 원격으로 쉽게 되살릴 수 있습니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/ExportImportSettings.html
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ 노이즈가 심한 CGM의 혈당값
CGM 혈당의 노이즈가 심하다면 어떻게 해야합니까?
+ 특별한 조치를 하지 않습니다. - AndroidAPS가 이를 알아서 처리할 것입니다.
+ 과량주입 또는 과소주입의 가능성을 막기 위해 closed loop 기능을 끕니다.
+ 지속적인 노이즈나 부정확한 센서를 교체합니다.
+ 사용 중인 CGM 어플이 데이터 평활화 기능을 제공하는지 확인합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ 운동과 프로파일
+ 유산소 운동을 할 때 프로파일을 어떻게 설정하는 것이 시스템에 가장 도움이 될까요?
+ 프로파일을 100% 보다 낮게 변경합니다.
+ 프로파일을 100% 보다 높게 변경합니다.
+ 프로파일을 100%로 그대로 둡니다.
+ Loop 기능을 중지합니다.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/temptarget.html#activity-temp-target
+ 운동과 임시 목표
+ 유산소 운동을 할 때 임시 목표를 어떻게 설정하는 것이 시스템에 가장 도움이 될까요?
+ 운동을 시작하기 전 적절한 시간에 \"운동 시 임시 목표\"가 작동하도록 설정합니다.
+ 운동이 끝난 후 \"운동 시 임시 목표\"를 설정합니다.
+ 임시 목표를 변경하지 않습니다.
+ \"저혈당 임시 목표\"보다 혈당이 떨어질 때까지 기다린 후 빠르게 반응하는 탄수화물 15g을 섭취합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/temptarget.html#activity-temp-target
+ 중지 또는 일시중지된 loop
Loop가 중지/일시중지 되었을때 인슐린이 주입됩니까?
네, Basal 인슐린은 계속 주입됩니다.
아니오, 인슐린 주입이 모두 중지됩니다.
+ Basal, ISF, and I:C 테스트
+ 언제 이 값들을 확인해야할까요?
+ Looping을 시작하게 전
+ 자주 고혈당 또는 저혈당을 경험할 때
+ 적어도 일주일에 한 번
+ 한 번 설정하고 확인하면, 이 값은 계속 변하면 안됨.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Getting-Started/FAQ.html#androidaps-settings
+ 기본 준비사항
+ AndroidAPS를 설정하고 사용하기 위해 필수적인 것은 무엇일까요?
유효한 프로파일 정보 (Basal, IC, ISF, DIA).
+ Android Studio가 설치되고 환경설정된 컴퓨터
지원되는 폰.
+ Closed loop을 사용할 계획이라면 호환되는 인슐린 펌프
+ 모든 데이터의 log를 보관하고 설정을 검토하기 위한 Nightscout
Tidepool 계정.
구글(Google) 계정.
깃허브(Github) 계정.
+ 프로그래밍이나 코딩을 해 본 경험
미니메드(MiniMed) 670G 펌프.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Module/module.html
스마트워치.
지원되는 연속혈당측정기(CGM).
+ 기본 준비사항
+ AndroidAPS를 설정하고 사용하기 위해 필수적인 것은 무엇일까요?
+ 프로파일을 설정하기 위해 확인된 정보 (ISF, I:C ratio, basal 양, DIA 등).
+ 호환되는 Android 장치 (예를 들어, 핸드폰, Android 워치, 또는 태블릿).
+ Closed loop을 실행하기 위해서는 AndroidAPS가 인터넷에 연결되어 있어야 함.
+ 지원되는 CGM과 핸드폰 또는 장치에 혈당값을 수신하기 위한 적절한 어플.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Module/module.html
+ AndroidAPS 업데이트하기
+ 올바른 답변을 모두 체크하세요.
+ 컴퓨터에 Git을 설치하고 환경 설정해야 합니다.
+ AndroidAPS의 업데이트된 버전이 배포되면, 일정 시간이 지난 후 이전 버전은 원격으로 제한됩니다.
+ Keystore의 위치를 저장하고 기록해두어야 이전에 설치할 때 사용했던 동일한 signing key를 업데이트할 때 사용할 수 있습니다.
시스템이 잘 작동한다면 절대 업데이트하지마세요.
+ 만약 apk를 만드는 것이 어렵다면, 친구가 만든 apk를 사용하여 설치할 수 있습니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ 문제 해결
+ 어디에서 AndroidAPS에 대한 도움을 받을 수 있을까요?
+ Facebook의 AndrioidAPS 사용자 그룹에 조언을 요청할 수 있습니다.
+ AndroidAPS 문서를 읽어야 (그리고 다시 읽어야) 합니다.
+ AndroidAPS Gitter room에 기술적 문제들을 기록하고, 조언을 요청할 수 있습니다.
+ 당뇨병 클리닉/내분비내과의사에게 문의해야 합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
https://www.facebook.com/groups/AndroidAPSUsers/
https://gitter.im/MilosKozak/AndroidAPS
+ 인슐린 플러그인
+ 어떤 인슐린에서 초-초속효성의 Oref 플러그인을 사용해야 할까요?
피아스프(Fiasp®)
+ 노보래피드(NovoRapid®)/노보로그(Novolog®)
휴마로그(Humalog®)
+ 액트라피드(Actrapid®)/휴말린 R(Humalin R®)/\"보통의\" 인간 인슐린.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Configuration/Config-Builder.html#insulin
+ 민감도 플러그인
+ 올바른 답변을 모두 체크하세요.
+ 민감도 플러그인은 AndroidAPS가 일시적 또는 단기적으로 인슐린 민감도를 조절할 수 있도록 합니다. (예를 들어, 호르몬 변화 또는 주입 부위에서 흡수의 문제)
+ 민감도 플러그인은 프로파일을 수정할 때 사용할 수 있도록 basal 양, I:C ratio, ISF의 추천되는 변화값을 사용자에게 제공합니다.
+ 캐뉼라 교체를 입력하면 Autosens 비율은 100%로 되돌아갑니다.
+ 일부 플러그인 옵션은 사용자가 설정 가능한 시간 범위를 갖습니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Configuration/Sensitivity-detection-and-COB.html
+ 탄수화물 입력 오류
부적절한 탄수화물을 입력하였다면 어떻게 하여야 합니까?
+ 관리 메뉴에서 잘못된 입력을 삭제하고, 새로운 탄수화물 양으로 수정합니다.
+ 주입 세트 교체 메뉴의 prime 기능을 사용하여 bolus 인슐린을 주입합니다.
+ 특별한 조치를 하지 않습니다. - AndroidAPS가 적절한 조정을 할 것입니다.
+ 홈 화면에서 \"인슐린 (bolus)\" 버튼을 사용하여 bolus 인슐린을 주입합니다.
+ 인슐린 주입/입력 오류
+ 만약 펌프 기록에서 보여지는 것보다 인슐린이 적게 주입되었을 때 어떻게 해야 할까요? (예를 들어, 주입 막힘, 캐뉼라 문제, 샤워 후 펌프 재부착을 잊어버렸을 때)
+ Nightscout 케어포탈에서 인슐린 데이터를 삭제하여 펌프 기록에서 이를 제거합니다.
+ AndroidAPS와 펌프 기록을 비교합니다.
+ \"주입되지 않은\" 인슐린양을 계산하여 시린지/펜 또는 prime 기능을 사용하여 인슐린을 주입합니다.
+ 특별한 조치를 취하지 않고, AndroidAPS가 결과적으로 높은 혈당 정도를 조정할 수 있도록 합니다.
+ 활성 인슐린 (IOB)
+ 올바른 답변을 모두 체크하세요.
+ IOB 값은 실행된 임시 basal의 영향을 받습니다.
+ 혈당이 목표보다 낮을 경우 높은 임시 basal은 실행되지 않습니다.
+ 운동 없이도 음수의 IOB (마이너스 IOB) 구간이 많을 경우, 프로파일이 너무 강한 것이며 인슐린 양을 적게 설정해야 합니다.
+ 양수의 IOB (플러스 IOB) 구간이 많을 경우, 인슐린 저항성 또는 입력하지 않은 식사를 의미합니다.
+ 탄수화물 입력과 bolus
+ 섭취한 탄수화물을 계산하고 기록할 때 gram 단위만을 사용해야 합니다.
+ 섭취한 탄수화물은 적절한 변환 방식 (예를 들어, DAFNE \"CHO\" 변환 또는 유럽의 \"Bread Units\")을 이용하여 기록할 수 있습니다.
+ AndroidAPS는 탄수화물의 \"소화\"를 예측하고 COB를 계산하기 위해 dynamic model을 사용합니다.
+ 만약 혈당이 적절한 값을 벗어나면 (너무 낮거나 너무 높은 경우), 탄수화물 또는 교정 인슐린의 제안을 위해 bolus 계산기를 사용할 수 있습니다.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-to-carb-ratio-ic-g-u
+ 확장 탄수화물 (e-carbs)
+ c-carbs (확장 탄수화물)을 언제 사용할 수 있을까요?
+ (일정 기간에 걸쳐 인슐린을 나눠서 주입하는 확장 bolus와 유사하게) 일정 기간에 걸쳐 나눠서 탄수화물을 섭취할 계획이 있을 때.
+ AndroidAPS가 모르게 (인슐린 주입없이) 운동 시 섭취하는 \'free\' 탄수화물을 기록하기 위함.
+ (이후에 나눠서 섭취할) 확장 탄수화물 (e-carbs)은 AndroidAPS가 고지방/고단백질 식이를 조절하는데 도움을 줄 수 있습니다.
+ 저혈당 처치를 위해 사용한 탄수화물의 제거를 기록하기 위함.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/Extended-Carbs.html
+ 원격 모니터링
+ 어떻게 AndroidAPS를 원격으로 모니터링할 수 있을까요 (예를 들어, 아이들)?
+ NS Client 어플, Nightscout 어플, Nightscout 웹페이지 모두 AndroidAPS를 원격으로 팔로우 할 수 있게 합니다.
+ 다른 어플들(예를 들어, Dexcom 팔로우, 팔로우 모드의 xDrip)은 일부 변수들(혈당/센서 수치)을 원격으로 팔로우 할 수 있지만, 알고리즘이 달라 부정확한 IOB 또는 COB 값을 보여줄 수 있습니다.
+ AndroidAPS를 원격으로 팔로우하기 위해서는 Wi-Fi나 모바일/셀룰러 네트워크 데이터를 이용하여 두 기기가 모두 인터넷에 연결되어 있어야 합니다.
+ NS Client를 원격 팔로워로 사용하면 모니터링과 AndroidAPS의 완전한 제어가 가능합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Children/Children.html
+ 인슐린 민감도 (ISF)
+ ISF 값을 올리면 일정한 양의 탄수화물을 다루기 위해 더 많은 인슐린이 주입하게 합니다.
+ ISF 값을 낮추면 목표 혈당보다 높을 때 교정을 위해 더 많은 인슐린이 주입하게 합니다.
+ 혈당이 목표보다 낮을 때에는 ISF를 높이거나 낮추는 것이 인슐린 주입에 영향을 주지 않습니다.
+ ISF를 AndroidAPS 설정에 입력해야 합니다.
변경사항을 적용하는데 프로파일에서 ISF 값 변경하는 것으로 충분합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/Profiles.html
+ 프로파일에서 한 개 이상의 I:C ratio를 사용할 수 있습니다.
+ 프로파일에서 ISF를 바꾸면, I:C ratio도 항상 바꿔줘야 합니다.
+ 인슐린 대 탄수화물 비율 (I:C ratio)
+ 높은 I:C ratio은 탄수화물 섭취 시 인슐린을 적게 주입하게 합니다.
+ 높은 I:C ratio은 탄수화물 섭취 시 인슐린을 적게 주입하게 합니다.
COB가 0 인 경우 IC 비율을 변경하면 혈당을 교정하기 위해 다른 양의 인슐린이 주입됩니다.
+ Bread unit (교환 단위)를 10g 또는 12g으로 계산하면 IC 값도 달라지게 됩니다.
+ IC: 1U의 인슐린으로 bread uits (교환 단위)를 얼마나 섭취할 수 있는 지를 의미합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ 프로파일 변경
+ 프로파일을 90%로 변경하였을 때, 다음 중 옳은 것은?
+ Basal 양이 10% 감소합니다.
+ ISF가 10% 증가합니다.
+ I:C ratio 값이 10% 작은 수가 됩니다.
+ ISF와 I:C ratio는 변하지 않습니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ 프로파일 변경
+ 프로파일을 120%로 변경하였을 때, 다음 중 옳은 것은?
+ 목표 혈당값이 20% 높아집니다.
+ Basal 양이 20% 증가합니다.
+ 목표 혈당값은 변하지 않습니다.
+ ISF가 20% 증가합니다.
+ 프로파일 변경
+ 평소보다 2시간 먼저 일어난 경우, 변경된 일정을 AndroidAPS에게 어떻게 입력해야 할까요?
+ 시간이동 2으로 프로파일을 변경합니다.
+ 시간이동 -2으로 프로파일을 변경합니다.
+ \"식사 전 임시 목표\"로 설정합니다.
+ 프로파일을 100% 보다 높게 변경합니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ 프로파일의 변화
+ Basal rates, ISF, I:C ratio 등을 프로파일에서 설정해야 합니다.
+ Nightscout 프로파일에서의 변화를 활성화 시키려면, AndroidAPS용 핸드폰이 인터넷에 연결되어 있어야 합니다.
+ 변경된 것을 실행하려면, 프로파일에서 변화된 값을 수정하기만 하면 됩니다.
+ 변화하는 상황 (예를 들어, 호르몬 변화, 교대근무, 평일/주말 생활 방식)에 적응하기 위하여 여러 개의 프로파일을 만들어서 선택할 수 있습니다.
https://androidaps.readthedocs.io/en/latest/CROWDIN/ko/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Basal 양에 대한 도움
Basal값 등과 관련된 도움을 어디서 받아야 하나요?
의료진
구글(Google)
페이스북(Facebook)
+ 다른 약물. 하단의 문구를 읽고, 내용을 수용하면 네모칸에 체크하십시오.
+ AndroidAPS는 혈당을 올리기 위하여 basal값을 내리거나 중단합니다. SGLT2 억제제 (gliflozins) 계열의 약물들은 혈당 상승을 억제하여 DKA (케톤산증)을 일으킬 정도로 위험한 인슐린의 결핍을 유발할 수 있습니다.
+\n일반적인 브랜드명은 다음과 같습니다: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\n본인은 AndroidAPS를 사용할 때 이러한 약물들을 복용하지 않을 것, 또는 이러한 약물들을 복용하기 전에 loop을 비활성화 할 것을 약속합니다.
diff --git a/app/src/main/res/values-ko-rKR/objectives.xml b/app/src/main/res/values-ko-rKR/objectives.xml
index 620b7a5f37..9bf19a6aee 100644
--- a/app/src/main/res/values-ko-rKR/objectives.xml
+++ b/app/src/main/res/values-ko-rKR/objectives.xml
@@ -19,7 +19,10 @@
섭취한 탄수화물양을 입력하고 1주일동안 낮시간대에 loop를 성공적으로 사용하여 봅니다
AMA(Advanced Meal Assist)같은 낮시간대를 위한 추가적인 기능들을 실행하여 봅니다
낮시간대에 SMB(Super Micro Bolus)같은 추가기능을 활성화해 사용해봅니다
+ 자동화 사용
SMB가 잘 작동하게 하기위해서 wiki를 반드시 읽은 다음 maxIOB 값을 올려보세요! maxIOB=평균 식사 Bolus + 3 x 최대하루 Basal이면 적당한 시작값입니다
+ 자동화가 어떻게 작동하는지 설명서를 확인하세요. 간단한 첫 번째 규칙을 만들어 보십시오. 실행하기 전에 AAPS가 알림을 보여주도록 설정합니다. 자동화가 적시에 잘 작동하는 것을 확인하면 알림을 실제 실행으로 변경하십시오.
+(https://androidaps.readthedocs.io/en/latest/EN/Usage/Automation.html)
NS에서 혈당이 확인 가능합니다
NS에서 펌프상태가 확인 가능합니다
수동 주입
@@ -34,9 +37,11 @@
Loop 플러그인 내용을 표시합니다
홈의 혈당 차트를 길게 눌러 차트 시간을 변경하세요
입력
+ 다른 시스템에서 closed loop을 적어도 3개월 동안 사용한 경우 목표를 건너뛸 수 있는 코드를 받을 수 있습니다. 자세한 정보는 https://androidaps.readthedocs.io/en/latest/EN/Usage/Objectives.html#skip-objectives를 참고하십시오.
코드 인증
잘못된 코드
당신의 지식을 확인해봅니다
+ 문제들에 대한 공부. 각각의 질문에 네 개의 답변이 주어집니다. 한 개 이상의 정답이 있을 수 있습니다. 올바른 것을 모두 체크하고, 확인을 선택하십시오.
다음 시간까지 답변 불가능: %1$s
잘못된 답변!
다음 미답변
diff --git a/app/src/main/res/values-ko-rKR/strings.xml b/app/src/main/res/values-ko-rKR/strings.xml
index 40430fb863..ef443cfa1f 100644
--- a/app/src/main/res/values-ko-rKR/strings.xml
+++ b/app/src/main/res/values-ko-rKR/strings.xml
@@ -6,6 +6,7 @@
관리 안전설정
최대 허용 Bolus [U]
최대 허용 탄수화물 [g]
+ %1$s 설정
설정
NS에서 관리 새로고침
데이터베이스 초기화
@@ -19,6 +20,7 @@
Nightscout에서 정의된 음식 설정을 표시합니다.
휴마로그와 노보래피드에 대한 인슐린 설정
피아스프에 대한 인슐린 설정
+ Lyumjev에 대한 인슐린 설정
인슐린활동의 피크를 직접 정의할 수 있습니다. 고급 사용자만 사용해야 합니다.
Loop를 활성화 혹은 비활성화합니다.
Nightscout과 데이터 동기화하기
@@ -30,11 +32,13 @@
다회요법으로 관리하는 사용자를 위한 설정
가상용 펌프를 위한 설정(Open Loop)
Oref0와 동일한 방법으로 민감도가 계산되지만, 과거 시간을 지정할 수 있습니다. 최소 탄수화물 흡수는 설정에서 최대 탄수화물 흡수 시간으로 부터 계산됩니다.
+ 민감도가 과거 8시간의 데이터로 부터 계산됩니다. (흡수되지 않은 경우) 탄수화물은 설정에서 설정된 시간이 지나면 없어집니다. UAM(알리지 않은 음식)도 계산합니다.
민감도가 편차의 가중평균으로 계산됩니다. 최근의 편차가 더 가중됩니다. 최소 탄수화물 흡수는 설정에서 최대 탄수화물 흡수 시간으로 부터 계산됩니다. 이 알고리즘의 민감도가 가장 빠릅니다.
패치된 Eversense 앱에서 혈당값 받기
Glimp에서 혈당값 받기
600SeriesAndroidUploader에서 혈당값 받기
Nightscout에서 다운로드하여 혈당값 받기
+ xDrip+에서 혈당값 받기
모든 관리를 저장합니다.
WearOS 워치를 이용하여 AndroidAPS를 모니터하고 제어합니다.
xDrip+ 워치페이스에서 Loop정보 보여주기
@@ -77,8 +81,6 @@
케어포털
펌프
어떤 펌프를 AndroidAPS에서 사용하시겠습니까?
- 관리
- 관리를 위해서 어떤 플러그인을 사용합니까?
프로파일
어떤 프로파일을 AndroidAPS에서 사용합니까?
APS
@@ -107,11 +109,14 @@
입력값을 변경하세요!
혈당 출처
AndroidAPS가 어디에서 데이터를 가져옵니까?
+ xDrip+
APS 모드
Closed Loop
Open Loop
+ 저혈당 주입정지
Loop 중지됨
새로운 제안이 있습니다
+ 탄수화물 제안
지원하지 않는 Nightscout 버전입니다
Basal IOB
Bolus 제한이 적용되었습니다
@@ -126,7 +131,9 @@
임시Basal
확장 Bolus
Nightscout 버전:
+ 부족 %1$d g
설정이 저장되었습니다
+ 사용자 입력 사항들이 저장됨
다음 위치에 설정을 저장하시겠습니까
다음 위치에서 설정을 불러오시겠습니까
설정을 불러왔습니다
@@ -136,6 +143,17 @@
이 값은 OpenAPS에서 Max Basal(최대 Basal)로 설정되는 값입니다
OpenAPS가 주입할수 있는 최대 Basal IOB [U]
이 값은 OpenAPS에서 Max IOB라고 부르는 값입니다\n기본값은 0으로 설정되어 있습니다. 몇일 혹은 몇주 정도 사용 후 적절한 값으로 변경할 수 있습니다.
+ 내보낸 preferences 암호화 하기 위해 마스터 비밀번호가 필요합니다.
+ 내보낸 preferences를 가져오기 위해서는 마스터 비밀번호가 필요합니다.
+ 내보내기 취소됩니다! 환경 설정을 내보내지 않았습니다!
+ 가져오고 취소됩니다! 환경설정을 가져오지 않았습니다.
+ 가져오기 전에 환경설정을 확인하세요.
+ 환경 설정을 가져올 수가 없습니다.
+ 환경 설정을 가져오면 안됩니다.
+ 환경설정 가져오기 문제 설명
+ 환경설정 가져오기 문제의 상세정보
+ 가져오기
+ 무시하고 가져오기 (위험!)
최종 사용자 라이선스 동의서
이 프로그램을 의학적 결정을 내리는 데 사용해서는 안되며, 여기에 대한 어떠한 보증도 없습니다. 이 프로그램의 품질과 성능에 관한 모든 위험은 사용자에게 있습니다.\nMUST NOT BE USED TO MAKE MEDICAL DECISIONS. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
모두 이해하였고 동의합니다.
@@ -249,6 +267,8 @@
SMS폰번호가 유효하지 않습니다
보정
xDrip+가 설치되지 않았습니다
+ 보정이 xDrip으로 전송되었습니다+
+ 보정 전송됨. xDrip에서 수신이 되도록 설정되어 있어야 합니다+.
펌프 일시중지됨
실행중
가상펌프 설정
@@ -275,6 +295,7 @@
IOB 자세하게 보여주기
워치페이스에 IOB를 Bolus IOB와 Basal IOB로 나누어서 보여줍니다.
성공하지 못했습니다. 폰을 확인하세요
+ 사용불가
어린이
청소년
성인
@@ -287,11 +308,16 @@
2시간동안 Loop 일시중지
3시간동안 Loop 일시중지
10시간동안 Loop 일시중지
+ 펌프 일시중지
15분동안 펌프 일시중지
30분동안 펌프 일시중지
1시간동안 펌프 일시중지
2시간동안 펌프 일시중지
3시간동안 펌프 일시중지
+ 1시간
+ 2시간
+ 3시간
+ 10시간
재실행
펌프 재연결
기간이 잘못되었습니다.
@@ -311,6 +337,8 @@
홈화면에 상태 표시등 보여주기
주사기량 경고 기준값[U]
주사기량 위험 기준값[U]
+ BAS
+ ACT
버전정보
SMS 권한 누락
전화 상태 권한이 허가되지 않았습니다
@@ -319,6 +347,9 @@
BGI를 상태라인에 추가하기
확장Bolus 취소
프로파일 변경 실행
+ 센서
+ 인슐린
+ 나이:
알람 옵션
누락 데이터 기준값 [min]
위험 누락 데이터 기준값 [min]
@@ -549,6 +580,7 @@
주의: 활성화하고 펌프에 연결하게되면, AndroidAPS는 프로파일의 Basal설정을 복사해서 기존에 펌프에 저장되어 있던 Basal설정을 덮어쓰게 될것입니다. AndroidAPS의 Basal설정이 올바른지 반드시 확인하세요. 만약 확실치 않거나 Basal설정을 덮어씌우길 원치않는다면, 취소버튼을 누르고 나중에 다시 연결하세요.
관리 데이터가 불완전합니다
정비 설정
+ Email
전송할 로그 수
정비
MAINT
@@ -634,6 +666,7 @@
혈당 정상범위의 하한값(표시 전용)
혈당 정상범위의 상한값(표시 전용)
나이:
+ 몸무게:
ID:
확인
가장 많이 사용된 프로파일:
@@ -661,4 +694,7 @@
임시 Basal 요청시간
임시 Basal 실행시간
+ 예측
+ 차트 메뉴
+ 교체
diff --git a/app/src/main/res/values-lt-rLT/strings.xml b/app/src/main/res/values-lt-rLT/strings.xml
index 0d6ab9e074..fac5bc203d 100644
--- a/app/src/main/res/values-lt-rLT/strings.xml
+++ b/app/src/main/res/values-lt-rLT/strings.xml
@@ -80,8 +80,6 @@
Priežiūra
Pompa
Kokią pompą naudosite su AndroidAPS?
- Terapija
- Kuris įskiepis bus naudojamas terapijos tvarkymui?
Profilis
Kurį profilį naudos AndroidAPS?
DKS
diff --git a/app/src/main/res/values-nl-rNL/strings.xml b/app/src/main/res/values-nl-rNL/strings.xml
index 8f9ba618cd..b9c916af95 100644
--- a/app/src/main/res/values-nl-rNL/strings.xml
+++ b/app/src/main/res/values-nl-rNL/strings.xml
@@ -81,8 +81,6 @@
Careportal
Pomp
Welke pomp wil je gaan gebruiken met AndroidAPS?
- Behandelingen
- Welke plugin moet worden gebruikt voor de Behandelingen?
Profiel
Welk profiel moet AndroidAPS gebruiken?
APS
diff --git a/app/src/main/res/values-no-rNO/strings.xml b/app/src/main/res/values-no-rNO/strings.xml
index 0f85c408c7..e63e0eba9a 100644
--- a/app/src/main/res/values-no-rNO/strings.xml
+++ b/app/src/main/res/values-no-rNO/strings.xml
@@ -81,8 +81,6 @@
Careportal
Pumpe
Hvilken pumpe ønsker du å bruke sammen med AndroidAPS?
- Behandlinger
- Hvilken plugin burde brukes til håndtering av behandlinger?
Profil
Hvilken profil bør AndroidAPS bruke?
APS
@@ -778,6 +776,7 @@
BS
Verktøy
Vis beregning
+ Vis slettede
Slett køen? All data i køen vil gå tapt!
Bruk av forlenget bolus funksjon vil deaktivere lukket loop i perioden med forlenget bolus. Vil du virkelig dette?
Lukket loop deaktivert på grunn av forlenget bolus
@@ -899,4 +898,25 @@
Profil maksimal basal dose
Aktiv basal dose
Profil karbohydratfaktor (IK)
+ Full synkronisering
+ Prime
+ Synkronisering
+ Profiler, boluser, karbohydrater, midlertidige basaler lastes opp til NS
+ Last opp data til NS
+ Hent lagrede profiler
+ Synkroniser profiler fra NS til lokal profil
+ Motta midlertidige BS mål
+ Aksepter midlertidige mål angitt med NS eller NSClient
+ Motta profilbytter
+ Aksepter profilbytter som er angitt via NS eller NSClient
+ Motta APS offline hendelser
+ Aksepter APS offline hendelser lagt inn gjennom NS eller NSKlient
+ Motta insulin
+ Aksepter insulin angitt via NS eller NSClient (enhetene er ikke dosert, kun beregnet mot IOB)
+ Motta karbohydrater
+ Aksepter karbohydrater angitt med NS eller NSClient
+ Motta behandlingshendelser
+ Godta behandlingshendelser (kanyle, insulin, batteribytte osv.) som er lagt inn gjennom NS eller NSClient
+ Motta/tilbakefyll CGM data
+ Aksepter CGM data fra NS
diff --git a/app/src/main/res/values-pl-rPL/strings.xml b/app/src/main/res/values-pl-rPL/strings.xml
index 1b2c1b26b2..bc8c65242e 100644
--- a/app/src/main/res/values-pl-rPL/strings.xml
+++ b/app/src/main/res/values-pl-rPL/strings.xml
@@ -81,8 +81,6 @@
PortalOpieki
Pompa
Którą pompę chcesz wykorzystać do AndroidAPS?
- Terapia
- Która wtyczka powinna być używana do obsługi leczenia?
Profil
Który profil będzie używany w AndroidAPS?
APS
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index e75601545e..48f5835d62 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -78,8 +78,6 @@
Careportal
Bomba
Qual a bomba que gostaria de usar com AndroidAPS?
- Tratamentos
- Qual o plugin que deve ser usado para os tratamentos?
Perfil
Qual perfil o AndroidAPS deve usar?
APS
diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml
index aa36535290..95b3d18ad7 100644
--- a/app/src/main/res/values-pt-rPT/strings.xml
+++ b/app/src/main/res/values-pt-rPT/strings.xml
@@ -81,8 +81,6 @@
Careportal
Bomba
Qual a bomba que gostaria de utilizar com AndroidAPS?
- Tratamentos
- Qual o plugin que deve ser usado para os tratamentos?
Perfil
Que perfil deverá ser usado pelo AndroidAPS?
APS
diff --git a/app/src/main/res/values-ro-rRO/strings.xml b/app/src/main/res/values-ro-rRO/strings.xml
index eeb6707fdd..370ab6cdf3 100644
--- a/app/src/main/res/values-ro-rRO/strings.xml
+++ b/app/src/main/res/values-ro-rRO/strings.xml
@@ -81,8 +81,6 @@
Careportal
Pompă
Ce pompă doriți să folosiți cu AndroidAPS?
- Tratamente
- Ce plugin doriți să folosiți pentru gestionarea tratamentelor?
Profil
Ce profil doriți să folosească AndroidAPS?
APS
diff --git a/app/src/main/res/values-ru-rRU/strings.xml b/app/src/main/res/values-ru-rRU/strings.xml
index b9edc29846..3dfb51a6af 100644
--- a/app/src/main/res/values-ru-rRU/strings.xml
+++ b/app/src/main/res/values-ru-rRU/strings.xml
@@ -81,8 +81,6 @@
Портал лечения / назначений
помпа
Какой помпой вы хотели бы пользоваться с AndroidAPS?
- назначения
- Каким плагином пользоваться для выполнения назначений?
профиль
Какой профиль следует использовать в AndroidAPS?
система ИПЖ
@@ -913,6 +911,8 @@ Context | Edit Context
Принимать временные цели, установленные через NS или NSClient
Получать переключения профиля
Принимать переключения профиля, введенные через NS или NSClient
+ Принимать события APS автономно
+ Принимать события APS введенные через NS или клиент NS автономно
Принимать инсулин
Принимать инсулин, введенный через NS или NSClient (не подается, только рассчитывается как активный IOB)
Принимать углеводы
@@ -921,4 +921,6 @@ Context | Edit Context
Принимать события терапии (катетер, инсулин, изменение батареи и т. д.) через NS или NSClient
Получать/заполнять данные мониторинга CGM
Принимать данные мониторинга CGM из NS
+ Таймаут во время ожидания окончания предыдущего соединения с помпой
+ В очереди есть еще один болюс. Повторите попытку позже.
diff --git a/app/src/main/res/values-sk-rSK/strings.xml b/app/src/main/res/values-sk-rSK/strings.xml
index 936d9a2b36..25519b199c 100644
--- a/app/src/main/res/values-sk-rSK/strings.xml
+++ b/app/src/main/res/values-sk-rSK/strings.xml
@@ -81,8 +81,6 @@
Starostlivosť
Pumpa
Akú pumpu chcete používať s AndroidAPS?
- Ošetrenia
- Aký modul chcete používať pre spracovanie ošetrení?
Profil
Aký profil má používať AndroidAPS?
APS
@@ -911,6 +909,8 @@
Prijať dočasné ciele zadané prostredníctvom NS, alebo NSClienta
Prijímať prepnutia profilov
Prijať prepnutia profilov zadané prostredníctvom NS, alebo NSClienta
+ Prijímať udalosti APS offline
+ Prijať APS offline udalosti zadané prostredníctvom NS, alebo NSClienta
Prijímať inzulín
Prijať inzulín vložený cez NS, alebo NSClient (nie je dodaný, iba započítaný do IOB)
Prijímať sacharidy
diff --git a/app/src/main/res/values-sv-rSE/strings.xml b/app/src/main/res/values-sv-rSE/strings.xml
index f86149ac29..b5853150c3 100644
--- a/app/src/main/res/values-sv-rSE/strings.xml
+++ b/app/src/main/res/values-sv-rSE/strings.xml
@@ -82,8 +82,6 @@ Eversense-appen.
Careportal
Pump
Vilken pump vill du använda med AndroidAPS?
- Behandlingar
- Vilket insticksprogram ska användas för att hantera behandlingar?
Profil
Vilken profil ska AndroidAPS använda?
APS
diff --git a/app/src/main/res/values-tr-rTR/strings.xml b/app/src/main/res/values-tr-rTR/strings.xml
index 2e9efe6091..da43d1f516 100644
--- a/app/src/main/res/values-tr-rTR/strings.xml
+++ b/app/src/main/res/values-tr-rTR/strings.xml
@@ -73,8 +73,6 @@
Careportal
Pompa
Hangi pompa ile AndroidAPS kullanmak istersiniz?
- Tedaviler
- Hangi eklenti tedavi işleme için kullanılsın?
Profil
Hangi profili AndroidAPS kullanmalı?
APS (YPS)
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index 76ef7ce813..910992c926 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -74,8 +74,6 @@
护理记录
胰岛素泵
你想用 AndroidAPS连接哪个胰岛素泵?
- 治疗
- 什么插件应该用于治疗处理?
配置文件
AndroidAPS 应该使用哪个配置文件?
APS
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 1e932c24dd..b8b391ef37 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
@@ -1155,5 +1153,7 @@
ns_receive_cgm
Receive/backfill CGM data
Accept CGM data from NS
+ Timeout while waiting for finish of previous pump communication
+ There is another bolus in queue. Try again later.
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
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/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..0a8dd8db50 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.ensureTempDirExists()).thenReturn(File("src/test/res/logger"))
}
@Test fun logFilesTest() {
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt
index dcc14fabfc..cf4e9d1b87 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt
@@ -56,7 +56,7 @@ class AuthRequestTest : TestBase() {
@Test fun doTests() {
val requester = Sms("aNumber", "aText")
- val action: SmsAction = object : SmsAction() {
+ val action: SmsAction = object : SmsAction(false) {
override fun run() {
actionCalled = true
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.kt
index 29fa359f51..ba47efe6c9 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.kt
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.kt
@@ -10,14 +10,14 @@ class SmsActionTest {
var result = ""
@Test fun doTests() {
- var smsAction: SmsAction = object : SmsAction() {
+ var smsAction: SmsAction = object : SmsAction(false) {
override fun run() {
result = "A"
}
}
smsAction.run()
Assert.assertEquals(result, "A")
- smsAction = object : SmsAction(1.0) {
+ smsAction = object : SmsAction(false, 1.0) {
override fun run() {
result = "B"
}
@@ -25,7 +25,7 @@ class SmsActionTest {
smsAction.run()
Assert.assertEquals(result, "B")
Assert.assertEquals(smsAction.aDouble(), 1.0, 0.000001)
- smsAction = object : SmsAction(1.0, 2) {
+ smsAction = object : SmsAction(false, 1.0, 2) {
override fun run() {
result = "C"
}
@@ -34,7 +34,7 @@ class SmsActionTest {
Assert.assertEquals(result, "C")
Assert.assertEquals(smsAction.aDouble(), 1.0, 0.000001)
Assert.assertEquals(smsAction.secondInteger().toLong(), 2)
- smsAction = object : SmsAction("aString", 3) {
+ smsAction = object : SmsAction(false, "aString", 3) {
override fun run() {
result = "D"
}
@@ -43,7 +43,7 @@ class SmsActionTest {
Assert.assertEquals(result, "D")
Assert.assertEquals(smsAction.aString(), "aString")
Assert.assertEquals(smsAction.secondInteger().toLong(), 3)
- smsAction = object : SmsAction(4) {
+ smsAction = object : SmsAction(false, 4) {
override fun run() {
result = "E"
}
@@ -51,7 +51,7 @@ class SmsActionTest {
smsAction.run()
Assert.assertEquals(result, "E")
Assert.assertEquals(smsAction.anInteger().toLong(), 4)
- smsAction = object : SmsAction(5, 6) {
+ smsAction = object : SmsAction(false, 5, 6) {
override fun run() {
result = "F"
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt
index 223314fd3b..01261b62fc 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.kt
@@ -86,6 +86,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
it.resourceHelper = resourceHelper
it.otp = otp
it.dateUtil = dateUtil
+ it.commandQueue = commandQueue
}
}
}
@@ -262,7 +263,7 @@ class SmsCommunicatorPluginTest : TestBaseWithProfile() {
Assert.assertTrue(smsCommunicatorPlugin.isCommand("BOLUS", ""))
smsCommunicatorPlugin.messageToConfirm = null
Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", ""))
- smsCommunicatorPlugin.messageToConfirm = AuthRequest(injector, Sms("1234", "ddd"), "RequestText", "ccode", object : SmsAction() {
+ smsCommunicatorPlugin.messageToConfirm = AuthRequest(injector, Sms("1234", "ddd"), "RequestText", "ccode", object : SmsAction(false) {
override fun run() {}
})
Assert.assertTrue(smsCommunicatorPlugin.isCommand("BLB", "1234"))
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/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/automation/build.gradle b/automation/build.gradle
index 55565f892b..e3b5a31fa9 100644
--- a/automation/build.gradle
+++ b/automation/build.gradle
@@ -6,15 +6,9 @@ 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"
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
-android {
- defaultConfig {
- versionCode 1
- versionName "1.0"
- }
-}
-
dependencies {
implementation project(':core')
implementation project(':database')
diff --git a/automation/src/main/res/values-fr-rFR/strings.xml b/automation/src/main/res/values-fr-rFR/strings.xml
index 449448894d..44315399d7 100644
--- a/automation/src/main/res/values-fr-rFR/strings.xml
+++ b/automation/src/main/res/values-fr-rFR/strings.xml
@@ -3,9 +3,9 @@
Auto
Automatisation
Tâches d\'automatisation définies par l\'utilisateur
- Merci d\'entrer le nom de la tâche.
- Merci de spécifier au moins un déclencheur.
- Merci de spécifier au moins une action.
+ Veuillez entrer un nom pour la tâche.
+ Veuillez spécifier au moins un déclencheur.
+ Veuillez spécifier au moins une action.
Alarme: %1$s
Alarme:
Mess :
diff --git a/automation/src/main/res/values-ko-rKR/strings.xml b/automation/src/main/res/values-ko-rKR/strings.xml
index 2c1f7d9cef..8ae570f554 100644
--- a/automation/src/main/res/values-ko-rKR/strings.xml
+++ b/automation/src/main/res/values-ko-rKR/strings.xml
@@ -6,6 +6,8 @@
작업 이름을 입력하세요.
적어도 하나의 트리거를 지정하세요.
적어도 하나의 액션을 지정하세요.
+ 알람: %1$s
+ 알람:
메세지:
이미 활성화됨
이미 비활성화됨
@@ -46,6 +48,8 @@
GPS 위치 사용
수동 위치 사용
위치 서비스
+ 연결 중
+ 연결 해제 중
단기 평균 증분
장기 평균 증분
증분
@@ -69,6 +73,7 @@
추가
복사
임시 목표 %1$s
+ 장치에 블루투스 연결 %1$s %2$s
WiFi SSID %1$s %2$s
Autosens %1$s %2$s %%
Autosens %
@@ -82,6 +87,7 @@
혈당 [%1$s]:
마지막 Bolus
마지막 Bolus 시간 %1$s %2$s 분 전
+ COB
COB %1$s %2$.0f
IOB [U]:
거리 [m]:
diff --git a/automation/src/main/res/values-lt-rLT/strings.xml b/automation/src/main/res/values-lt-rLT/strings.xml
index c6dbde7171..9a77054a2d 100644
--- a/automation/src/main/res/values-lt-rLT/strings.xml
+++ b/automation/src/main/res/values-lt-rLT/strings.xml
@@ -7,6 +7,7 @@
Nurodykite mažiausiai vieną sąlygą.
Nurodykite mažiausiai vieną veiksmą.
Aliarmas: %1$s
+ Aliarmas:
Pranešimas:
Jau įjungta
Jau išjungta
@@ -87,6 +88,7 @@
Gliukozė [%1$s]:
Paskutinis bolusas
Paskutinis Bolusas prieš %1$s %2$s min
+ AAO
AAO %1$s %2$.0f
AIO [U]:
Atstumas [m]:
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/build.gradle b/build.gradle
index 79bf4a03c8..cf4d289cfa 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,18 +1,15 @@
// 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 1.5.0 prevents travis from pass
- // remove @kotlin.ExperimentalStdlibApi everywhere when upgrade
- kotlin_version = '1.4.32'
- coreVersion = '1.5.0'
+ kotlin_version = '1.5.10'
+ coreVersion = '1.6.0'
rxjava_version = '2.2.21'
rxandroid_version = '2.1.1'
rxkotlin_version = '2.4.0'
room_version = '2.3.0'
lifecycle_version = '2.3.1'
- dagger_version = '2.36'
+ dagger_version = '2.37'
coroutinesVersion = '1.4.1'
activityVersion = '1.2.0'
fragmentktx_version = '1.3.0'
@@ -29,12 +26,12 @@ buildscript {
tink_version = '1.5.0'
junit_version = '4.13.2'
- mockitoVersion = '3.10.0'
+ mockitoVersion = '3.11.2'
powermockVersion = '2.0.9'
dexmakerVersion = "1.2"
retrofit2Version = '2.9.0'
okhttp3Version = '4.9.0'
- byteBuddyVersion = '1.11.0'
+ byteBuddyVersion = '1.11.5'
androidx_junit = '1.1.2'
androidx_rules = '1.4.0-alpha04'
@@ -46,12 +43,9 @@ buildscript {
maven { url "https://dl.bintray.com/kotlin/kotlinx" }
}
dependencies {
- // Update to 4.2.1 is not possible because it forces use build-tools 30.0.2
- // and this is not available in travis so far
- // 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.android.tools.build:gradle:4.2.2'
+ classpath 'com.google.gms:google-services:4.3.8'
+ classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
@@ -78,7 +72,6 @@ allprojects {
mavenCentral()
maven { url "https://maven.google.com" }
maven { url 'https://jitpack.io' }
- maven { url "https://google.bintray.com/flexbox-layout" }
ivy {
url 'https://github.com/'
patternLayout {
diff --git a/combo/build.gradle b/combo/build.gradle
index 8020051b31..6e8a0ec0c6 100644
--- a/combo/build.gradle
+++ b/combo/build.gradle
@@ -6,14 +6,7 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':core')
diff --git a/combo/src/main/res/values-fr-rFR/strings.xml b/combo/src/main/res/values-fr-rFR/strings.xml
index 321624b7f2..53e1970f73 100644
--- a/combo/src/main/res/values-fr-rFR/strings.xml
+++ b/combo/src/main/res/values-fr-rFR/strings.xml
@@ -1,7 +1,7 @@
- Intégration des pompes Accu-Chek Combo il faut avoir Ruffy installé
- Programmer la pompe pour injecter un bolus
+ Pour l\'intégration des pompes Accu-Chek Combo, il faut d\'abord installer Ruffy
+ Programmation de la pompe pour injecter un bolus
État
Activité
Pas de connexion depuis %1$d min
@@ -10,13 +10,13 @@
Arrêté pour cause d\'erreur
Arrêté par l\'utilisateur
En cours d\'exécution
- Annulation en cours du TBR
- Paramétrer TBR (%1$d%% / %2$d min)
+ Annulation du DBT
+ Réglage DBT (%1$d%% / %2$d min)
Injection du Bolus en cours (%1$.1f U)
Actualisation en cours
L\'opération demandée n\'est pas prise en charge par la pompe
Utilisation dangereuse : les bolus étendus ou carrés sont actifs. Le mode Boucle a été programmé pour des suspensions seulement pour 6 heures. Uniquement les bolus normaux sont pris en charge par le mode Boucle
- Utilisation dangereuse : la pompe utilise un profil avec taux basal différent de celui du premier. Le mode Boucle a été désactivé. Sélectionner le premier profil sur la pompe et rafraîchir.
+ Utilisation dangereuse : la pompe utilise un profil avec un taux basal différent du premier. Le mode Boucle a été désactivé. Sélectionner le premier profil sur la pompe et rafraîchir.
Un bolus avec la même quantité d’insuline a été demandé au cours de la dernière minute. Pour prévenir l’administration accidentelle de deux bolus à la fois et pour protéger contre les bugs, ceci (bolus) n\'est pas autorisé.
Maintenant
Lecture historique pompe
@@ -37,13 +37,13 @@
Paramétrage de la pompe invalide. Vérifiez la documentation et le menu QUICK INFO en utilisant le logiciel de configuration 360.
Lecture du profil basal
L\'historique de la pompe a été modifié depuis le calcul du bolus. Le bolus n\'a pas été administré. Merci de recalculer le bolus s\'il est toujours nécessaire.
- Le bolus a été délivré mais il n\'a pas pu être ajouté à l\'historique des traitements. Ceci peut se produire lorsque deux petits bolus de la même taille sont gérés dans les deux dernières minutes. Merci de vérifier l\'historique de la pompe et les entrées de traitements puis utilisez le Careportal pour y ajouter les entrées manquantes. Assurez-vous de ne pas ajouter des entrées au cours de la même minute et pour la même quantité d\'insuline.
+ Le bolus a été délivré mais il n\'a pas pu être ajouté à l\'historique des traitements. Ceci peut se produire lorsque deux petits bolus de même taille sont injectés dans les deux dernières minutes. Veuillez vérifier l\'historique de la pompe et les entrées de traitements puis utilisez Careportal pour y ajouter les entrées manquantes. Assurez-vous de ne pas ajouter d\'entrées au cours de la même minute et pour la même quantité d\'insuline.
Rejet cible temporaire haute parce que le calcul ne prend pas en compte les changements récents de l\'historique pompe
Actualisation de l\'état de la pompe
Le taux basal de la pompe a été modifié et sera bientôt actualisé
Le pourcentage de basal a changé dans la pompe mais sa lecture a échoué
Vérification des modifications de l\'historique
- De multiples bolus similaires viennent d\'être importés dans la même minute. Un seul enregistrement a pu être ajouté aux traitements. Merci de vérifier la pompe et d\'ajouter manuellement un enregistrement de bolus en utilisant l\'onglet Careportal. Assurez vous de créer ce bolus avec un temps différent de tous les autres Bolus.
+ De multiples bolus similaires viennent d\'être importés dans la même minute. Un seul enregistrement a pu être ajouté aux traitements. Veuillez vérifier la pompe et d\'ajouter manuellement un enregistrement de bolus en utilisant l\'onglet Careportal. Assurez vous de créer ce bolus avec un temps différent de tous les autres Bolus.
\n\ndocumentation :\nhttps://androidaps.readthedocs.io/fr/latest/\n\nfacebook :\nhttps://www.facebook.com/groups/AndroidAPSUsers
Le dernier bolus enregistré date d\'il y a plus de 24h ou est dans le futur. Vérifiez que la date dans la pompe est correctement définie.
L\'heure/date sur la pompe du dernier bolus administré semble erroné. L\'IA est probablement incorrecte. Vérifiez l\'heure/date de la pompe.
diff --git a/combo/src/main/res/values-lt-rLT/strings.xml b/combo/src/main/res/values-lt-rLT/strings.xml
index 496bdf4c3e..56aa4d18dd 100644
--- a/combo/src/main/res/values-lt-rLT/strings.xml
+++ b/combo/src/main/res/values-lt-rLT/strings.xml
@@ -3,6 +3,7 @@
Accu-Chek Combo pompos integracija, reikalinga Ruffy programėlė
Programuojamas bolusas
Būsena
+ Aktyvumas
Nėra ryšio su pompa %1$d min
%1$d%% (liko%2$d min)
Inicijuojama
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/build.gradle b/core/build.gradle
index 9b2d54be1e..7a71e453c1 100644
--- a/core/build.gradle
+++ b/core/build.gradle
@@ -8,13 +8,7 @@ apply from: 'core_dependencies.gradle'
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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':database')
diff --git a/core/core_dependencies.gradle b/core/core_dependencies.gradle
index e3971e2519..4f03629c07 100644
--- a/core/core_dependencies.gradle
+++ b/core/core_dependencies.gradle
@@ -88,7 +88,7 @@ dependencies {
api 'com.google.android.gms:play-services-wearable:17.0.0'
api 'com.google.android.gms:play-services-location:17.1.0'
- api("com.google.android:flexbox:2.0.1")
+ api("com.google.android.flexbox:flexbox:3.0.0")
api("io.socket:socket.io-client:1.0.0") {
// excluding org.json which is provided by Android
exclude group: "org.json", module: "json"
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..0e29d22b00 100644
--- a/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt
+++ b/core/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.kt
@@ -26,6 +26,7 @@ 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.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.queue.Callback
@@ -232,11 +233,15 @@ class TDDStatsActivity : NoSplashAppCompatActivity() {
@SuppressLint("SetTextI18n")
private fun loadDataFromDB() {
historyList.clear()
- historyList.addAll(repository.getLastTotalDailyDoses(10, false).blockingGet())
+ // timestamp DESC sorting!
+ historyList.addAll(repository.getLastTotalDailyDoses(10, true).blockingGet())
//only use newest 10
historyList = historyList.subList(0, min(10, historyList.size))
+ // dummies reset
+ dummies.clear()
+
//fill single gaps
val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault())
for (i in 0 until historyList.size - 1) {
@@ -425,7 +430,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/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/dialogs/ErrorDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt
index 609b70a01e..a5ccaa2b41 100644
--- a/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt
+++ b/core/src/main/java/info/nightscout/androidaps/dialogs/ErrorDialog.kt
@@ -17,7 +17,6 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.services.AlarmSoundServiceHelper
import info.nightscout.androidaps.utils.T
-import org.mozilla.javascript.tools.jsc.Main
import javax.inject.Inject
class ErrorDialog : DaggerDialogFragment() {
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))
diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt
index 898fa5f371..f02488f617 100644
--- a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt
+++ b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt
@@ -97,11 +97,11 @@ fun therapyEventFromJson(jsonObject: JSONObject): TherapyEvent? {
return te
}
-fun TherapyEvent.toJson(isAdd: Boolean): JSONObject =
+fun TherapyEvent.toJson(isAdd: Boolean, dateUtil: DateUtil): JSONObject =
JSONObject()
.put("eventType", type.text)
.put("isValid", isValid)
- .put("created_at", timestamp)
+ .put("created_at", dateUtil.toISOString(timestamp))
.put("enteredBy", enteredBy)
.put("units", if (glucoseUnit == TherapyEvent.GlucoseUnit.MGDL) Constants.MGDL else Constants.MMOL)
.also {
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/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/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/IobCobCalculator.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt
index e0e3dfbb0a..9e3a9d428a 100644
--- a/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt
+++ b/core/src/main/java/info/nightscout/androidaps/interfaces/IobCobCalculator.kt
@@ -27,6 +27,8 @@ interface IobCobCalculator {
fun iobArrayToString(array: Array): String
fun convertToJSONArray(iobArray: Array): JSONArray
+ fun clearCache()
+
/**
* Calculate CobInfo to now()
*
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/PumpSync.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt
index 46493ebfe2..e7c606e458 100644
--- a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt
+++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpSync.kt
@@ -346,7 +346,6 @@ interface PumpSync {
/**
* Invalidate of temporary basals that failed to start
- * Dash specific, replace by setting duration to zero ????
*
* If exists, isValid is set false
* If db record doesn't exist data is ignored and false returned
@@ -450,4 +449,4 @@ interface PumpSync {
fun createOrUpdateTotalDailyDose(timestamp: Long, bolusAmount: Double, basalAmount: Double, totalAmount: Double, pumpId: Long?, pumpType: PumpType, pumpSerial: String): Boolean
-}
\ 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/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) {
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/general/maintenance/PrefFileListProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt
index 86208dce3e..028b97ca75 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,11 +28,14 @@ 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 tempPath = File(path, "AAPS" + File.separator + "temp")
+ 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 const val IMPORT_AGE_NOT_YET_OLD_DAYS = 60
}
@@ -90,13 +94,28 @@ 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 ensureTempDirExists(): File {
+ if (!tempPath.exists()) {
+ tempPath.mkdirs()
+ }
+ return tempPath
+ }
+
+ fun ensureExtraDirExists(): File {
+ if (!extraPath.exists()) {
+ extraPath.mkdirs()
+ }
+ return extraPath
}
fun newExportFile(): File {
@@ -104,7 +123,7 @@ class PrefFileListProvider @Inject constructor(
return File(aapsPath, timeLocal + "_" + config.FLAVOR + ".json")
}
- fun newExportXmlFile(): File {
+ fun newExportCsvFile(): File {
val timeLocal = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyy-MM-dd'_'HHmmss"))
return File(exportsPath, timeLocal + "_UserEntry.csv")
}
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 7d61543edf..ba1609c579 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
@@ -68,9 +68,9 @@ class PumpSyncImplementation @Inject constructor(
return true
}
- if (type.description != storedType || serialNumber != storedSerial)
+ if ((type.description != storedType || serialNumber != storedSerial) && timestamp >= storedTimestamp)
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/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/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java
index 32c1d36488..2f37f541a6 100644
--- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java
+++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java
@@ -6,6 +6,7 @@ package info.nightscout.androidaps.plugins.pump.common.utils;
import org.joda.time.LocalDateTime;
import org.joda.time.Minutes;
+import org.joda.time.Seconds;
import java.util.Calendar;
import java.util.GregorianCalendar;
@@ -245,13 +246,17 @@ public class DateTimeUtil {
public static int getATechDateDiferenceAsMinutes(Long date1, Long date2) {
-
Minutes minutes = Minutes.minutesBetween(toLocalDateTime(date1), toLocalDateTime(date2));
-
return minutes.getMinutes();
}
+ public static int getATechDateDiferenceAsSeconds(Long date1, Long date2) {
+ Seconds seconds = Seconds.secondsBetween(toLocalDateTime(date1), toLocalDateTime(date2));
+ return seconds.getSeconds();
+ }
+
+
public static long getMillisFromATDWithAddedMinutes(long atd, int minutesDiff) {
GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(atd);
oldestEntryTime.add(Calendar.MINUTE, minutesDiff);
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/core/src/main/res/values-bg-rBG/strings.xml b/core/src/main/res/values-bg-rBG/strings.xml
index ac97acedbc..13f1cbb625 100644
--- a/core/src/main/res/values-bg-rBG/strings.xml
+++ b/core/src/main/res/values-bg-rBG/strings.xml
@@ -62,6 +62,7 @@
Тип събитие
мг/дл
ммол/л
+ гр.
Допълнителни настройки
Bluetooth
BT ограничения
@@ -202,6 +203,7 @@
Часовник
Автоматизация
По избор
+ Помпа
Кръг - Loop
Времето за връзка изтече
@@ -285,6 +287,13 @@
С
Н
+ СПРИ БОЛУС
+ Източник
+ Действие
+
+ - %1$d час
+ - %1$d часа
+
- %1$d минутa
- %1$d минути
diff --git a/core/src/main/res/values-cs-rCZ/strings.xml b/core/src/main/res/values-cs-rCZ/strings.xml
index 1140bdd2f1..1fb65bf365 100644
--- a/core/src/main/res/values-cs-rCZ/strings.xml
+++ b/core/src/main/res/values-cs-rCZ/strings.xml
@@ -382,6 +382,9 @@
Datum
Žádné jednotky
Exportovat uživatelské záznamy do Excelu (csv)
+ SMYČKA ZMĚNĚNA
+ SMYČKA ODEBRÁNA
+ JINÉ
- %1$d den
- %1$d dnů
diff --git a/core/src/main/res/values-fr-rFR/strings.xml b/core/src/main/res/values-fr-rFR/strings.xml
index 4a784f34ba..dca16eb3a9 100644
--- a/core/src/main/res/values-fr-rFR/strings.xml
+++ b/core/src/main/res/values-fr-rFR/strings.xml
@@ -11,7 +11,7 @@
Erreur injection basal temporaire
%1$.2f U vont être injectées
Attente connection pompe
- Connexion à %1$d en cours
+ Connexion en cours : %1$d sec.
%1$.2f U ont été injectées
Connexion
Connection en cours
@@ -382,6 +382,9 @@
Horodatage
Aucune unité
Exporter les entrées utilisateur vers Excel (csv)
+ BOUCLE CHANGÉE
+ BOUCLE SUPPRIMÉE
+ AUTRE
- %1$d jour
- %1$d jours
diff --git a/core/src/main/res/values-it-rIT/strings.xml b/core/src/main/res/values-it-rIT/strings.xml
index 62b4a7441d..f769ae42f9 100644
--- a/core/src/main/res/values-it-rIT/strings.xml
+++ b/core/src/main/res/values-it-rIT/strings.xml
@@ -105,6 +105,7 @@
Note
Rimuovi
Aggiungi nuovo
+ I dati arrivano da un micro differente. Cambia il driver del micro per resettarne lo stato.
Limitazione max velocità basale a %1$.2f U/h a causa di: %2$s
limite micro
@@ -211,6 +212,7 @@
Micro
Loop
NS
+ Record
Time out connessione
@@ -300,6 +302,7 @@
CHO
CHO ESTESI
BASALE TEMPORANEA
+ TARGET TEMPORANEO
NUOVO PROFILO
CLONA PROFILO
MEMORIZZA PROFILO
@@ -318,21 +321,25 @@
CANCELLA CHIAVI DI ASSOCIAZIONE
ACCETTA BASALE TEMPORANEA
CANCELLA BASALE TEMPORANEA
+ CANCELLA BOLO
CANCELLA BOLO ESTESO
+ CANCELLA TARGET TEMPORANEO
PORTALE
CAMBIO POSIZIONE CANNULA
CAMBIO SERBATOIO
CALIBRAZIONE
BOLO DI CARICAMENTO
TRATTAMENTO
- PORTALE NS AGGIORNAMENTO
- CAMBIO PROFILO NS AGGIORNAMENTO
- TRATTAMENTI NS AGGIORNAMENTO
+ PORTALE NS: AGGIORNAMENTO
+ CAMBIO PROFILO NS: AGGIORNAMENTO
+ TRATTAMENTI NS: AGGIORNAMENTO
+ TARGET TEMPORANEO NS: AGGIORNAMENTO
AUTOMAZIONE RIMOSSA
BG RIMOSSO
PORTALE RIMOSSO
BOLO RIMOSSO
CHO RIMOSSI
+ BASALE TEMPORANEA RIMOSSA
BOLO ESTESO RIMOSSO
CIBO
CIBO RIMOSSO
@@ -340,6 +347,7 @@
CAMBIO PROFILO RIMOSSO
EVENTI DI RIAVVIO RIMOSSI
TRATTAMENTO RIMOSSO
+ TARGET TEMPORANEO RIMOSSO
NS IN PAUSA
NS RIPRESA
CODA NS CANCELLATA
@@ -360,12 +368,23 @@
IMPORTA DATABASE
ESPORTAZIONE OTP
RESET OTP
+ STOP SMS
ESPORTA VOCI UTENTE
+ AVVIA AAPS
+ USCITA AAPS
+ PLUGIN ABILITATO
+ PLUGIN DISABILITATO
SCONOSCIUTO
Stringa
Fonte
+ Offset UTC
Azione
+ Data e ora
+ Nessuna unità
Esporta voci utente in Excel (csv)
+ LOOP CAMBIATO
+ LOOP RIMOSSO
+ ALTRO
- %1$d giorno
- %1$d giorni
diff --git a/core/src/main/res/values-iw-rIL/strings.xml b/core/src/main/res/values-iw-rIL/strings.xml
index ef704b5f4d..3159c19f7a 100644
--- a/core/src/main/res/values-iw-rIL/strings.xml
+++ b/core/src/main/res/values-iw-rIL/strings.xml
@@ -382,6 +382,9 @@
חתימת זמן
ללא יחידה
יצוא ערכי משתמש לאקסל (csv)
+ הלולאה שונתה
+ הלולאה הוסרה
+ אחר
- %1$d יום
- %1$d ימים
diff --git a/core/src/main/res/values-ko-rKR/strings.xml b/core/src/main/res/values-ko-rKR/strings.xml
index a1c6377f68..4b71c404f8 100644
--- a/core/src/main/res/values-ko-rKR/strings.xml
+++ b/core/src/main/res/values-ko-rKR/strings.xml
@@ -2,54 +2,224 @@
+ 새로고침
+ 에러
+ 설정되지 않음
+ Basal 프로파일 갱신 실패
+ Basal 프로파일이 펌프에 업데이트 되었습니다
+ 사용할수 없는 입력 데이터
+ 임시Basal 주입 에러
+ 펌프를 기다리는 중
+ %1$d 초 동안 연결중
+ 통신 확인
+ 연결중
+ 연결됨
+ 연결 끊김
+ 연결끊기중
+ AndroidAPS 시작
+ %1$.1f U
+ %1$.2f U
+ %1$.0f / %2$d U
%1$.2f U/h
+ %1$.2f 시간
+ %1$d 분
+ 펌프가 바쁩니다
+ 펌프 연결 에러
+ 허용된 제한값에 도달하였습니다
+ 목표
+ 닫기
+ 잠시 기다려 주세요...
+ 음소거
+ 새로고침
+ 정지 누름
+ 정지
+ 탄수화물
+ 프로파일이 유효하지 않습니다!!!
+ 프로파일이 설정되지 않았습니다.
+ 날짜
+ 단위
+ 인슐린활동시간(DIA):
+ 인슐린 대 탄수화물 비율(IC):
+ 인슐린 민감도(ISF):
+ Basal
+ 목표:
+ 초기화중 ...
+ 시리얼번호
+ 배터리
+ 마지막 접속
+ 최근 Bolus:
+ 일 인슐린 총량
+ 기본 Basal양
+ 임시Basal
+ 확장Bolus
+ 인슐린 잔량
+ 펌프 이력
+ 프로파일 보기
+ 이벤트 종류
+ mg/dl
+ mmol/l
+ g
+ 고급 설정
+ 블루투스
+ 블루투스 감시기능
+ 펌프에 연결이 되지 않을때 폰의 블루투스를 1초간 껐다 켭니다. 블루투스 스택이 정지되는 일부폰에 이 기능이 도움이 됩니다.
+ 동기화
네
아니오
제한으로 인해 LOOP가 사용불가합니다.
+ 네
펌프에서 유효한 Basal양을 읽을 수 없습니다.
%2$s로 인해 최대 IOB가 %1$.1f U로 제한됩니다.
위험한 사용
펌프에 연결할 수 없습니다.
확장 Bolus
펌프 시간 업데이트
+ 종료
+ 시리얼번호
+ 기록 삭제
+ Loop가 중지중입니다.
+ 알람
Loop 중지하기
Loop 실행하기
Loop 재실행
Loop 일시중지
+ 기간 [min]
공지
아직 NS에서 프로파일을 로드하지 못했습니다.
존재합니다.
존재하지 않습니다.
혈당
+ IOB
+ COB
이름:
시간
와이파이 SSID
+ 이벤트 시간
+ 노트
+ 삭제
새로 추가
+ %2$s로 인해 최대 Basal양이 %1$.2f U/h으로 제한됩니다.
+ 펌프 제한
+ %2$s로 인해 최대 비율이 %1$d%%로 제한됩니다.
+ 양의 값이어야 합니다.
+ %2$s로 인해 Bolus가 %1$.1f U로 제한됩니다.
+ 펌프가 초기화와 프로파일 설정이 되지 않았습니다!
+ 확인
+ 메시지
+ 네
+ 취소
+ 무시
+ BLE(블루투스 저전력) 지원되지 않음
+ 블루투스가 활성화되지 않았습니다.
+ 위치가 활성화되지 않았습니다.
+ 최신 스마트폰에서 블루투스 검색이 작동하려면 위치가 활성화되어 있어야합니다. AAPS는 당신의 위치를 추적하지 않으며 페어링에 성공한 후 비활성화 할 수 있습니다.
+ 시간
+ 일
+ 시간
+ 초
+ 분
+ 시
+ 일
+ 주
+ 초
+ 분
+ 시
+ 일
+ 주
+ 분
+ 일
+ 잘못된 비밀번호
+ Basal값이 시간단위로 설정되지 않았습니다: %1$s
+ 지원되는 최소값으로 Basal값이 대체되었습니다:%1$s
+ 지원되는 최대값으로 Basal값이 대체되었습니다:%1$s
+ /U
+ U/h
+ g/U
+ 프로파일이 선택되지 않았습니다
프로파일 %1$d%%을 %2$d 분 동안 시작
+ * 가상 펌프에서는 Basal/Bolus에 대해 범위로 지정이 될 수 없고, 이산값(discrete values)만 지원 됩니다.
+ 임시Basal 취소하기
+ 임시Basal 허용
+ 주입량
+ 기간
+ 근거
+ 변경사항 없음
+ 유효하지 않은 프로파일: %1$s
+ 혈당 체크
+ 알림
+ 노트
+ 의문
+ 운동
+ 펌프 위치 변경
+ CGM 센서 삽입
+ CGM 센서 시작
+ 인슐린 카트리지 교체
+ 프로파일 변경
+ 간식Bolus
+ Meal Bolus
+ 교정Bolus
+ 콤보Bolus
+ 임시Basal 시작
+ 임시Basal 종료
+ 탄수화물 교정
+ OpenAPS 오프라인
+ 펌프 배터리 교체
+ 임시 목표
+ 임시 목표 취소
Bolus 마법사
+ 채혈
+ 센서
+ 수동
+ 알수없음
식사직전
저혈당
+ 활동
워치
자동화
사용자 정의
+ 펌프
+ Loop
+ 연결시간초과
+ 실행
+ 의견
+ 성공
+ 퍼센트
+ 절대값
+ 인슐린
+ U
+ 결과 기다리는 중
+ SMB
+ 누적 일총량
+ 지수가중 일총량
+ Basal
+ Bolus
+ 일총량
+ 비율
+ #일
+ 가중
+ 교체/채움을 위해 Bolus를 사용한 경우 부정확할 수 있습니다!!
+ 오래된 데이터입니다. \"새로고침\"을 누르세요.
+ 총 기본 Basal
+ 총기초량 * 2
+ 시간 감지
가져올 파일을 선택하세요.
환경설정은 AAPS (%1$s) 와는 다르게 생성되기 때문에 불러오는 도중 일부 설정이 누락되거나 설정이 되지 않을 수 있습니다. - 가져오기를 수행한 후 설정을 확인하고 업데이트 해주시기 바랍니다.
@@ -62,6 +232,17 @@
유효하지 않은 버전을 이용 중입니다. Loop가 비활성화 되었습니다!
%1$s 버전이 사용 가능합니다.
+ 폰을 재부팅하거나 AndroidAPS를 재시작하세요 \n그렇지 않으면 로그 기록이 되지 않습니다.(알고리즘이 정상적인 작동하는지 확인하기 위해 로그가 필요합니다.)!
+ 실행
+
+ - %1$d 일
+
+
+ - %1$d 시간
+
+
+ - %1$d 분
+
diff --git a/core/src/main/res/values-no-rNO/strings.xml b/core/src/main/res/values-no-rNO/strings.xml
index 8087301f35..5dc889cffd 100644
--- a/core/src/main/res/values-no-rNO/strings.xml
+++ b/core/src/main/res/values-no-rNO/strings.xml
@@ -105,6 +105,7 @@
Merknader
Fjern
Legg til ny
+ Data kommer fra forskjellige pumper. Bytt pumpevalg for å nullstille pumpens tilstand.
Begrenser maks basal dose til %1$.2f E/t på grunn av %2$s
pumpebegrensning
@@ -208,6 +209,10 @@
Wear
Automatisering
Egendefinert
+ Pumpe
+ Loop
+ NS
+ Registrer
Tilkoblingen ble tidsavbrutt
@@ -297,6 +302,7 @@
KARBO
FORLENGET KARBO
TEMP BASAL
+ MIDLERTIDIG BS MÅL
NY PROFIL
KOPIER PROFIL
LAGRE PROFIL
@@ -315,23 +321,33 @@
NULLSTILL PARRINGS NØKLER
AKSEPTER TEMP BASAL
AVBRYT TEMP BASAL
+ AVBRYT BOLUS
AVBRYT FORLENGET BOLUS
+ AVBRYT MIDLERTIDIG BS MÅL
CAREPORTAL
+ BYTTE SLANGESETT
+ BYTTE RESERVOAR
KALIBRERING
PRIME BOLUS
BEHANDLING
CAREPORTAL NS OPPDATER
PROFILBYTTE NS OPPDATER
BEHANDLINGER NS OPPDATER
+ OPPDATER MIDLERTIDIG BS MÅL NS
AUTOMASJON FJERNET
BS FJERNET
CAREPORTAL FJERNET
+ BOLUS FJERNET
+ KARBO FJERNET
+ MIDLERTIDIG BS MÅL FJERNET
FORLENGET BOLUS FJERNET
+ MAT
MÅLTID FJERNET
PROFIL FJERNET
PROFILBYTTE FJERNET
RESTART HENDELSER FJERNET
BEHANDLING FJERNET
+ MIDLERTIDIG BS MÅL FJERNET
NS PAUSET
GJENOPPTA NS
NS KØ SLETTET
@@ -352,9 +368,23 @@
IMPORTER DATABASER
OTP EKSPORT
OTP RESET
+ STOPP SMS
EKSPORTER BRUKEROPPFØRINGER
+ START AAPS
+ AVSLUTT AAPS
+ PLUGIN AKTIVERT
+ PLUGIN DEAKTIVERT
UKJENT
+ Tekst
+ Kildekode
+ UTC tid forskyvning
+ Handling
+ Tidspunkt
+ Ingen enhet
Eksporter brukeroppføringer til Excel (csv)
+ LOOP ENDRET
+ LOOP FJERNET
+ ANNET
- %1$d dag
- %1$d dager
diff --git a/core/src/main/res/values-sk-rSK/strings.xml b/core/src/main/res/values-sk-rSK/strings.xml
index efbb0c3052..aaf22657af 100644
--- a/core/src/main/res/values-sk-rSK/strings.xml
+++ b/core/src/main/res/values-sk-rSK/strings.xml
@@ -382,6 +382,9 @@
Časová pečiatka
Žiadna jednotka
Exportovať užívateľské záznamy do Excelu (csv)
+ UZAVRETÝ OKRUH ZMENENÝ
+ UZAVRETÝ OKRUH ODSTRÁNENÝ
+ INÉ
- %1$d deň
- %1$d dní
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/crowdin.yml b/crowdin.yml
index 4939f67605..d43fae2787 100644
--- a/crowdin.yml
+++ b/crowdin.yml
@@ -39,3 +39,5 @@ files:
translation: /insight/src/main/res/values-%android_code%/exceptions.xml
- source: /automation/src/main/res/values/strings.xml
translation: /automation/src/main/res/values-%android_code%/strings.xml
+ - source: /diaconn/src/main/res/values/strings.xml
+ translation: /diaconn/src/main/res/values-%android_code%/strings.xml
diff --git a/dana/build.gradle b/dana/build.gradle
index 33b66a5090..46e26b9616 100644
--- a/dana/build.gradle
+++ b/dana/build.gradle
@@ -6,12 +6,10 @@ 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"
-
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
android {
defaultConfig {
- versionCode 1
- versionName "1.0"
kapt {
arguments {
arg("room.incremental", "true")
diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt
index 9b9a446889..063cdc0584 100644
--- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt
+++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt
@@ -168,6 +168,10 @@ class DanaFragment : DaggerFragment() {
binding.danaPumpstatuslayout.visibility = View.GONE
}
}, fabricPrivacy::logException)
+ binding.danaPumpstatus.text = ""
+ binding.danaPumpstatuslayout.visibility = View.GONE
+ @Suppress("SetTextI18n")
+ binding.btconnection.text = "{fa-bluetooth-b}"
updateGUI()
}
@@ -191,14 +195,14 @@ class DanaFragment : DaggerFragment() {
val pump = danaPump
val plugin: Pump = activePlugin.activePump
if (pump.lastConnection != 0L) {
- val agoMsec = System.currentTimeMillis() - pump.lastConnection
- val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt()
+ val agoMilliseconds = System.currentTimeMillis() - pump.lastConnection
+ val agoMin = (agoMilliseconds.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
+ val agoMilliseconds = System.currentTimeMillis() - pump.lastBolusTime
+ val agoHours = agoMilliseconds.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)
diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt
index bcbdea9165..56cf61dcfc 100644
--- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt
+++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaPump.kt
@@ -406,7 +406,8 @@ class DanaPump @Inject constructor(
0x05 -> PumpType.DANA_RS
0x06 -> PumpType.DANA_RS_KOREAN
0x07 -> PumpType.DANA_I
- else -> PumpType.DANA_R
+ 0x09 -> PumpType.DANA_I
+ else -> PumpType.USER
}
companion object {
diff --git a/dana/src/main/res/values-fr-rFR/strings.xml b/dana/src/main/res/values-fr-rFR/strings.xml
index 594074b7a3..0e1a7c6d9f 100644
--- a/dana/src/main/res/values-fr-rFR/strings.xml
+++ b/dana/src/main/res/values-fr-rFR/strings.xml
@@ -43,7 +43,7 @@
Obtenir les paramètres pompe
Obtenir l\'heure de la pompe
Différence horaire importante
- Différence horaire importante:\nL\'heure de la pompe est en écart de plus d\'une heure et demi.\nMerci d\'ajuster manuellement l\'heure de la pompe et assurez-vous que la lecture de l\'historique de la pompe ne cause pas de dysfonctionnements.\nSi possible, effacez l\'historique de la pompe avant de modifier l\'heure ou désactivez la Boucle Fermée pour une DAI après la dernière entrée erronée de l\'historique et au minimum une DAI à partir de maintenant.
+ Différence horaire importante:\nL\'heure de la pompe est en écart de plus d\'une heure et demi.\nVeuillez ajuster manuellement l\'heure de la pompe et assurez-vous que la lecture de l\'historique de la pompe ne cause pas de dysfonctionnements.\nSi possible, effacez l\'historique de la pompe avant de modifier l\'heure ou désactivez la Boucle Fermée pour une DAI après la dernière entrée erronée de l\'historique et au minimum une DAI à partir de maintenant.
Veuillez appairer votre pompe avec votre téléphone !
Limite quotidienne d\'insuline proche
Injection du bolus démarrée
diff --git a/dana/src/main/res/values-ko-rKR/strings.xml b/dana/src/main/res/values-ko-rKR/strings.xml
index 3ea04e700d..eb4bee77bb 100644
--- a/dana/src/main/res/values-ko-rKR/strings.xml
+++ b/dana/src/main/res/values-ko-rKR/strings.xml
@@ -1,2 +1,120 @@
-
+
+ 동기화
+ 현재까지 발견된 기기가 없습니다.
+ 연동완료
+ 연동시간초과
+ 펌프연동 대기중
+ 다나RS
+ Dana
+ 다나RS 펌프와 연동
+ 최대 Bolus 위반
+ 명령 오류
+ 속도 오류
+ 인슐린 제한 위반
+ 요청: %1$.2fU 전송: %2$.2fU 에러코드: %3$s
+ 값이 제대로 설정되지 않았습니다
+ Basal 단위를 0.01 U/h로 설정하세요
+ 페어링 정보를 다시 설정하시겠습니까?
+ %1$s\n모델: %2$02X\n 프로토콜: %3$02X\n 코드: %4$02X
+ 이벤트 처리중
+ 펌프에서 확장Bolus를 활성화 하세요
+ 주입됨
+ 정지됨
+ 지원되지 않는 펌프 펌웨어
+ 펌프 에러
+ 배터리 부족
+ 사전 설정된 Basal양보다 적게 주입
+ 펌프 종료
+ 펌프배터리 방전
+ 막힘
+ 빈 주사기
+ 샤프트를 확인하세요.
+ 최대 Basal
+ 일일 최대
+ 혈당측정알람
+ 남은 인슐린 양
+ 놓친 Bolus
+ 잘못된 페어링 정보입니다. 새로운 페어링을 요청합니다.
+ 펌프 상태 가져오는중
+ 확장Bolus 상태 가져오는중
+ Bolus 상태 가져오는중
+ 임시Basal 상태 가져오는중
+ 펌프설정 가져오는중
+ 펌프시간 가져오는중
+ 큰 시간 차이
+ 큰 시간 차이:\n펌프의 시간과 1.5시간 이상 차이가 납니다.\n펌프의 이력에서 잘못된 시간을 읽어들임으로써 예상치 못한 행동이 발생하지 않도록 펌프의 시간을 수동으로 변경하세요.\n가능하면 시간을 변경하기 전에 펌프의 이력을 삭제하거나, 설정된 DIA 시간동안 Closed Loop를 비활성화 하세요.
+ 펌프를 폰과 동기화 하십시오
+ 인슐린 일 허용량에 근접중
+ Bolus 주입을 시작합니다.
+ Bolus 종료를 기다리고 있습니다. %d초 남았습니다.
+ 임시Basal 취소중
+ 확장Bolus 설정중
+ 확장Bolus 취소중
+ Basal양 업데이트중
+ 임시Basal 설정중
+ 시간 동기화 대기중 (%1$d 초)
+ 펌프 비밀번호가 잘못되었습니다!
+ 알람
+ Basal 시간
+ Boluses
+ 탄수화물
+ 일일 인슐린
+ 에러
+ 혈당
+ 교체
+ 중지
+ 교체
+ 사용자 옵션
+ 시간형식
+ 버튼 스크롤
+ 버튼 누르면 소리가 납니다.
+ 알람
+ 소리
+ 진동
+ 모두
+ LCD 시간 [seconds]
+ 화면조명 시간 [seconds]
+ 혈당 단위
+ 종료 [hours]
+ 낮은 주사기량 [Units]
+ 펌프로 옵션 저장
+ 다나R 펌프와 연동(다나 RN)
+ 내수용 다나R 펌프와 연동(다나 R)
+ 업그레이드 펌웨어가 설치된 다나R 펌프와 연동
+ DANA
+ 블루투스 어댑터를 찾지 못했습니다
+ 선택된 기기를 찾지 못했습니다
+ 펌프에서 U/d에서 U/h로 모드를 변경하세요
+ 다나R 한글
+ 다나R
+ 펌프 드라이버가 수정되었습니다.
+ 다나R v2
+ 펌프에서 이지모드(EasyUI)를 해제하세요
+ Basal 프로파일 설정이 실패하였습니다
+ 블루투스 상태
+ 펌프 IOB
+ Basal 단위
+ Bolus 단위
+ 펌웨어
+ 다나 펌프 설정
+ 12h
+ 24h
+ 켜짐
+ 꺼짐
+ 다나R 블루투스
+ 펌프 비밀번호 (v1 전용)
+ 펌프 비밀번호
+ 200%%이상 주입 위해 확장 Bolus 사용
+ Bolus 속도
+ 선택된 펌프
+ 주사기 교체 기록
+ 히스토리에서 발견될 때 \"인슐린 교체\"를 실행에서 입력
+ Canula 변경 기록
+ 히스토리에서 발견될 때 \"인슐린 교체\"를 실행에서 입력
+ PIN1
+ PIN2
+ 펌프\n에 있는 OK을 누르고 2개의 표시된 번호\n를 입력하는 동안 빼기 버튼을 눌러 화면이 꺼지지 않게 합니다.
+ 1: (12자리)
+ 2: (8자리)
+
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/build.gradle b/danar/build.gradle
index 09899f5540..230038a50c 100644
--- a/danar/build.gradle
+++ b/danar/build.gradle
@@ -6,13 +6,7 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':core')
diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt
index 0cd213a56a..cff117939c 100644
--- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt
+++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt
@@ -1,6 +1,7 @@
package info.nightscout.androidaps.danaRv2.comm
import dagger.android.HasAndroidInjector
+import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.danar.comm.MessageBase
import info.nightscout.androidaps.events.EventPumpStatusChanged
@@ -69,7 +70,7 @@ class MsgHistoryEvents_v2 constructor(
val param2 = intFromBuff(bytes, 9, 2)
val status: String
when (recordCode.toInt()) {
- info.nightscout.androidaps.dana.DanaPump.TEMPSTART -> {
+ DanaPump.TEMPSTART -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min")
val temporaryBasalInfo = temporaryBasalStorage.findTemporaryBasal(datetime, param1.toDouble())
pumpSync.syncTemporaryBasalWithPumpId(
@@ -84,7 +85,7 @@ class MsgHistoryEvents_v2 constructor(
status = "TEMPSTART " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.TEMPSTOP -> {
+ DanaPump.TEMPSTOP -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime))
pumpSync.syncStopTemporaryBasalWithPumpId(
timestamp = datetime,
@@ -94,7 +95,7 @@ class MsgHistoryEvents_v2 constructor(
status = "TEMPSTOP " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.EXTENDEDSTART -> {
+ DanaPump.EXTENDEDSTART -> {
val newRecord = pumpSync.syncExtendedBolusWithPumpId(
timestamp = datetime,
amount = param1 / 100.0,
@@ -107,7 +108,7 @@ class MsgHistoryEvents_v2 constructor(
status = "EXTENDEDSTART " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.EXTENDEDSTOP -> {
+ DanaPump.EXTENDEDSTOP -> {
val newRecord = pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = datetime,
endPumpId = datetime,
@@ -117,7 +118,7 @@ class MsgHistoryEvents_v2 constructor(
status = "EXTENDEDSTOP " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.BOLUS -> {
+ DanaPump.BOLUS -> {
val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0)
val newRecord = pumpSync.syncBolusWithPumpId(
timestamp = datetime,
@@ -130,7 +131,7 @@ class MsgHistoryEvents_v2 constructor(
status = "BOLUS " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.DUALBOLUS -> {
+ DanaPump.DUALBOLUS -> {
val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0)
val newRecord = pumpSync.syncBolusWithPumpId(
timestamp = datetime,
@@ -143,7 +144,7 @@ class MsgHistoryEvents_v2 constructor(
status = "DUALBOLUS " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.DUALEXTENDEDSTART -> {
+ DanaPump.DUALEXTENDEDSTART -> {
val newRecord = pumpSync.syncExtendedBolusWithPumpId(
timestamp = datetime,
amount = param1 / 100.0,
@@ -156,7 +157,7 @@ class MsgHistoryEvents_v2 constructor(
status = "DUALEXTENDEDSTART " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.DUALEXTENDEDSTOP -> {
+ DanaPump.DUALEXTENDEDSTOP -> {
val newRecord = pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = datetime,
endPumpId = datetime,
@@ -166,32 +167,32 @@ class MsgHistoryEvents_v2 constructor(
status = "DUALEXTENDEDSTOP " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.SUSPENDON -> {
+ DanaPump.SUSPENDON -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDON (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")")
status = "SUSPENDON " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.SUSPENDOFF -> {
+ DanaPump.SUSPENDOFF -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDOFF (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")")
status = "SUSPENDOFF " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.REFILL -> {
+ DanaPump.REFILL -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT REFILL (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
status = "REFILL " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.PRIME -> {
+ DanaPump.PRIME -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PRIME (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
status = "PRIME " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.PROFILECHANGE -> {
+ DanaPump.PROFILECHANGE -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PROFILECHANGE (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h")
status = "PROFILECHANGE " + dateUtil.timeString(datetime)
}
- info.nightscout.androidaps.dana.DanaPump.CARBS -> {
+ DanaPump.CARBS -> {
val newRecord = pumpSync.syncCarbsWithTimestamp(
timestamp = datetime,
amount = param1.toDouble(),
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/main/java/info/nightscout/androidaps/danar/comm/MsgStatusBolusExtended.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusBolusExtended.kt
index 6795b472ef..49b813c87d 100644
--- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusBolusExtended.kt
+++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgStatusBolusExtended.kt
@@ -52,6 +52,6 @@ class MsgStatusBolusExtended(
return (floor(System.currentTimeMillis() / 1000.0) - tempBasalAgoSecs).toLong() * 1000
}
- // because there is no fixed timestamp of start allow update of tbr only if tbr start differs more
- private fun isWithin3Sec(newStart: Long) = abs(newStart - danaPump.tempBasalStart) < 3000
+ // because there is no fixed timestamp of start allow update of eb only if tbr start differs more
+ private fun isWithin3Sec(newStart: Long) = abs(newStart - danaPump.extendedBolusStart) < 3000
}
\ No newline at end of file
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/build.gradle b/danars/build.gradle
index 9ac3aa3f9a..a013ae98af 100644
--- a/danars/build.gradle
+++ b/danars/build.gradle
@@ -6,13 +6,12 @@ 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"
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
android {
ndkVersion "21.1.6352462"
defaultConfig {
- versionCode 1
- versionName "1.0"
ndk {
moduleName "BleCommandUtil"
diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt
index fdd97c7a4a..ffe87ed77b 100644
--- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt
+++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt
@@ -9,13 +9,15 @@ import android.text.format.DateFormat
import androidx.preference.Preference
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.dana.DanaPump
+import info.nightscout.androidaps.dana.comm.RecordTypes
import info.nightscout.androidaps.danars.events.EventDanaRSDeviceChange
import info.nightscout.androidaps.danars.services.DanaRSService
import info.nightscout.androidaps.data.DetailedBolusInfo
-import info.nightscout.androidaps.interfaces.Profile
import info.nightscout.androidaps.data.PumpEnactResult
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
@@ -31,8 +33,6 @@ import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalSt
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType
import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.T.Companion.mins
-import info.nightscout.androidaps.extensions.convertedToAbsolute
-import info.nightscout.androidaps.extensions.plannedRemainingMinutes
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.sharedPreferences.SP
@@ -622,7 +622,7 @@ class DanaRSPlugin @Inject constructor(
}
override val isFakingTempsByExtendedBoluses: Boolean = false
- override fun loadTDDs(): PumpEnactResult = loadHistory(info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_DAILY)
+ override fun loadTDDs(): PumpEnactResult = loadHistory(RecordTypes.RECORD_TYPE_DAILY)
override fun canHandleDST(): Boolean = false
override fun clearPairing() {
sp.remove(resourceHelper.gs(R.string.key_danars_pairingkey) + mDeviceName)
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/DanaRSPacket.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacket.kt
new file mode 100644
index 0000000000..918bb78207
--- /dev/null
+++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacket.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 DanaRSPacket(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 val friendlyName: 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/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 73%
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..dbfbf8dc6f 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
@@ -118,14 +118,13 @@ open class DanaRS_Packet_APS_History_Events(
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) {
@@ -138,9 +137,9 @@ open class DanaRS_Packet_APS_History_Events(
isAbsolute = false,
type = temporaryBasalInfo?.type,
pumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -148,9 +147,9 @@ open class DanaRS_Packet_APS_History_Events(
val newRecord = pumpSync.syncStopTemporaryBasalWithPumpId(
timestamp = datetime,
endPumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -161,9 +160,9 @@ open class DanaRS_Packet_APS_History_Events(
duration = T.mins(param2.toLong()).msecs(),
isEmulatingTB = false,
pumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -171,9 +170,9 @@ open class DanaRS_Packet_APS_History_Events(
val newRecord = pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = datetime,
endPumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -184,9 +183,9 @@ open class DanaRS_Packet_APS_History_Events(
amount = param1 / 100.0,
type = detailedBolusInfo?.bolusType,
pumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -197,9 +196,9 @@ open class DanaRS_Packet_APS_History_Events(
amount = param1 / 100.0,
type = detailedBolusInfo?.bolusType,
pumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -210,9 +209,9 @@ open class DanaRS_Packet_APS_History_Events(
duration = T.mins(param2.toLong()).msecs(),
isEmulatingTB = false,
pumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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)
}
@@ -220,19 +219,19 @@ open class DanaRS_Packet_APS_History_Events(
val newRecord = pumpSync.syncStopExtendedBolusWithPumpId(
timestamp = datetime,
endPumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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 DanaRS_Packet_APS_History_Events(
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)
}
@@ -265,9 +264,9 @@ open class DanaRS_Packet_APS_History_Events(
timestamp = datetime,
amount = param1.toDouble(),
pumpId = pumpId,
- pumpType = PumpType.DANA_RS,
+ pumpType = danaPump.pumpType(),
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 DanaRS_Packet_APS_History_Events(
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)
}
}
@@ -300,7 +299,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 87%
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..ccaa4b23fd 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
@@ -27,7 +27,7 @@ class DanaRS_Packet_Option_Get_Pump_Time(
val sec = byteArrayToInt(getBytes(data, DATA_START + 5, 1))
val time = DateTime(2000 + year, month, day, hour, min, sec)
danaPump.setPumpTime(time.millis)
- aapsLogger.debug(LTag.PUMPCOMM, "Pump time " + dateUtil.dateAndTimeString(time.millis))
+ aapsLogger.debug(LTag.PUMPCOMM, "Pump time " + dateUtil.dateAndTimeAndSecondsString(time.millis))
}
override fun handleMessageNotReceived() {
@@ -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 84%
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..d8c5d5fbc8 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
@@ -28,7 +28,7 @@ class DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(
val zoneOffset = getBytes(data, DATA_START + 6, 1)[0].toInt()
val time = DateTime(2000 + year, month, day, hour, min, sec)
danaPump.setPumpTime(time.millis, zoneOffset)
- aapsLogger.debug(LTag.PUMPCOMM, "Pump time ${dateUtil.dateAndTimeString(danaPump.getPumpTime())} ZoneOffset: $zoneOffset")
+ aapsLogger.debug(LTag.PUMPCOMM, "Pump time ${dateUtil.dateAndTimeAndSecondsString(danaPump.getPumpTime())} ZoneOffset: $zoneOffset")
}
override fun handleMessageNotReceived() {
@@ -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 85%
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..8b14ee9085 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,16 +5,16 @@ 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
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME
- aapsLogger.debug(LTag.PUMPCOMM, "Setting pump time " + dateUtil.dateAndTimeString(time))
+ aapsLogger.debug(LTag.PUMPCOMM, "Setting pump time " + dateUtil.dateAndTimeAndSecondsString(time))
}
override fun getRequestParams(): ByteArray {
@@ -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 84%
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..5e34f81f41 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,17 +6,17 @@ 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
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_OPTION__SET_PUMP_UTC_AND_TIME_ZONE
- aapsLogger.debug(LTag.PUMPCOMM, "Setting UTC pump time ${dateUtil.dateAndTimeString(time)} ZoneOffset: $zoneOffset")
+ aapsLogger.debug(LTag.PUMPCOMM, "Setting UTC pump time ${dateUtil.dateAndTimeAndSecondsString(time)} ZoneOffset: $zoneOffset")
}
override fun getRequestParams(): ByteArray {
@@ -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.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_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 61c506d835..15dca9e37a 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,12 +12,14 @@ 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
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,10 +62,12 @@ 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
- 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
@@ -124,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)
@@ -140,6 +143,27 @@ class BLEComm @Inject internal constructor(
fun disconnect(from: String) {
aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from")
+ if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_BLE5) {
+ // there was no response from pump after started encryption
+ // assume pairing keys are invalid
+ val lastClearRequest = sp.getLong(R.string.key_rs_last_clear_key_request, 0)
+ if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) {
+ ToastUtils.showToastInUiThread(context, R.string.invalidpairing)
+ danaRSPlugin.changePump()
+ sp.getStringOrNull(R.string.key_danars_address, null)?.let { address ->
+ bluetoothAdapter?.getRemoteDevice(address)?.let { device ->
+ try {
+ device::class.java.getMethod("removeBond").invoke(device)
+ } catch (e: Exception) {
+ aapsLogger.error("Removing bond has been failed. ${e.message}")
+ }
+ }
+ }
+ } else if (lastClearRequest == 0L) {
+ aapsLogger.error("Clearing pairing keys postponed")
+ sp.putLong(R.string.key_rs_last_clear_key_request, dateUtil.now())
+ }
+ }
if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_RSv3) {
// there was no response from pump after started encryption
// assume pairing keys are invalid
@@ -174,6 +198,30 @@ class BLEComm @Inject internal constructor(
}
@Synchronized fun close() {
+ /*
+ if (!encryptedDataRead && !encryptedCommandSent) {
+ // there was no response from pump before started encryption
+ // assume pairing is invalid
+ val lastClearRequest = sp.getLong(R.string.key_rs_last_clear_key_request, 0)
+ if (lastClearRequest != 0L && dateUtil.isOlderThan(lastClearRequest, 5)) {
+ ToastUtils.showToastInUiThread(context, R.string.invalidpairing)
+ danaRSPlugin.changePump()
+ sp.getStringOrNull(R.string.key_danars_address, null)?.let { address ->
+ bluetoothAdapter?.getRemoteDevice(address)?.let { device ->
+ try {
+ aapsLogger.debug(LTag.PUMPBTCOMM, "Removing bond")
+ device::class.java.getMethod("removeBond").invoke(device)
+ } catch (e: Exception) {
+ aapsLogger.error("Removing bond has been failed. ${e.message}")
+ }
+ }
+ }
+ } else if (lastClearRequest == 0L) {
+ aapsLogger.error("Clearing pairing keys postponed")
+ sp.putLong(R.string.key_rs_last_clear_key_request, dateUtil.now())
+ }
+ }
+ */
aapsLogger.debug(LTag.PUMPBTCOMM, "BluetoothAdapter close")
bluetoothGatt?.close()
bluetoothGatt = null
@@ -327,12 +375,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 +387,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 +406,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 +418,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 +454,9 @@ class BLEComm @Inject internal constructor(
bufferLength -= length + 7
// now we have encrypted packet in inputBuffer
- //aapsLogger.debug(LTag.PUMPBTCOMM, "<<<<< PROCESSING: " + DanaRS_Packet.toHexString(inputBuffer))
// decrypt the packet
- bleEncryption.getDecryptedPacket(inputBuffer)?.let { decryptedBuffer ->
+ val decrypted = bleEncryption.getDecryptedPacket(inputBuffer)
+ decrypted?.let { decryptedBuffer ->
if (decryptedBuffer[0] == BleEncryption.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE.toByte()) {
when (decryptedBuffer[1]) {
// 1st packet exchange
@@ -450,8 +490,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
@@ -473,7 +514,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)
}
@@ -482,7 +523,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
@@ -505,11 +546,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()
}
@@ -520,17 +561,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)
@@ -538,12 +579,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()
@@ -554,15 +595,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
@@ -593,20 +634,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
@@ -654,7 +695,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)
}
@@ -664,7 +705,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)
}
@@ -683,7 +724,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")
}
@@ -691,14 +732,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
@@ -718,12 +759,16 @@ 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.requestParams
- aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> " + message.friendlyName + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params))
+ val params = message.getRequestParams()
+ if (bluetoothGatt == null) {
+ aapsLogger.debug(LTag.PUMPBTCOMM, ">>>>> IGNORING (NOT CONNECTED) " + message.friendlyName + " " + DanaRSPacket.toHexString(command) + " " + DanaRSPacket.toHexString(params))
+ return
+ }
+ 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)
@@ -786,16 +831,16 @@ class BLEComm @Inject internal constructor(
aapsLogger.warn(LTag.PUMPBTCOMM, "Reply not received " + message.friendlyName)
message.handleMessageNotReceived()
}
- // verify encryption for v3
- if (message is DanaRS_Packet_Etc_Keep_Connection)
+ // verify encryption for v3 & BLE
+ 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 {
@@ -803,7 +848,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.friendlyName + " " + DanaRSPacket.toHexString(decryptedBuffer))
// process received data
message.handleMessage(decryptedBuffer)
message.setReceived()
@@ -811,7 +856,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..d98579bd21 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 & BLE
+ 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()))
+ danaPump.protocol >= 5 -> { // can set seconds
+ 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/main/jniLibs/arm64-v8a/libBleEncryption.so b/danars/src/main/jniLibs/arm64-v8a/libBleEncryption.so
index 7c0c49b7e8..baf9014328 100644
Binary files a/danars/src/main/jniLibs/arm64-v8a/libBleEncryption.so and b/danars/src/main/jniLibs/arm64-v8a/libBleEncryption.so differ
diff --git a/danars/src/main/jniLibs/armeabi-v7a/libBleEncryption.so b/danars/src/main/jniLibs/armeabi-v7a/libBleEncryption.so
index 4778aca663..f5daf1449d 100644
Binary files a/danars/src/main/jniLibs/armeabi-v7a/libBleEncryption.so and b/danars/src/main/jniLibs/armeabi-v7a/libBleEncryption.so differ
diff --git a/danars/src/main/jniLibs/x86/libBleEncryption.so b/danars/src/main/jniLibs/x86/libBleEncryption.so
index e5ef3a17a4..b63dd5a234 100644
Binary files a/danars/src/main/jniLibs/x86/libBleEncryption.so and b/danars/src/main/jniLibs/x86/libBleEncryption.so differ
diff --git a/danars/src/main/jniLibs/x86_64/libBleEncryption.so b/danars/src/main/jniLibs/x86_64/libBleEncryption.so
index e4c02d8842..871e79aad5 100644
Binary files a/danars/src/main/jniLibs/x86_64/libBleEncryption.so and b/danars/src/main/jniLibs/x86_64/libBleEncryption.so differ
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/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 98c90be4ac..1fa4f4c7ee 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
@@ -2,12 +2,13 @@ package info.nightscout.androidaps.danars.comm
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
+import info.nightscout.androidaps.dana.DanaPump
+import info.nightscout.androidaps.danars.DanaRSTestBase
import info.nightscout.androidaps.danars.encryption.BleEncryption
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
-import info.nightscout.androidaps.danars.DanaRSTestBase
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@@ -26,17 +27,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 +48,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)
- Assert.assertEquals(BleEncryption.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY.toLong(), testPacket.getOpCode().toLong())
+ val forTesting: DanaRSPacket = DanaRSPacketAPSSetEventHistory(packetInjector, 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())
diff --git a/database/build.gradle b/database/build.gradle
index f408159e29..951064cb47 100644
--- a/database/build.gradle
+++ b/database/build.gradle
@@ -7,8 +7,6 @@ apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle"
android {
defaultConfig {
- versionCode 1
- versionName "1.0"
kapt {
arguments {
arg("room.incremental", "true")
diff --git a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt
index da7449f887..11754adf03 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/AppRepository.kt
@@ -213,6 +213,11 @@ open class AppRepository @Inject internal constructor(
return null
}
+ fun getPermanentProfileSwitch(timestamp: Long): ProfileSwitch? =
+ database.profileSwitchDao.getPermanentProfileSwitchActiveAt(timestamp)
+ .subscribeOn(Schedulers.io())
+ .blockingGet()
+
fun getAllProfileSwitches(): Single> =
database.profileSwitchDao.getAllProfileSwitches()
.subscribeOn(Schedulers.io())
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")
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/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/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusCalculatorResultTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusCalculatorResultTransaction.kt
index da50ce0a55..b824e1b4f4 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusCalculatorResultTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusCalculatorResultTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdBolusCalculatorResultTransaction(val bolusCalculatorResult: Bolu
override fun run() {
val current = database.bolusCalculatorResultDao.findById(bolusCalculatorResult.id)
- if (current != null && current.interfaceIDs.nightscoutId != bolusCalculatorResult.interfaceIDs.nightscoutId)
- database.bolusCalculatorResultDao.updateExistingEntry(bolusCalculatorResult)
+ if (current != null && current.interfaceIDs.nightscoutId != bolusCalculatorResult.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = bolusCalculatorResult.interfaceIDs.nightscoutId
+ database.bolusCalculatorResultDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusTransaction.kt
index a6e0a574ff..2504545419 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdBolusTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdBolusTransaction(val bolus: Bolus) : Transaction() {
override fun run() {
val current = database.bolusDao.findById(bolus.id)
- if (current != null && current.interfaceIDs.nightscoutId != bolus.interfaceIDs.nightscoutId)
- database.bolusDao.updateExistingEntry(bolus)
+ if (current != null && current.interfaceIDs.nightscoutId != bolus.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = bolus.interfaceIDs.nightscoutId
+ database.bolusDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdCarbsTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdCarbsTransaction.kt
index 2cba4540f9..9595fd3a17 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdCarbsTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdCarbsTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdCarbsTransaction(val carbs: Carbs) : Transaction() {
override fun run() {
val current = database.carbsDao.findById(carbs.id)
- if (current != null && current.interfaceIDs.nightscoutId != carbs.interfaceIDs.nightscoutId)
- database.carbsDao.updateExistingEntry(carbs)
+ if (current != null && current.interfaceIDs.nightscoutId != carbs.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = carbs.interfaceIDs.nightscoutId
+ database.carbsDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdDeviceStatusTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdDeviceStatusTransaction.kt
index 766f672877..159992ba5f 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdDeviceStatusTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdDeviceStatusTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdDeviceStatusTransaction(val deviceStatus: DeviceStatus) : Transa
override fun run() {
val current = database.deviceStatusDao.findById(deviceStatus.id)
- if (current != null && current.interfaceIDs.nightscoutId != deviceStatus.interfaceIDs.nightscoutId)
- database.deviceStatusDao.update(deviceStatus)
+ if (current != null && current.interfaceIDs.nightscoutId != deviceStatus.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = deviceStatus.interfaceIDs.nightscoutId
+ database.deviceStatusDao.update(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdExtendedBolusTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdExtendedBolusTransaction.kt
index cfa12027b1..cc174ad734 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdExtendedBolusTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdExtendedBolusTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdExtendedBolusTransaction(val bolus: ExtendedBolus) : Transaction
override fun run() {
val current = database.extendedBolusDao.findById(bolus.id)
- if (current != null && current.interfaceIDs.nightscoutId != bolus.interfaceIDs.nightscoutId)
- database.extendedBolusDao.updateExistingEntry(bolus)
+ if (current != null && current.interfaceIDs.nightscoutId != bolus.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = bolus.interfaceIDs.nightscoutId
+ database.extendedBolusDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdFoodTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdFoodTransaction.kt
index e03e38e343..78179c8cb8 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdFoodTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdFoodTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdFoodTransaction(val food: Food) : Transaction() {
override fun run() {
val current = database.foodDao.findById(food.id)
- if (current != null && current.interfaceIDs.nightscoutId != food.interfaceIDs.nightscoutId)
- database.foodDao.updateExistingEntry(food)
+ if (current != null && current.interfaceIDs.nightscoutId != food.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = food.interfaceIDs.nightscoutId
+ database.foodDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdGlucoseValueTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdGlucoseValueTransaction.kt
index 954aadd39b..3b43b92943 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdGlucoseValueTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdGlucoseValueTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdGlucoseValueTransaction(val glucoseValue: GlucoseValue) : Transa
override fun run() {
val current = database.glucoseValueDao.findById(glucoseValue.id)
- if (current != null && current.interfaceIDs.nightscoutId != glucoseValue.interfaceIDs.nightscoutId)
- database.glucoseValueDao.updateExistingEntry(glucoseValue)
+ if (current != null && current.interfaceIDs.nightscoutId != glucoseValue.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = glucoseValue.interfaceIDs.nightscoutId
+ database.glucoseValueDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdOfflineEventTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdOfflineEventTransaction.kt
index ebb19ce486..3da1b26ce7 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdOfflineEventTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdOfflineEventTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdOfflineEventTransaction(val offlineEvent: OfflineEvent) : Transa
override fun run() {
val current = database.offlineEventDao.findById(offlineEvent.id)
- if (current != null && current.interfaceIDs.nightscoutId != offlineEvent.interfaceIDs.nightscoutId)
- database.offlineEventDao.updateExistingEntry(offlineEvent)
+ if (current != null && current.interfaceIDs.nightscoutId != offlineEvent.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = offlineEvent.interfaceIDs.nightscoutId
+ database.offlineEventDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdProfileSwitchTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdProfileSwitchTransaction.kt
index 63a589db51..368a66dc3f 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdProfileSwitchTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdProfileSwitchTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdProfileSwitchTransaction(val profileSwitch: ProfileSwitch) : Tra
override fun run() {
val current = database.profileSwitchDao.findById(profileSwitch.id)
- if (current != null && current.interfaceIDs.nightscoutId != profileSwitch.interfaceIDs.nightscoutId)
- database.profileSwitchDao.updateExistingEntry(profileSwitch)
+ if (current != null && current.interfaceIDs.nightscoutId != profileSwitch.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = profileSwitch.interfaceIDs.nightscoutId
+ database.profileSwitchDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryBasalTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryBasalTransaction.kt
index be9a3c3efa..571f3da027 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryBasalTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryBasalTransaction.kt
@@ -2,11 +2,13 @@ package info.nightscout.androidaps.database.transactions
import info.nightscout.androidaps.database.entities.TemporaryBasal
-class UpdateNsIdTemporaryBasalTransaction(val bolus: TemporaryBasal) : Transaction() {
+class UpdateNsIdTemporaryBasalTransaction(val temporaryBasal: TemporaryBasal) : Transaction() {
override fun run() {
- val current = database.temporaryBasalDao.findById(bolus.id)
- if (current != null && current.interfaceIDs.nightscoutId != bolus.interfaceIDs.nightscoutId)
- database.temporaryBasalDao.updateExistingEntry(bolus)
+ val current = database.temporaryBasalDao.findById(temporaryBasal.id)
+ if (current != null && current.interfaceIDs.nightscoutId != temporaryBasal.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = temporaryBasal.interfaceIDs.nightscoutId
+ database.temporaryBasalDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryTargetTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryTargetTransaction.kt
index 419fba854d..28bd4211d6 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryTargetTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTemporaryTargetTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdTemporaryTargetTransaction(val temporaryTarget: TemporaryTarget)
override fun run() {
val current = database.temporaryTargetDao.findById(temporaryTarget.id)
- if (current != null && current.interfaceIDs.nightscoutId != temporaryTarget.interfaceIDs.nightscoutId)
- database.temporaryTargetDao.updateExistingEntry(temporaryTarget)
+ if (current != null && current.interfaceIDs.nightscoutId != temporaryTarget.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = temporaryTarget.interfaceIDs.nightscoutId
+ database.temporaryTargetDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTherapyEventTransaction.kt b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTherapyEventTransaction.kt
index 680fbe7ca3..0f04c6f81d 100644
--- a/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTherapyEventTransaction.kt
+++ b/database/src/main/java/info/nightscout/androidaps/database/transactions/UpdateNsIdTherapyEventTransaction.kt
@@ -6,7 +6,9 @@ class UpdateNsIdTherapyEventTransaction(val therapyEvent: TherapyEvent) : Transa
override fun run() {
val current = database.therapyEventDao.findById(therapyEvent.id)
- if (current != null && current.interfaceIDs.nightscoutId != therapyEvent.interfaceIDs.nightscoutId)
- database.therapyEventDao.updateExistingEntry(therapyEvent)
+ if (current != null && current.interfaceIDs.nightscoutId != therapyEvent.interfaceIDs.nightscoutId) {
+ current.interfaceIDs.nightscoutId = therapyEvent.interfaceIDs.nightscoutId
+ database.therapyEventDao.updateExistingEntry(current)
+ }
}
}
\ No newline at end of file
diff --git a/diaconn/build.gradle b/diaconn/build.gradle
new file mode 100644
index 0000000000..2b1454339c
--- /dev/null
+++ b/diaconn/build.gradle
@@ -0,0 +1,31 @@
+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"
+apply from: "${project.rootDir}/gradle/jacoco_global.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..0c3ff324d7
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt
@@ -0,0 +1,198 @@
+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 = ""
+ }
+
+ val todayInsulinAmount = (pump.todayBaseAmount + pump.todaySnackAmount + pump.todayMealAmount)
+ val todayInsulinLimitAmount = (pump.maxBasal.toInt() * 24) + pump.maxBolusePerDay.toInt()
+ binding.dailyunits.text = resourceHelper.gs(R.string.reservoirvalue, todayInsulinAmount, todayInsulinLimitAmount)
+ warnColors.setColor(binding.dailyunits, todayInsulinAmount, todayInsulinLimitAmount * 0.75, todayInsulinLimitAmount * 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.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..168c0f3fa5
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt
@@ -0,0 +1,593 @@
+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.resultErrorCode, 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 U for $durationInMinutes mins (doLowTemp || doHighTemp)")
+ val connectionOK: Boolean = if (durationInMinutes == 15 || durationInMinutes == 30) {
+ diaconnG8Service?.tempBasalShortDuration(absoluteAfterConstrain, durationInMinutes) ?: false
+ } else {
+ val durationInHours = max(durationInMinutes / 60.0, 1.0)
+ 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
+ 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.resultErrorCode, 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
+ if(!result.success) setErrorMsg(diaconnG8Pump.resultErrorCode, result)
+ } 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
+ if(!result.success) {
+ setErrorMsg(diaconnG8Pump.resultErrorCode, result)
+ diaconnG8Service?.readPumpStatus()
+ }
+
+ } 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)
+ 32 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_32)
+ 33 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_33)
+ 34 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_34)
+ 35 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_35)
+ 36 -> result.comment = resourceHelper.gs(R.string.diaconn_g8_errorcode_36)
+ 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..77739cf9e9
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Pump.kt
@@ -0,0 +1,374 @@
+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
+
+
+ /*
+ * TEMP BASALS
+ */
+ var tempBasalStart: Long = 0
+ var tempBasalDuration: Long = 0 // in milliseconds
+ var tempBasalAbsoluteRate: Double = 0.0
+ var tempBasalPercent: Int = 0
+
+ var tempBasalTotalSec: Long
+ set(durationInSec) {
+ tempBasalDuration = T.secs(durationInSec).msecs()
+ }
+ get() = T.msecs(tempBasalDuration).mins()
+ var isTempBasalInProgress: Boolean
+ get() = tempBasalStart != 0L && dateUtil.now() in tempBasalStart..tempBasalStart + tempBasalDuration
+ set(isRunning) {
+ if (isRunning) throw IllegalArgumentException("Use to cancel TBR only")
+ else {
+ tempBasalStart = 0L
+ tempBasalDuration = 0L
+ tempBasalAbsoluteRate = 0.0
+ }
+ }
+ val tempBasalRemainingMin: Int
+ get() = max(T.msecs(tempBasalStart + tempBasalDuration - dateUtil.now()).mins().toInt(), 0)
+
+ fun temporaryBasalToString(): String {
+ if (!isTempBasalInProgress) return ""
+
+ val passedMin = ((min(dateUtil.now(), tempBasalStart + tempBasalDuration) - tempBasalStart) / 60.0 / 1000).roundToInt()
+ return tempBasalAbsoluteRate.toString() + "U/h @" +
+ dateUtil.timeString(tempBasalStart) +
+ " " + passedMin + "/" + 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
+ get() = extendedBolusStart != 0L && dateUtil.now() in extendedBolusStart..extendedBolusStart + extendedBolusDuration
+ set(isRunning) {
+ if (isRunning) throw IllegalArgumentException("Use to cancel EB only")
+ else {
+ extendedBolusStart = 0L
+ extendedBolusDuration = 0L
+ extendedBolusAmount = 0.0
+ }
+ }
+ val extendedBolusPassedMinutes:Int
+ get() = T.msecs(max(0, dateUtil.now() - extendedBolusStart)).mins().toInt()
+ val extendedBolusRemainingMinutes: Int
+ get() = max(T.msecs(extendedBolusStart + extendedBolusDuration - dateUtil.now()).mins().toInt(), 0)
+ private val extendedBolusDurationInMinutes: Int
+ get() = T.msecs(extendedBolusDuration).mins().toInt()
+
+ var extendedBolusAbsoluteRate: Double
+ get() = extendedBolusAmount * T.hours(1).msecs() / extendedBolusDuration
+ set(rate) {
+ extendedBolusAmount = rate * extendedBolusDuration / T.hours(1).msecs()
+ }
+
+ fun extendedBolusToString(): String {
+ if (!isExtendedInProgress) return ""
+ //return "E "+ DecimalFormatter.to2Decimal(extendedBolusDeliveredSoFar) +"/" + DecimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" +
+ // " " + extendedBolusPassedMinutes + "/" + extendedBolusMinutes + "'"
+ return "E "+ DecimalFormatter.to2Decimal(extendedBolusAbsoluteRate) + "U/h @" +
+ dateUtil.timeString(extendedBolusStart) +
+ " " + extendedBolusPassedMinutes + "/" + extendedBolusDurationInMinutes + "'"
+ }
+
+ 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
+
+ var resultErrorCode: Int = 0 // last start bolus erroCode
+
+ // Bolus settings
+ 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
+
+ // LGS Status
+ var lgsStatus: Int = 0 // LGS Status(1=LGS_ON, 2=LGS_OFF)
+ var lgsTime:Int = 0 // LGS Setting time (0~255 min)
+ var lgsElapsedTime:Int = 0 // LGS Passed Time (0~255 min)
+
+ 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 // 임시기저 상태 (1 : running, 2:not running )
+ 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..8a661ed7a7
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/di/DiaconnG8PacketModule.kt
@@ -0,0 +1,83 @@
+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
+ @ContributesAndroidInjector abstract fun contributesBigAPSMainInfoInquirePacket(): BigAPSMainInfoInquirePacket
+ @ContributesAndroidInjector abstract fun contributesBigAPSMainInfoInquireResponsePacket(): BigAPSMainInfoInquireResponsePacket
+
+
+
+}
\ 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..97f2e09403
--- /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.resultErrorCode = 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..f54fc49d4a
--- /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.resultErrorCode = 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..5ec73cbe3c
--- /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.resultErrorCode = 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..d7902d76f9
--- /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.resultErrorCode = 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/BigAPSMainInfoInquirePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquirePacket.kt
new file mode 100644
index 0000000000..7f7fb4b343
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquirePacket.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
+
+/**
+
+ * BigAPSMainInfoInquirePacket
+ */
+class BigAPSMainInfoInquirePacket(
+ injector: HasAndroidInjector
+) : DiaconnG8Packet(injector ) {
+
+ @Inject lateinit var diaconnG8Pump: DiaconnG8Pump
+
+ init {
+ msgType = 0x54
+ aapsLogger.debug(LTag.PUMPCOMM, "BigAPSMainInfoInquirePacket 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_APS_MAIN_INFO_INQUIRE"
+ }
+}
\ No newline at end of file
diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt
new file mode 100644
index 0000000000..5b56b512df
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt
@@ -0,0 +1,335 @@
+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
+
+/**
+ * BigAPSMainInfoInquireResponsePacket
+ */
+class BigAPSMainInfoInquireResponsePacket(
+ 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 = 0x94.toByte()
+ aapsLogger.debug(LTag.PUMPCOMM, "BigAPSMainInfoInquireResponsePacket init")
+ }
+
+ override fun handleMessage(data: ByteArray?) {
+ val result = defect(data)
+ if (result != 0) {
+ aapsLogger.debug(LTag.PUMPCOMM, "BigAPSMainInfoInquireResponsePacket 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)
+
+ // save current pump firmware version
+ 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) // bolus speed (1~8)
+
+ // 7. Tempbasal status
+ diaconnG8Pump.tbStatus = getByteToInt(bufferData) // tempbasal status
+ diaconnG8Pump.tbTime = getByteToInt(bufferData) // tempbasal durationn
+ diaconnG8Pump.tbInjectRateRatio = getShortToInt(bufferData) //rate/percent
+ diaconnG8Pump.tbElapsedTime = getShortToInt(bufferData) // tempbasal elapsed time(0~1425 min)
+
+ // 8. Basal status
+ diaconnG8Pump.baseStatus = getByteToInt(bufferData) // 기저주입 상태
+ diaconnG8Pump.baseHour = getByteToInt(bufferData) // 현재 주입시간
+ diaconnG8Pump.baseAmount = getShortToInt(bufferData) / 100.0 // 주입설정량
+ diaconnG8Pump.baseInjAmount = getShortToInt(bufferData) / 100.0 // 현재 주입량
+
+ // 9. snack bolus status
+ diaconnG8Pump.snackStatus = getByteToInt(bufferData) //주입상태
+ diaconnG8Pump.snackAmount = getShortToInt(bufferData) / 100.0 // 주입설정량
+ diaconnG8Pump.snackInjAmount = getShortToInt(bufferData) / 100.0 // 현재주입량
+ diaconnG8Pump.snackSpeed = getByteToInt(bufferData) //주입속도
+
+ // 10. 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 // 현재 주입량
+
+ // 11. 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 // 스퀘어주입량
+
+ // 12. 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 주입량
+
+ // 13. daily injection status
+ diaconnG8Pump.todayBaseAmount = getShortToInt(bufferData) / 100.0 // 기저주입 총량
+ diaconnG8Pump.todayMealAmount = getShortToInt(bufferData) / 100.0 // 식사주입 총량
+ diaconnG8Pump.todaySnackAmount = getShortToInt(bufferData) / 100.0 // 회식주입 총량
+
+ // 14. 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)
+
+ // 15. 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)
+
+ // 16. 1hour basal limit
+ diaconnG8Pump.maxBasalPerHours = getShortToInt(bufferData).toDouble() / 100.0 // not include tempbasal limit
+ diaconnG8Pump.maxBasal = diaconnG8Pump.maxBasalPerHours * 2 // include tempbasal
+
+ // 17. snack limit
+ diaconnG8Pump.maxBolus = getShortToInt(bufferData).toDouble() / 100
+ diaconnG8Pump.maxBolusePerDay = getShortToInt(bufferData).toDouble() / 100
+
+ // 18. pump sound
+ diaconnG8Pump.beepAndAlarm = getByteToInt(bufferData) -1
+ diaconnG8Pump.alarmIntesity = getByteToInt(bufferData) -1
+
+ // 19. pump light time
+ diaconnG8Pump.lcdOnTimeSec = getByteToInt(bufferData) // kind (1=30 sec, 2=40 sec, 3=50 sec)
+
+ // 20. language
+ diaconnG8Pump.selectedLanguage = getByteToInt(bufferData) // language (1=Chiness, 2=Korean, 3=English)
+
+ // 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.dateAndTimeAndSecondsString(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)
+ aapsLogger.debug(LTag.PUMPCOMM, "maxBasalPerHours > " + diaconnG8Pump.maxBasalPerHours)
+ aapsLogger.debug(LTag.PUMPCOMM, "maxBasal > " + diaconnG8Pump.maxBasal)
+ aapsLogger.debug(LTag.PUMPCOMM, "maxBolus > " + diaconnG8Pump.maxBolus)
+ aapsLogger.debug(LTag.PUMPCOMM, "maxBolusePerDay > " + diaconnG8Pump.maxBolusePerDay)
+ aapsLogger.debug(LTag.PUMPCOMM, "beepAndAlarm > " + diaconnG8Pump.beepAndAlarm)
+ aapsLogger.debug(LTag.PUMPCOMM, "alarmIntesity > " + diaconnG8Pump.alarmIntesity)
+ aapsLogger.debug(LTag.PUMPCOMM, "lcdOnTimeSec > " + diaconnG8Pump.lcdOnTimeSec)
+ aapsLogger.debug(LTag.PUMPCOMM, "selectedLanguage > " + diaconnG8Pump.selectedLanguage)
+ }
+
+ override fun getFriendlyName(): String {
+ return "PUMP_BIG_APS_MAIN_INFO_INQUIRE_RESPONSE"
+ }
+}
\ 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..e75008d66c
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt
@@ -0,0 +1,767 @@
+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 -> {
+ 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")
+
+ diaconnG8Pump.lastBolusAmount = logItem.injectAmount / 100.0
+ diaconnG8Pump.lastBolusTime = logDateTime
+
+ //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
+ 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.injectSquareAmount / 100.0 + "U RealDuration: " + logItem.getInjectTime() + "min")
+
+ 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 = DateTime(logDateTime).withTimeAtStartOfDay().millis
+ 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 = DateTime(logDateTime).withTimeAtStartOfDay().millis
+ 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..42aca3f51e
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt
@@ -0,0 +1,324 @@
+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)
+
+ // 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.dateAndTimeAndSecondsString(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..8a5b22f5da
--- /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.resultErrorCode = 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..922335e612
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8Packet.java
@@ -0,0 +1,320 @@
+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, "Canceled due to the opt number did not match.");
+ 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;
+
+ case 32:
+ aapsLogger.error(LTag.PUMPCOMM, "During LGS running, injection is restricted");
+ break;
+
+ case 33:
+ aapsLogger.error(LTag.PUMPCOMM, "LGS status is ON, ON Command is declined.");
+ break;
+
+ case 34:
+ aapsLogger.error(LTag.PUMPCOMM, "LGS status is OFF, OFF Command is declined.");
+ break;
+
+ case 35:
+ aapsLogger.error(LTag.PUMPCOMM, "Tempbasal start is rejected when tempbasal is running");
+ break;
+
+ case 36:
+ aapsLogger.error(LTag.PUMPCOMM, "Tempbasal stop is rejected when tempbasal is not running");
+ 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..5c6c984e14
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/DiaconnG8ResponseMessageHashTable.kt
@@ -0,0 +1,53 @@
+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(BigAPSMainInfoInquireResponsePacket(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..d3a1aff191
--- /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.resultErrorCode = 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..921b7cfdf8
--- /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.resultErrorCode = 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..b883154ad9
--- /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 {
+ val 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..922198207d
--- /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.resultErrorCode = 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..53f2f6e96e
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt
@@ -0,0 +1,56 @@
+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.squareTime = settingMinutes
+ diaconnG8Pump.squareInjTime = elapsedTime
+ diaconnG8Pump.squareAmount = bolusAmountToBeDelivered
+ diaconnG8Pump.squareInjAmount = deliveredBolusAmount
+
+ aapsLogger.debug(LTag.PUMPCOMM, "Result: $result")
+ aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + diaconnG8Pump.squareAmount + " U/h")
+ aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus duration: " + diaconnG8Pump.squareTime + " min")
+ aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far: " + diaconnG8Pump.squareInjTime + " min")
+ aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus delivered so far: " + diaconnG8Pump.squareInjAmount + " 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..051612ba2c
--- /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.resultErrorCode = 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..802e95985e
--- /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.resultErrorCode = 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..aa60b70c1a
--- /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.resultErrorCode = 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..4a560dd979
--- /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.resultErrorCode = 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..29f5823037
--- /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_LOG_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..fba733ee8c
--- /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.resultErrorCode = 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..2b6d5db384
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/TempBasalInquireResponsePacket.kt
@@ -0,0 +1,55 @@
+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) // 임시기저 경과시간
+
+ 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..d2eec42bcd
--- /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..3ef1cf5668
--- /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.resultErrorCode = 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..75523537f8
--- /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.resultErrorCode = 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..0f2568f832
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/PumplogUtil.java
@@ -0,0 +1,161 @@
+package info.nightscout.androidaps.diaconn.pumplog;
+
+import android.annotation.SuppressLint;
+
+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 날짜 문자열
+ */
+ @SuppressLint("SimpleDateFormat")
+ 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 날짜 문자열
+ */
+ @SuppressLint("SimpleDateFormat")
+ 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..9220e46510
--- /dev/null
+++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt
@@ -0,0 +1,660 @@
+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.diaconn.pumplog.PumplogUtil
+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.StringUtils
+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)))
+
+ val pumpFirmwareVersion = sp.getString(resourceHelper.gs(R.string.pumpversion),"")
+
+ if(!StringUtils.emptyString(pumpFirmwareVersion) && PumplogUtil.isPumpVersionGe(pumpFirmwareVersion, 3, 0)) {
+ sendMessage(BigAPSMainInfoInquirePacket(injector)) // APS Pump Main Info
+ } else {
+ sendMessage(BasalLimitInquirePacket(injector)) // basal Limit
+ sendMessage(SneckLimitInquirePacket(injector)) // bolus Limit
+ sendMessage(BigMainInfoInquirePacket(injector)) // Pump Main Info
+ sendMessage(SoundInquirePacket(injector)) // sounds
+ sendMessage(DisplayTimeInquirePacket(injector)) // display
+ sendMessage(LanguageInquirePacket(injector)) // 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))
+
+ // pump version check
+ if(diaconnG8Pump.isPumpVersionGe2_63) {
+ sendMessage(IncarnationInquirePacket(injector))
+ }
+
+ 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 )
+ // 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)
+ sendMessage(AppConfirmSettingPacket(injector, msg.msgType, diaconnG8Pump.otpNumber))
+ diaconnG8Pump.otpNumber = 0
+ }
+
+ // pump bolus speed inquire
+ sendMessage(BolusSpeedInquirePacket(injector))
+ 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)
+ // 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)
+ // otp process
+ if(!processConfirm(stop.msgType)) return
+ while (!diaconnG8Pump.bolusStopped) {
+ SystemClock.sleep(200)
+ }
+ } else {
+ diaconnG8Pump.bolusStopped = true
+ }
+ }
+
+ fun tempBasal(absoluteRate: Double, durationInHours: Double): Boolean {
+ if (!isConnected) return false
+
+ // temp state check
+ sendMessage(TempBasalInquirePacket(injector))
+
+ if (diaconnG8Pump.tbStatus ==1 ) {
+ rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
+ val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio)
+ // tempbasal stop
+ sendMessage(msgPacket)
+ // 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).toInt(), tbInjectRate)
+ sendMessage(msgTBR)
+ // 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 {
+ // temp state check
+ sendMessage(TempBasalInquirePacket(injector))
+
+ if (diaconnG8Pump.tbStatus ==1 ) {
+ rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
+ val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio)
+ // tempbasal stop
+ sendMessage(msgPacket)
+ // 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)
+ // 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
+ }
+
+ // temp state check
+ sendMessage(TempBasalInquirePacket(injector))
+ if (diaconnG8Pump.tbStatus ==1 ) {
+ rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)))
+ val msgPacket = TempBasalSettingPacket(injector, 2, diaconnG8Pump.tbTime, diaconnG8Pump.tbInjectRateRatio)
+ // tempbasal stop
+ sendMessage(msgPacket)
+ // 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)
+ // 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)))
+ // temp state check
+ sendMessage(TempBasalInquirePacket(injector))
+ if(diaconnG8Pump.tbStatus == 1) {
+ val msgPacket = TempBasalSettingPacket(
+ injector,
+ 2,
+ diaconnG8Pump.tbTime,
+ diaconnG8Pump.tbInjectRateRatio
+ )
+ // tempbasal stop
+ sendMessage(msgPacket)
+ // otp process
+ if (!processConfirm(msgPacket.msgType)) return false
+ SystemClock.sleep(500)
+ }
+
+ loadHistory()
+ val tbr = pumpSync.expectedPumpState().temporaryBasal
+ diaconnG8Pump.fromTemporaryBasal(tbr)
+ rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING))
+ return true
+ }
+
+ 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)
+ // otp process
+ if(!processConfirm(msgExtended.msgType)) return false
+ //diaconnG8Pump.isExtendedInProgress = true
+ 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 msgType = if(diaconnG8Pump.dualStatus == 1) 0x09.toByte() else 0x08.toByte()
+ val msgStop = InjectionCancelSettingPacket(injector, msgType)
+ sendMessage(msgStop)
+ // otp process
+ if(!processConfirm(msgStop.msgType)) return false
+ loadHistory() // pump log sync( db update)
+ 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(requestReqPacket4.msgType)) 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)
+ // 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 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/diaconn/src/main/res/layout/diaconn_g8_history_activity.xml b/diaconn/src/main/res/layout/diaconn_g8_history_activity.xml
new file mode 100644
index 0000000000..e8c0d99923
--- /dev/null
+++ b/diaconn/src/main/res/layout/diaconn_g8_history_activity.xml
@@ -0,0 +1,94 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/diaconn/src/main/res/layout/diaconn_g8_history_item.xml b/diaconn/src/main/res/layout/diaconn_g8_history_item.xml
new file mode 100644
index 0000000000..66ee8536db
--- /dev/null
+++ b/diaconn/src/main/res/layout/diaconn_g8_history_item.xml
@@ -0,0 +1,90 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/diaconn/src/main/res/layout/diaconn_g8_user_options_activity.xml b/diaconn/src/main/res/layout/diaconn_g8_user_options_activity.xml
new file mode 100644
index 0000000000..c652b6516f
--- /dev/null
+++ b/diaconn/src/main/res/layout/diaconn_g8_user_options_activity.xml
@@ -0,0 +1,336 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/diaconn/src/main/res/values-af-rZA/strings.xml b/diaconn/src/main/res/values-af-rZA/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-af-rZA/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-bg-rBG/strings.xml b/diaconn/src/main/res/values-bg-rBG/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-bg-rBG/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-ca-rES/strings.xml b/diaconn/src/main/res/values-ca-rES/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-ca-rES/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-cs-rCZ/strings.xml b/diaconn/src/main/res/values-cs-rCZ/strings.xml
new file mode 100644
index 0000000000..180f2e7f65
--- /dev/null
+++ b/diaconn/src/main/res/values-cs-rCZ/strings.xml
@@ -0,0 +1,100 @@
+
+
+ Zrušit párování
+ Nejsou k dispozici žádná zařízení
+ Párování pumpy Diaconn
+ Chyba pumpy
+ Alarmy
+ Hodinové bazály
+ Bolusy
+ Denní inzulín
+ Chyby
+ Doplňování
+ Plnění
+ Pozastavit
+ Spárováno
+ Čekání na párování
+ Verze
+ Neplatné párovací informace. Spouštění nového párování
+ Nahrávám nastavení pumpy
+ Nahrávám čas v pumpě
+ Velký rozdíl v času:\nČas v pumpě se liší minimálně o 1,5 h.\nProsím upravte čas v pumpě ručně a vymažte historii pumpy.\nPokud je to třeba, pozastavte smyčku alespoň na \"DIA\" hodin.
+ Velký rozdíl v času
+ Blíží se denní limit inzulínu
+ Spouštím bolus
+ Čekání na předpokládaný konec bolusu
+ Nahrávám bolusy
+ Zastavuji dočasný bazál
+ Nastavuji dočasný bazál
+ Nastavuji prodloužený bolus
+ Zastavuji prodloužený bolus
+ Aktualizuji bazály
+ Integrace pumpy pro pumpy Diaconn G8
+ Diakonn G8
+ Diakonn G8
+ Překročen maximální bolus
+ Chyba příkazu
+ Chyba rychlosti
+ Překročen limit inzulínu
+ Požadováno: %1$.2fU Doručeno: %2$.2fU Chyba: %3$s
+ Hodnota nenastavena správně
+ Zařízení Bluetooth Diaconn G8
+ Heslo k pumpě
+ Rychlost bolusu
+ Vybraná pumpa
+ Použít prodloužené bolusy pro >200%%
+ Zobrazovat prodloužený bolus v %%
+ Stav Bluetooth
+ CDD
+ Krok bolusu
+ Krok bazálu
+ Firmware
+ UŽIVATELSKÉ VOLBY
+ Prosím, spárujte pumpu s telefonem!
+ "Zpracovávám Událost "
+ aps_last_log_num
+ aps_wrapping_count
+ Dočasný Bazál
+ Nastavení pumpy Diaconn
+ Zvuk
+ zvuk
+ vibrovat
+ ticho
+ Hlasitost alarmu
+ nízká
+ střední
+ vysoká
+ Čas před vypnutím displeje [second]
+ ULOŽIT VOLBY DO PUMPY
+ Jazyk
+ Rychlost bolusu
+ Čínština
+ Korejština
+ Angličtina
+ "10 "
+ 10
+ 20
+ 30
+ nízká
+ Aplikace zablokována
+ Upozornění na stav baterie
+ Upozornění na nedostatek inzulínu
+ Je vyžadována výměna baterie
+ Je vyžadována výměna inzulínu
+ pump_version
+ aps_incarnation_no
+ pump_serial_no
+ Zaznamenat výměnu zásobníku
+ Přidat událost \"Výměna inzulínu\" do portálu pěče, pokud je zjištěna v historii
+ Zaznamenat změnu jehly
+ Přidat událost \"Výměna setu\" do portálu pěče, pokud je zjištěna v historii
+ Přidat událost \"Výměna baterie\" do portálu pěče, pokud je zjištěna v historii
+ Zaznamenat výměnu baterie
+ Probíhá synchronizace logu
+ Nedostatek inzulínu
+ Slabá baterie
+ Resetovat po obnovení továrního nastavení
+ Resetovat po nouzovém vypnutí
+ Resetovat po výměně baterie
+ Dokončeno
+
diff --git a/diaconn/src/main/res/values-da-rDK/strings.xml b/diaconn/src/main/res/values-da-rDK/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-da-rDK/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-de-rDE/strings.xml b/diaconn/src/main/res/values-de-rDE/strings.xml
new file mode 100644
index 0000000000..76017f5a34
--- /dev/null
+++ b/diaconn/src/main/res/values-de-rDE/strings.xml
@@ -0,0 +1,150 @@
+
+
+ Kopplung zurücksetzen
+ Keine Geräte verfügbar
+ Diaconn Pumpe verbinden
+ Pumpenfehler
+ Alarme
+ Basal-Stunden
+ Boli
+ Insulin-Tagesmengen
+ Fehler
+ Füllen
+ Befüllen
+ Unterbrechen
+ Kopplung OK
+ Warte auf Kopplung
+ Version
+ Ungültige Kopplungs-Info. Kopple neu.
+ Pumpen-Einstellungen werden ermittelt
+ Zeiteinstellung der Pumpe wird ermittelt
+ Großer Zeitunterschied:\nDie Zeit in der Pumpe weicht um mindestens 1,5 Stunden ab.\nPasse die Zeit auf der Pumpe manuell an und lösche zuvor - falls möglich - die Pumpenhistorie.\nAlternativ kannst Du den Loop für die Stunden der Insulinwirkzeit (DIA) deaktivieren.
+ Großer Zeitunterschied Titel
+ Tagesinsulin-Limit wird bald erreicht
+ Bolus-Abgabe gestartet
+ Warte auf das geschätze Bolus-Ende
+ Status des Bolus wird ermittelt
+ TBR wird abgebrochen
+ TBR wird gesetzt
+ Verzögerter Bolus wird gesetzt
+ Verzögerter Bolus wird abgebrochen
+ Basalrate wird aktualisiert
+ Pumpenintegration für Diaconn G8 Pumpen
+ Diaconn G8
+ Diaconn G8
+ Max. Bolus überschritten
+ Fehler bei Befehlsausführung
+ Geschwindigkeits-Fehler
+ Insulin-Beschränkung verletzt
+ Angefragt: %1$.2f IE. Abgegeben: %2$.2f IE. Fehlercode: %3$s
+ Wert nicht korrekt gesetzt
+ Diaconn G8 Bluetooth Gerät
+ Pumpen-Passwort
+ Bolus-Geschwindigkeit
+ Ausgewählte Pumpe
+ Benutze verzögerten Bolus für hohe TBR >200%%
+ Zeige verzögerten Bolus als %% an.
+ Bluetooth-Status
+ TDD
+ Bolus-Schritt
+ Basal-Schritt
+ Firmware
+ BENUTZER-OPTIONEN
+ Bitte kopple deine Pumpe mit deinem Telefon!
+ "Ereignis wird verarbeitet "
+ Temporäre Basalrate
+ Diaconn-Pumpen Einstellungen
+ Töne
+ Töne
+ Vibration
+ Lautlos
+ Alarmintensität
+ niedrig
+ mittel
+ hoch
+ LCD-Einschaltdauer [Sek.]
+ OPTION IN PUMPE SPEICHERN
+ Sprache
+ Bolus-Geschwindigkeit
+ Chinesisch
+ Korean
+ Englisch
+ "10 "
+ 10
+ 20
+ 30
+ niedrig
+ Verstopfung
+ Akku-Alarm
+ Warnung Insulinmangel
+ Batteriewechsel erforderlich
+ Neues Insulin erforderlich
+ Reservoirwechsel aufzeichnen
+ Reservoirwechsel im Careportal hinzufügen, falls dies in der Historie gefunden wird.
+ Kanülenwechsel protokollieren
+ Kanülenwechsel im Careportal hinzufügen, falls dies in der Historie gefunden wird.
+ Batteriewechsel im Careportal hinzufügen, falls dies in der Historie gefunden wird.
+ Batteriewechsel protokollieren
+ Synchronisierung aufzeichnen
+ Niedriger Insulinstand
+ Niedriger Akkustand
+ Kanüle füllen :%1$.2f IE
+ Injector füllen:%1$.2fIE
+ Katheter füllen: %1$.2fIE
+ Reset nach Zurücksetzen auf Werkseinstellungen
+ Reset nach Notfallaus
+ Reset nach Batteriewechsel
+ Reset nach Kalibrierung
+ Zurücksetzen auf Werkseinstellungen
+ Unerwarteter Systemreset
+ Abgeschlossen
+ Verstopfung
+ Niedriger Akkustand
+ Niedriger Insulinstand
+ Stop durch Benutzer
+ System zurücksetzen
+ Andere
+ Notfall-Stop
+ BASAL
+ MAHLZEITEN BOLUS
+ NORMALER BOLUS
+ VERZÖGERTER BOLUS
+ DUAL BOLUS
+ KATHETER WECHSELN
+ KANÜLE WECHSELN
+ Verstopfung (%s)
+ Basalabgabe (%s)
+ Basal unterbrechen (%s)
+ Dual Bolus abgegeben
+ Multiwave Bolus gestartet
+ Multiwave Bolus abgegeben
+ Verzögerter Bolus gestartet
+ Verzögerter Bolus abgegeben
+ Mahlzeit fehlgeschlagen
+ Erfolgreich
+ Mahlzeit erfolgreich
+ diaconn_g8_logtubechange
+ CRC Fehler - Lookup nicht möglich.
+ Kann nicht auf fehlerhaften Eingabeparameter gesetzt werden.
+ Kann nicht auf fehlerhafte Protokollspezifikation gesetzt werden.
+ Essenszeitpunkt eingestellt. Keine Insulingabe möglich.
+ Von Pumpe abgebrochen
+ Andere Aktionen durchführen, App-Einstellungen beschränkt.
+ Weitere Injektion während Bolusgabe nicht möglich.
+ Fortsetzen der Basal-Injektion erforderlich
+ Abgebrochen, da die Pumpe nicht reagiert.
+ Abgabe wegen niedrigem Akkustand nicht möglich.
+ Abgabe wegen Insulinmangel nicht möglich.
+ Keine Abgabe, da Limit für Einzelabgabe überschritten.
+ Keine Abgabe, da Tageslimit überschritten.
+ Nach Abschluss der Basaleinrichtung kann Basalgabe erfolgen.
+ Der Befehl wurde nicht ausgeführt. Bitte versuche es erneut.
+ Katheterwechsel protokollieren
+ Katheterwechsel in Notizen hinzufügen, falls dies in der Historie gefunden wird.
+ TBR Start
+ Abgabe eingeschränkt während LGS läuft.
+ LGS aktiv, Befehl zum Einschalten zurückgewiesen.
+ LGS inaktiv, Befehl zum Ausschalten zurückgewiesen.
+ TBR Start ist während einer laufenden TBR nicht möglich.
+ TBR kann nicht gestoppt werden, da keine TBR läuft.
+
diff --git a/diaconn/src/main/res/values-el-rGR/strings.xml b/diaconn/src/main/res/values-el-rGR/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-el-rGR/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-es-rES/strings.xml b/diaconn/src/main/res/values-es-rES/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-es-rES/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-fr-rFR/strings.xml b/diaconn/src/main/res/values-fr-rFR/strings.xml
new file mode 100644
index 0000000000..5f50176c21
--- /dev/null
+++ b/diaconn/src/main/res/values-fr-rFR/strings.xml
@@ -0,0 +1,150 @@
+
+
+ Réinit. Appairage
+ Aucun appareil disponible
+ Appairage pompe Diaconn
+ Erreur Pompe
+ Alarmes
+ Heures Basal
+ Bolus
+ Insuline quotidienne
+ Erreurs
+ Amorcer
+ Remplir
+ Suspendre
+ Appairage Ok
+ En attente d\'appairage
+ Version
+ Appairage invalide. Demande de nouvel appairage
+ Obtenir les paramètres pompe
+ Obtenir l\'heure de la pompe
+ Différence horaire importante:\nL\'heure de la pompe est en écart de plus d\'une heure et demi.\nVeuillez ajuster manuellement l\'heure de la pompe et assurez-vous que la lecture de l\'historique de la pompe ne cause pas de dysfonctionnements.\nSi possible, effacez l\'historique de la pompe avant de modifier l\'heure ou désactivez la Boucle Fermée pour une DAI après la dernière entrée erronée de l\'historique et au minimum une DAI à partir de maintenant.
+ Différence horaire importante
+ Limite quotidienne d\'insuline proche
+ Injection du bolus démarrée
+ En attente de la fin du bolus estimé
+ Obtenir l\'état du bolus
+ Arrêter basal temp
+ Définir basal temp
+ Définir bolus étendu
+ Arrêter bolus étendu
+ Mise à jour des débits basal
+ Intégration de la pompe Diaconn G8
+ Diaconn G8
+ G8
+ Violation bolus Max
+ Erreur de commande
+ Erreur de vitesse
+ Violation de limite d\'insuline
+ Demandé : %1$.2fU Injecté : %2$.2fU code d’erreur : %3$s
+ Valeur incorrecte définie
+ Dispositif Bluetooth Diaconn G8
+ Mot de passe pompe
+ Vitesse bolus
+ Pompe sélectionnée
+ Utiliser les bolus étendus pour > 200%%
+ Afficher le bolus étendu en %%
+ État Bluetooth
+ DTI
+ Incrément Bolus
+ Incrément Basal
+ Firmware
+ OPTIONS UTILISATEUR
+ Veuillez appairer votre pompe avec votre téléphone !
+ "Traitement d'événement "
+ aps_last_log_num
+ aps_wrapping_count
+ Basal Temp.
+ Paramètres pompe Diaconn
+ Son
+ son
+ vibration
+ muet
+ Niveau de l\'alarme
+ bas
+ moyen
+ haut
+ Durée affichage LCD [secondes]
+ ENREGISTRER L\'OPTION DANS LA POMPE
+ Langue
+ Vitesse bolus
+ Chinois
+ Coréen
+ Anglais
+ "10 "
+ 10
+ 20
+ 30
+ bas
+ Injection bloquée
+ Alerte batterie
+ Avertissement manque d\'insuline
+ Remplacement de pile requis
+ Remplacement de l\'insuline requis
+ pump_version
+ aps_incarnation_no
+ pump_serial_no
+ Enreg. changement de réservoir
+ Ajouter \"Changement d\'Insuline\" dans careportal si détecté dans l\'historique
+ Enreg. le changement d\'aiguille
+ Ajouter \"Changement de Site\" dans careportal si détecté dans l\'historique
+ Ajouter \"Changement de pile\" dans careportal si détecté dans l\'historique
+ Enreg. changement pile
+ Enreg. synchronisation en cours
+ Manque d\'insuline
+ Pile faible
+ Amorçage site :%1$.2fU
+ Amorçage injecteur :%1$.2fU
+ Amorçage tubulure :%1$.2fU
+ Réinit. après configuration usine
+ Réinit. après la désactivation d\'urgence
+ Réinit. après changement de pile
+ Réinit. après calibration
+ Réinit. après la configuration de la pré-livraison
+ Réinit. inattendue du système
+ Effectué
+ Injection bloquée
+ Pile faible
+ Manque d\'insuline
+ Arrêt utilisateur
+ Réinit. système
+ Autre
+ Arrêt d\'urgence
+ BASAL
+ BOLUS REPAS
+ BOLUS NORMAL
+ BOLUS CARRÉ
+ BOLUS MIXTE
+ REMPLACER TUBULURE
+ REMPLACER L\'AIGUILLE
+ REMPLACER SERINGUE
+ Injection bloquée (%s)
+ autorisation basale (%s)
+ suspension basale (%s)
+ Succès du Double Normal
+ Début du double carré
+ Succès du double carré
+ Début du carré
+ Succès du carré
+ Repas échoué
+ Effectué
+ Repas réussi
+ diaconn_g8_logtubechange
+ Recherche impossible en raison d\'une erreur CRC de paquets.
+ Annulé par la pompe
+ Autres actions en cours, limitation des paramètres de l\'application.
+ Injection restreint pendant une autre injection de Bolus.
+ Reprise de l\'injection basale nécessaire
+ Annulé à cause d\'absence de réponse de la pompe.
+ L\'injection n\'est pas possible en raison d\'une pile faible.
+ Injection impossible en raison de manque d\'insuline.
+ Commande non transmise. Veuillez réessayer.
+ Enreg. changement de tubulure
+ Ajouter \"Changement de tubulure\" à Careportal lorsqu\'il est détecté dans l\'historique
+ Début Basal Temp.
+ En mode AGB, l\'injection d\'insuline est limitée
+ Mode AGB activé, la commande de mise en marche est refusée.
+ Mode AGB désactivé, la commande d\'arrêt est refusée.
+ Début de basal temp. rejeté quand une basal temp. est en cours d\'exécution
+ Arrêt de basal temp. rejeté quand une basal temp. n\'est pas en cours d\'exécution
+
diff --git a/diaconn/src/main/res/values-ga-rIE/strings.xml b/diaconn/src/main/res/values-ga-rIE/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-ga-rIE/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-hr-rHR/strings.xml b/diaconn/src/main/res/values-hr-rHR/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-hr-rHR/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-it-rIT/strings.xml b/diaconn/src/main/res/values-it-rIT/strings.xml
new file mode 100644
index 0000000000..992cec2992
--- /dev/null
+++ b/diaconn/src/main/res/values-it-rIT/strings.xml
@@ -0,0 +1,54 @@
+
+
+ Associazione micro Diaconn
+ Errore micro
+ Allarmi
+ Ore basali
+ Boli
+ Insulina giornaliera
+ Errori
+ Caricamento
+ Riempimento
+ Sospensione
+ Associazione OK
+ In attesa dell\'associazione
+ Versione
+ Informazioni associazione non valide. Richiesta nuova associazione
+ Ricezione impostazioni micro
+ Ricezione ora micro
+ Grande differenza oraria:\nL\'ora nel micro differisce per più di 1h e 30m. \nRegola l\'ora manualmente e assicurati che la lettura dello storico dal micro non causi comportamenti imprevisti.\nSe possibile, cancella lo storico del micro prima di cambiare l\'ora oppure disabilita il loop chiuso per un tempo corrispondente al tuo valore DIA.
+ Si avvicina il limite giornaliero di insulina
+ Avvio erogazione bolo
+ Ricezione stato bolo
+ Stop basale temporanea
+ Impostazione basale temporanea
+ Impostazione bolo esteso
+ Stop bolo esteso
+ Aggiornamento velocità basali
+ Diaconn G8
+ Diaconn G8
+ Violazione bolo massimo
+ Errore comando
+ Errore velocità
+ Violazione limite insulina
+ Chiesto: %1$.2fU Erogato: %2$.2fU Codice errore: %3$s
+ Valore non impostato correttamente
+ Password micro
+ Velocità bolo
+ Micro selezionato
+ Usa boli estesi per >200%%
+ Visualizza bolo esteso come %%
+ Stato bluetooth
+ TDD
+ Incremento bolo
+ Incremento basale
+ Firmware
+ OPZIONI UTENTE
+ Altro
+ BASALE
+ BOLO PASTO
+ BOLO NORMALE
+ BOLO ONDA QUADRA
+ BOLO ONDA DOPPIA
+ Avvio basale temporanea
+
diff --git a/diaconn/src/main/res/values-iw-rIL/strings.xml b/diaconn/src/main/res/values-iw-rIL/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-iw-rIL/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-ko-rKR/strings.xml b/diaconn/src/main/res/values-ko-rKR/strings.xml
new file mode 100644
index 0000000000..17265a3e78
--- /dev/null
+++ b/diaconn/src/main/res/values-ko-rKR/strings.xml
@@ -0,0 +1,118 @@
+
+
+ 페어링 초기화
+ 장비가 존재하지 않습니다.
+ 디아콘 펌프 페어링
+ 펌프 에러
+ 알람
+ 시간당 Basal 주입량
+ 하루 주입량
+ 교체
+ 중지
+ 펌프상태조회
+ 펌프시간정보 조회
+ Bolus 주입 시작
+ Bolus 주입이 진행 중 입니다.
+ Bolus 상태 조회
+ 임시Basal 중지
+ 임시Basal 설정
+ 확장 Bolus 설정
+ 확장 Bolus 중지
+ Basal 패턴 반영
+ G2e에서 만든 Diaconn G8 펌프
+ 속도 에러
+ Bolus 주입속도
+ 펌프를 선택하세요.
+ 사용자설정
+ 펌프와 전화기를 페어링해 주세요!
+ 임시 Basal
+ 디아콘 펌프 설정
+ 음향 선택
+ 소리
+ 진동
+ 무음
+ 음향 세기
+ 소
+ 중
+ 대
+ 조명지속시간[초]
+ 언어설정
+ Bolus 주입속도 [U/min]
+ 중국어
+ 한국어
+ 영어
+ 소
+ Bolus 주입막힘
+ 베터리 경고
+ 인슐린 부족 경고
+ 베터리 교체가 필요합니다.
+ 인슐린 교체가 필요합니다.
+ 인슐린 교체
+ 로그 동기화 시 케어포털 \"인슐린 교체\" 정보 자동 업로드
+ 바늘 교체
+ 로그 동기화 시 케어포털 \"위치 교체\" 정보 자동 업로드
+ 로그 동기화 시 케어포털 \"베터리 교체\" 정보 자동 업로드
+ 베터리 교체
+ 로그 동기화 진행 중
+ 인슐린 부족 경고
+ 베터리 부족 경고
+ 바늘교체 공기 빼기 :%1$.2fU
+ 주사기 교체 공기빼기 :%1$.2fU
+ 튜브 교체 공기빼기 :%1$.2fU
+ 공장초기화 리셋
+ 긴급 전원오프 리셋
+ 베터리교체 후 리셋
+ 보정 후 리셋
+ 출하전설정 후 리셋
+ 예상치 못한 시스템 리셋
+ 완료
+ 주입 막힘
+ 베터리 부족
+ 인슐린 부족
+ 사용자 중지
+ 시스템 리셋
+ 기타
+ 긴급 정지
+ 기저주입
+ 식사주입
+ 일반주입
+ 스퀘어주입
+ 듀얼주입
+ 튜브교체
+ 바늘교체
+ 주사기교체
+ 주입막힘 (%s)
+ 기저 재개 (%s)
+ 기저 중지 (%s)
+ 듀얼 일반 성공
+ 듀얼 스퀘어 시작
+ 듀얼 스퀘어 성공
+ 스퀘어 시작
+ 스퀘어 성공
+ 식사 실패
+ 성공
+ 식사 성공
+ 패킷 CRC 오류로 조회 불가합니다.
+ 입력 파라미터 오류로 설정 불가합니다.
+ 프로토콜 규격 오류로 설정 불가합니다.
+ 식사 시간제한 상태로, 주입할 수 없습니다.
+ 펌프에서 취소 하였습니다.
+ 타 작업중으로, 앱 설정 기능이 제한됩니다.
+ 다른 Bolus 주입 중으로, 주입이 제한됩니다.
+ 기저정지 해제가 필요합니다.
+ 펌프 미응답으로 취소 되었습니다.
+ 배터리 부족으로 주입할 수 없습니다.
+ 인슐린 부족으로 주입할 수 없습니다.
+ 1회 제한량 초과로 주입할 수 없습니다.
+ 금일 주입량 초과로 주입할 수 없습니다.
+ 기저설정 완료 후, 기저주입할 수 있습니다.
+ 명령이 전달되지 않았습니다. 다시 시도해주세요.
+ 튜브 교체
+ 로그 동기화 시 \"튜브 교체\" 노트 정보 자동 업로드
+ 임시Basal 시작
+ LGS 동작 중 볼러스 주입 거절
+ LGS ON일때, ON 거절
+ LGS OFF일 때, OFF 거절
+ 임시기저 설정중인 상태일 때, 임시기저 시작 명령 거절
+ 임시기저 설정이 안 된 상태일 때, 임시기저 중지 명령 거절
+
diff --git a/diaconn/src/main/res/values-lt-rLT/strings.xml b/diaconn/src/main/res/values-lt-rLT/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-lt-rLT/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-nl-rNL/strings.xml b/diaconn/src/main/res/values-nl-rNL/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-nl-rNL/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-no-rNO/strings.xml b/diaconn/src/main/res/values-no-rNO/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-no-rNO/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-pl-rPL/strings.xml b/diaconn/src/main/res/values-pl-rPL/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-pl-rPL/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-pt-rBR/strings.xml b/diaconn/src/main/res/values-pt-rBR/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-pt-rBR/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-pt-rPT/strings.xml b/diaconn/src/main/res/values-pt-rPT/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-pt-rPT/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-ro-rRO/strings.xml b/diaconn/src/main/res/values-ro-rRO/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-ro-rRO/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-ru-rRU/strings.xml b/diaconn/src/main/res/values-ru-rRU/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-ru-rRU/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-sk-rSK/strings.xml b/diaconn/src/main/res/values-sk-rSK/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-sk-rSK/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-sl-rSI/strings.xml b/diaconn/src/main/res/values-sl-rSI/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-sl-rSI/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-sv-rSE/strings.xml b/diaconn/src/main/res/values-sv-rSE/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-sv-rSE/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-ta-rIN/strings.xml b/diaconn/src/main/res/values-ta-rIN/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-ta-rIN/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-tr-rTR/strings.xml b/diaconn/src/main/res/values-tr-rTR/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-tr-rTR/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values-zh-rCN/strings.xml b/diaconn/src/main/res/values-zh-rCN/strings.xml
new file mode 100644
index 0000000000..3ea04e700d
--- /dev/null
+++ b/diaconn/src/main/res/values-zh-rCN/strings.xml
@@ -0,0 +1,2 @@
+
+
diff --git a/diaconn/src/main/res/values/arrays.xml b/diaconn/src/main/res/values/arrays.xml
new file mode 100644
index 0000000000..ab98405145
--- /dev/null
+++ b/diaconn/src/main/res/values/arrays.xml
@@ -0,0 +1,48 @@
+
+
+
+
+ - 1 U/min
+ - 2 U/min
+ - 3 U/min
+ - 4 U/min
+ - 5 U/min
+ - 6 U/min
+ - 7 U/min
+ - 8 U/min
+
+
+ - 1
+ - 2
+ - 3
+ - 4
+ - 5
+ - 6
+ - 7
+ - 8
+
+
+
+ - Chiness
+ - Korean
+ - English
+
+
+ - 1
+ - 2
+ - 3
+
+
+
+ - Small
+ - Medium
+ - Large
+
+
+ - 1
+ - 2
+ - 3
+
+
+
+
\ No newline at end of file
diff --git a/diaconn/src/main/res/values/colors.xml b/diaconn/src/main/res/values/colors.xml
new file mode 100644
index 0000000000..f8c6127d32
--- /dev/null
+++ b/diaconn/src/main/res/values/colors.xml
@@ -0,0 +1,10 @@
+
+
+ #FFBB86FC
+ #FF6200EE
+ #FF3700B3
+ #FF03DAC5
+ #FF018786
+ #FF000000
+ #FFFFFFFF
+
\ No newline at end of file
diff --git a/diaconn/src/main/res/values/ids.xml b/diaconn/src/main/res/values/ids.xml
new file mode 100644
index 0000000000..ab4bb053a1
--- /dev/null
+++ b/diaconn/src/main/res/values/ids.xml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/diaconn/src/main/res/values/strings.xml b/diaconn/src/main/res/values/strings.xml
new file mode 100644
index 0000000000..3a51a9ff15
--- /dev/null
+++ b/diaconn/src/main/res/values/strings.xml
@@ -0,0 +1,171 @@
+
+ diaconn_g8_pump_settings
+ diagonn_g8_address
+ Diaconn G8
+ key_diaconn_g8_bt_name
+ diaconn_g8_useextended
+ diaconn_g8_visualizeextendedaspercentage
+
+ g8_bolusspeed
+ diaconn_g8_logbatterychanges
+ diaconn_g8_loginsulinchange
+ diaconn_g8_logneedlechange
+
+ Reset Pairing
+ No Device available
+ Diaconn Pump Pairing
+ Pump Error
+ Alarms
+ Basal Hours
+ Boluses
+ Daily insulin
+ Errors
+ Prime
+ Refill
+ Suspend
+ Pairing Ok
+ Waiting for Pairing
+ Version
+ Invalid pairing information. Requesting new pairing
+ Getting pump settings
+ Getting pump time
+ Large time difference:\nTime in pump is off by more than 1.5 hours.\nPlease adjust the time manually on the pump and make sure that reading the history from the pump does not cause unexpected behaviour.\nIf possible, remove the history from the pump before changing the time or disable the closed loop for one DIA after the last wrong history entry but minimum one DIA from now.
+ Large time difference Title
+ Approaching insulin daily limit
+ Starting bolus delivery
+ Waiting for estimated bolus end
+ Getting Bolus Status
+ Stopping temp basal
+ Setting temp basal
+ Setting extended bolus
+ Stopping extended bolus
+ Updating basal rates
+ Pump Integration for Diaconn G8 Pumps
+ Diaconn G8
+ Diaconn G8
+ Max bolus violation
+ Command error
+ Speed error
+ Insulin limit violation
+ Asked: %1$.2fU Delivered: %2$.2fU Error code: %3$s
+ Value not set properly
+ Diaconn G8 Bluetooth device
+
+ Pump Password
+
+ Bolus speed
+ Selected pump
+ Use extended boluses for >200%%
+ Visualize extended bolus as %%
+ Bluetooth Status
+ TDD
+ Bolus Step
+ Basal Step
+ Firmware
+ USER OPTIONS
+ Please pair your pump with your phone!
+ "Processing Event "
+ aps_last_log_num
+ aps_wrapping_count
+ Temp Basal
+ Diaconn pump Settings
+ Sound
+ sound
+ vibrate
+ silent
+ Alarm intensity
+ low
+ middle
+ high
+ LCD on time [second]
+ SAVE OPTION TO PUMP
+ Language
+ Bolus speed
+ Chiness
+ Korean
+ English
+ "10 "
+ 10
+ 20
+ 30
+ low
+ Injection Blocked
+ Battery Warning
+ Insulin Lack Warning
+ Battery replacement is required
+ Insulin replacement is required
+ pump_version
+ aps_incarnation_no
+ pump_serial_no
+ Log reservoir change
+ Add \"Insulin Change\" event to careportal when detected in history
+ Log needle change
+ Add \"Site Change\" event to careportal when detected in history
+ Add \"Battery Change\" event to careportal when detected in history
+ Log battery change
+ Log Synchronization in progress
+ Inuslin shortage
+ Battery shortage
+ Needle prime :%1$.2fU
+ Injector prime :%1$.2fU
+ Tube change prime :%1$.2fU
+ Reset after factory reset
+ Reset after Emergency Off
+ Reset after user battery replacement
+ Reset after Calibration
+ Reset after pre-shipment setup
+ Unexpected system reset
+ Complete
+ Injection block
+ Battery shortage
+ Insuiln shortage
+ User stop
+ System reset
+ Other
+ Emergency stop
+ BASAL
+ MEAL BOLUS
+ NORMAL BOLUS
+ SQUARE BOLUS
+ DUAL BOLUS
+ REPLACE TUBE
+ REPLACE NEEDLE
+ REPLACE SYRINGE
+ Injection Block (%s)
+ basal release (%s)
+ basal suspend (%s)
+ Dual Nomarl Success
+ Dual Square Start
+ Dual Square Success
+ Square Start
+ Square Success
+ Meal Failed
+ Success
+ Meal Success
+ diaconn_g8_logtubechange
+ Can\'t lookup due to packet CRC error.
+ Can\'t be set to an input parameter error.
+ Can\'t be set to a protocol specification error.
+ Eating timed, cannot be injected.
+ Cancelled by pump
+ Taking other actions, limiting app settings.
+ During another Bolus injection, injection is restricted.
+ Require resume the basal injection
+ Cancelled due to pump not responding.
+ Injection is not possible due to low battery.
+ Insulin insufficiency cannot be injected.
+ You cannot inject it because it exceeds the limit once.
+ Injection cannot be injected because it exceeds the injection volume today.
+ After basal setup is complete, basal injection can be performed.
+ The command was not delivered. Please try again.
+ Log tube change
+ Add \"Tube Change\" event to Note when detected in history
+ TempBasal Start
+ During LGS running, injection is restricted
+ LGS status is ON, ON Command is declined.
+ LGS status is OFF, OFF Command is declined.
+ Tempbasal start is rejected when tempbasal is running
+ Tempbasal stop is rejected when tempbasal is not running
+
+
+
\ No newline at end of file
diff --git a/diaconn/src/main/res/values/themes.xml b/diaconn/src/main/res/values/themes.xml
new file mode 100644
index 0000000000..e52448bafa
--- /dev/null
+++ b/diaconn/src/main/res/values/themes.xml
@@ -0,0 +1,16 @@
+
+
+
+
\ No newline at end of file
diff --git a/diaconn/src/main/res/xml/pref_diaconn.xml b/diaconn/src/main/res/xml/pref_diaconn.xml
new file mode 100644
index 0000000000..f81699e887
--- /dev/null
+++ b/diaconn/src/main/res/xml/pref_diaconn.xml
@@ -0,0 +1,50 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/gradle/android_dependencies.gradle b/gradle/android_dependencies.gradle
index c07f69eea0..b3b28c7edc 100644
--- a/gradle/android_dependencies.gradle
+++ b/gradle/android_dependencies.gradle
@@ -5,7 +5,6 @@ android {
targetSdkVersion 28
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
- consumerProguardFiles 'consumer-rules.pro'
}
kotlinOptions {
diff --git a/gradle/jacoco_global.gradle b/gradle/jacoco_global.gradle
new file mode 100644
index 0000000000..991d9597b6
--- /dev/null
+++ b/gradle/jacoco_global.gradle
@@ -0,0 +1,8 @@
+jacoco {
+ toolVersion = "0.8.7"
+}
+
+tasks.withType(Test) {
+ jacoco.includeNoLocationClasses = true
+ jacoco.excludes = ['jdk.internal.*']
+}
\ No newline at end of file
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index 404e613d00..6d6af4e166 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl = https://services.gradle.org/distributions/gradle-6.8.2-all.zip
+distributionUrl = https\://services.gradle.org/distributions/gradle-7.0-all.zip
diff --git a/insight/build.gradle b/insight/build.gradle
index 33b66a5090..46e26b9616 100644
--- a/insight/build.gradle
+++ b/insight/build.gradle
@@ -6,12 +6,10 @@ 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"
-
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
android {
defaultConfig {
- versionCode 1
- versionName "1.0"
kapt {
arguments {
arg("room.incremental", "true")
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 @@
+
0 && profileFunction.getProfile(bolusID.getTimestamp()) != null)
pumpSync.syncExtendedBolusWithPumpId(
- bolusID.getTimestamp(),
+ startTimestamp,
event.getExtendedAmount(),
- T.mins(event.getDuration()).msecs(),
+ timestamp - startTimestamp,
isFakingTempsByExtendedBoluses(),
bolusID.getId(),
PumpType.ACCU_CHEK_INSIGHT,
diff --git a/insight/src/main/res/values-ko-rKR/alert_descriptions.xml b/insight/src/main/res/values-ko-rKR/alert_descriptions.xml
index 6687bd33e6..1eaf1759ab 100644
--- a/insight/src/main/res/values-ko-rKR/alert_descriptions.xml
+++ b/insight/src/main/res/values-ko-rKR/alert_descriptions.xml
@@ -4,6 +4,7 @@
%1$s U]]>
베터리 교체.
시간/날짜 설정
+ 아큐-첵 지원 문의
%1$d%%
기간: %2$s h]]>
%1$s U
주입: %2$s U]]>
카트리지를 삽입.
@@ -12,9 +13,12 @@
펌프 상태를 체크.
주입세트를 교체.
아큐-첵 지원 문의
+ 카트리지를 교체.
데이터 다운로드 재시작
+ 펌프 상태를 체크.
베터리 타입 설정.
카트리지 타입 설정.
베터리와 카트리지를 교체.
+ 카트리지를 교체.
언어 변경.
diff --git a/insight/src/main/res/values-ko-rKR/alert_titles.xml b/insight/src/main/res/values-ko-rKR/alert_titles.xml
index 0a675c63ce..ca4cf3ddde 100644
--- a/insight/src/main/res/values-ko-rKR/alert_titles.xml
+++ b/insight/src/main/res/values-ko-rKR/alert_titles.xml
@@ -3,6 +3,7 @@
Bolus 주입.
Bolus 누락
알람 시계
+ 주입세트를 교체
TBR 완료
카트리지 부족
베터리 부족
diff --git a/insight/src/main/res/values-lt-rLT/alert_descriptions.xml b/insight/src/main/res/values-lt-rLT/alert_descriptions.xml
index bb70b971c9..4c5d7e5b0f 100644
--- a/insight/src/main/res/values-lt-rLT/alert_descriptions.xml
+++ b/insight/src/main/res/values-lt-rLT/alert_descriptions.xml
@@ -2,7 +2,9 @@
%1$d%%\nTrukmė: %2$s h]]>
%1$s U]]>
+ Pakeiskite bateriją.
Nustatykite laiką/datą.
+ Kreipkitės į Accu-Chek palaikymo tarnybą.
%1$d%%
Trukmė: %2$s h]]>
%1$s U
Suleista: %2$s U]]>
Įdėkite rezervuarą.
@@ -11,9 +13,12 @@
Patikrinkite pompos būseną.
Pakeiskite infuzijos rinkinį.
Kreipkitės į Accu-Chek palaikymo tarnybą.
+ Pakeiskite rezervuarą.
Iš naujo paleiskite duomenų atsisiuntimą.
+ Patikrinkite pompos būseną.
Nustatykite baterijos tipą.
Nustatykite rezervuaro tipą.
Pakeiskite bateriją ir rezervuarą.
+ Pakeiskite rezervuarą.
Pakeiskite kalbą.
diff --git a/medtronic/build.gradle b/medtronic/build.gradle
index 4c3af48c8a..f7106a59bd 100644
--- a/medtronic/build.gradle
+++ b/medtronic/build.gradle
@@ -6,13 +6,7 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':core')
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/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/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 cb904b9afe..e558a22f88 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,13 +4,13 @@ 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
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.sync.PumpDbEntryTBR
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
@@ -49,7 +49,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 +80,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)
}
}
}
@@ -94,7 +93,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) {
@@ -350,7 +349,7 @@ class MedtronicHistoryData @Inject constructor(
aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "ProcessHistoryData: TBRs Processed [count=%d, items=%s]", tbrs.size, gson.toJson(tbrs)))
if (tbrs.isNotEmpty()) {
try {
- processTBREntries(tbrs) // TODO not implemented yet
+ processTBREntries(tbrs)
} catch (ex: Exception) {
aapsLogger.error(LTag.PUMP, "ProcessHistoryData: Error processing TBR entries: " + ex.message, ex)
throw ex
@@ -479,11 +478,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
@@ -493,9 +492,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, "DD: entryWithTempId=$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)
@@ -581,7 +582,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) {
@@ -603,7 +604,10 @@ class MedtronicHistoryData @Inject constructor(
}
processDTO = TempBasalProcessDTO(
itemOne = treatment,
- processOperation = TempBasalProcessDTO.Operation.Add)
+ processOperation = TempBasalProcessDTO.Operation.Add,
+ aapsLogger = aapsLogger,
+ objectType = TempBasalProcessDTO.ObjectType.TemporaryBasal
+ )
}
}
if (processDTO != null) {
@@ -612,89 +616,115 @@ class MedtronicHistoryData @Inject constructor(
if (processList.isNotEmpty()) {
for (tempBasalProcessDTO in processList) {
+ aapsLogger.debug(LTag.PUMP, "DD: tempBasalProcessDTO.itemOne: " + gson.toJson(tempBasalProcessDTO.itemOne))
+ aapsLogger.debug(LTag.PUMP, "DD: tempBasalProcessDTO.itemTwo: " + (if (tempBasalProcessDTO.itemTwo == null) "null" else gson.toJson(tempBasalProcessDTO.itemTwo!!)))
+
val entryWithTempId = findDbEntry(tempBasalProcessDTO.itemOne, tbrRecords)
aapsLogger.debug(LTag.PUMP, "DD: entryWithTempId: " + (if (entryWithTempId == null) "null" else entryWithTempId.toString()))
- val tbrEntry = tempBasalProcessDTO.itemOne.getDecodedDataEntry("Object") as TempBasalPair
+ val tbrEntry = tempBasalProcessDTO.itemOneTbr //.getDecodedDataEntry("Object") as TempBasalPair
aapsLogger.debug(LTag.PUMP, String.format("DD: tbrEntry=%s, tempBasalProcessDTO=%s", gson.toJson(tbrEntry), gson.toJson(tempBasalProcessDTO)))
if (entryWithTempId != null) {
- 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))
+ if (tbrEntry != null) {
+ aapsLogger.debug(LTag.PUMP, "DD: tempIdEntry=${entryWithTempId}, tbrEntry=${tbrEntry}, " +
+ "tempBasalProcessDTO=${tempBasalProcessDTO}, " +
+ "pumpType=${medtronicPumpStatus.pumpType}, serial=${medtronicPumpStatus.serialNumber}")
- val result = pumpSync.syncTemporaryBasalWithTempId(
- tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
- tbrEntry.insulinRate,
- tempBasalProcessDTO.duration * 60L * 1000L,
- !tbrEntry.isPercent,
- entryWithTempId.temporaryId,
- PumpSync.TemporaryBasalType.NORMAL,
- tempBasalProcessDTO.pumpId,
- medtronicPumpStatus.pumpType,
- medtronicPumpStatus.serialNumber)
+ aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithTempId " +
+ "[date=${tempBasalProcessDTO.atechDateTime}, dateProcess=${tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime)}, " +
+ "tbrEntry.insulinRate=${tbrEntry.insulinRate}, " +
+ "duration=${tempBasalProcessDTO.durationAsSeconds} s, " +
+ "isAbsolute=${!tbrEntry.isPercent}, temporaryId=${entryWithTempId.temporaryId}, " +
+ "pumpId=${tempBasalProcessDTO.pumpId}, pumpType=${medtronicPumpStatus.pumpType}, " +
+ "pumpSerial=${medtronicPumpStatus.serialNumber}]")
- aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "syncTemporaryBasalWithTempId [date=%d, temporaryId=%d, pumpId=%d, rate=%.2f %s, duration=%d, pumpSerial=%s] - Result: %b",
- tempBasalProcessDTO.atechDateTime, entryWithTempId.temporaryId, tempBasalProcessDTO.pumpId,
- tbrEntry.insulinRate, (if (tbrEntry.isPercent) "%" else "U"), tempBasalProcessDTO.duration,
- medtronicPumpStatus.serialNumber, result))
+ val result = pumpSync.syncTemporaryBasalWithTempId(
+ tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
+ tbrEntry.insulinRate,
+ tempBasalProcessDTO.durationAsSeconds * 1000L,
+ !tbrEntry.isPercent,
+ entryWithTempId.temporaryId,
+ PumpSync.TemporaryBasalType.NORMAL,
+ tempBasalProcessDTO.pumpId,
+ medtronicPumpStatus.pumpType,
+ medtronicPumpStatus.serialNumber)
- pumpSyncStorage.removeTemporaryBasalWithTemporaryId(entryWithTempId.temporaryId)
- tbrRecords.remove(entryWithTempId)
+ aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithTempId - Result: ${result}")
- entryWithTempId.pumpId = tempBasalProcessDTO.pumpId
- entryWithTempId.date = tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime)
+ pumpSyncStorage.removeTemporaryBasalWithTemporaryId(entryWithTempId.temporaryId)
+ tbrRecords.remove(entryWithTempId)
- if (isTBRActive(entryWithTempId)) {
- medtronicPumpStatus.runningTBR = entryWithTempId
+ entryWithTempId.pumpId = tempBasalProcessDTO.pumpId
+ entryWithTempId.date = tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime)
+
+ if (isTBRActive(entryWithTempId)) {
+ medtronicPumpStatus.runningTBR = entryWithTempId
+ }
+ } else {
+ aapsLogger.warn(LTag.PUMP, "tbrEntry (itemOne) is null, shouldn't be.")
}
} else {
- val result = pumpSync.syncTemporaryBasalWithPumpId(
- tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
- tbrEntry.insulinRate,
- tempBasalProcessDTO.duration * 60L * 1000L,
- !tbrEntry.isPercent,
- PumpSync.TemporaryBasalType.NORMAL,
- tempBasalProcessDTO.pumpId,
- medtronicPumpStatus.pumpType,
- medtronicPumpStatus.serialNumber)
- aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "syncTemporaryBasalWithPumpId [date=%d, pumpId=%d, rate=%.2f %s, duration=%d, pumpSerial=%s] - Result: %b",
- tempBasalProcessDTO.atechDateTime, tempBasalProcessDTO.pumpId,
- tbrEntry.insulinRate, (if (tbrEntry.isPercent) "%" else "U"), tempBasalProcessDTO.duration,
- medtronicPumpStatus.serialNumber, result))
+ if (tbrEntry != null) {
- if (medtronicPumpStatus.runningTBR != null) {
- if (!isTBRActive(medtronicPumpStatus.runningTBR!!)) {
- medtronicPumpStatus.runningTBR = null
+ aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithPumpId [date=${tempBasalProcessDTO.atechDateTime}, " +
+ "pumpId=${tempBasalProcessDTO.pumpId}, rate=${tbrEntry.insulinRate} U, " +
+ "duration=${tempBasalProcessDTO.durationAsSeconds} s, pumpSerial=${medtronicPumpStatus.serialNumber}]")
+
+ val result = pumpSync.syncTemporaryBasalWithPumpId(
+ tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
+ tbrEntry.insulinRate,
+ tempBasalProcessDTO.durationAsSeconds * 1000L,
+ !tbrEntry.isPercent,
+ PumpSync.TemporaryBasalType.NORMAL,
+ tempBasalProcessDTO.pumpId,
+ medtronicPumpStatus.pumpType,
+ medtronicPumpStatus.serialNumber)
+
+ aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithPumpId - Result: $result")
+
+ if (medtronicPumpStatus.runningTBR != null) {
+ if (!isTBRActive(medtronicPumpStatus.runningTBR!!)) {
+ medtronicPumpStatus.runningTBR = null
+ }
}
- }
- if (isTBRActive(tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime), tempBasalProcessDTO.duration)) {
- if (medtronicPumpStatus.runningTBR == null) {
- medtronicPumpStatus.runningTBR = info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry(0L,
- tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
- medtronicPumpStatus.pumpType,
- medtronicPumpStatus.serialNumber,
- null,
- info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntryTBR(tbrEntry.insulinRate, !tbrEntry.isPercent, tempBasalProcessDTO.duration, PumpSync.TemporaryBasalType.NORMAL),
- tempBasalProcessDTO.pumpId)
+ if (isTBRActive(startTimestamp = tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
+ durationSeconds = tempBasalProcessDTO.durationAsSeconds)) {
+ if (medtronicPumpStatus.runningTBR == null) {
+ medtronicPumpStatus.runningTBR = info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry(0L,
+ tryToGetByLocalTime(tempBasalProcessDTO.atechDateTime),
+ medtronicPumpStatus.pumpType,
+ medtronicPumpStatus.serialNumber,
+ null,
+ PumpDbEntryTBR(rate = tbrEntry.insulinRate,
+ isAbsolute = !tbrEntry.isPercent,
+ durationInSeconds = tempBasalProcessDTO.durationAsSeconds,
+ tbrType = PumpSync.TemporaryBasalType.NORMAL),
+ tempBasalProcessDTO.pumpId)
+ }
}
+ } else {
+ aapsLogger.warn(LTag.PUMP, "tbrEntry (itemOne) is null, shouldn't be.")
}
}
} // for
} // collection
}
- fun isTBRActive(dbEntry: info.nightscout.androidaps.plugins.pump.common.sync.PumpDbEntry): Boolean {
- return isTBRActive(dbEntry.date, dbEntry.tbrData!!.durationInMinutes)
+ fun isTBRActive(dbEntry: PumpDbEntry): Boolean {
+ return isTBRActive(
+ startTimestamp = dbEntry.date,
+ durationSeconds = dbEntry.tbrData!!.durationInSeconds)
}
- fun isTBRActive(startTimestamp: Long, durationMin: Int): Boolean {
- val endDate = startTimestamp + (durationMin * 60 * 1000)
+ fun isTBRActive(startTimestamp: Long, durationSeconds: Int): Boolean {
+ val endDate = startTimestamp + (durationSeconds * 1000)
return (endDate > System.currentTimeMillis())
}
@@ -712,7 +742,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
@@ -772,20 +802,22 @@ class MedtronicHistoryData @Inject constructor(
private fun processSuspends(tempBasalProcessList: List) {
for (tempBasalProcess in tempBasalProcessList) {
+ aapsLogger.debug(LTag.PUMP, "processSuspends::syncTemporaryBasalWithPumpId [date=${tempBasalProcess.itemOne.atechDateTime}, " +
+ "rate=0.0, duration=${tempBasalProcess.durationAsSeconds} s, type=${PumpSync.TemporaryBasalType.PUMP_SUSPEND}, " +
+ "pumpId=${tempBasalProcess.itemOne.pumpId}, " +
+ "pumpSerial=${medtronicPumpStatus.serialNumber}]")
+
val result = pumpSync.syncTemporaryBasalWithPumpId(
tryToGetByLocalTime(tempBasalProcess.itemOne.atechDateTime),
0.0,
- tempBasalProcess.duration * 60 * 1000L,
+ tempBasalProcess.durationAsSeconds * 1000L,
true,
PumpSync.TemporaryBasalType.PUMP_SUSPEND,
tempBasalProcess.itemOne.pumpId,
medtronicPumpStatus.pumpType,
medtronicPumpStatus.serialNumber)
- aapsLogger.debug(LTag.PUMP, String.format(Locale.ENGLISH, "processSuspends::syncTemporaryBasalWithPumpId [date=%d, rate=%.2f, duration=%d, pumpId=%d, pumpSerial=%s] - Result: %b",
- tempBasalProcess.itemOne.atechDateTime, 0.0, tempBasalProcess.duration, tempBasalProcess.itemOne.pumpId,
- medtronicPumpStatus.serialNumber, result))
-
+ aapsLogger.debug(LTag.PUMP, "syncTemporaryBasalWithPumpId: Result: $result")
}
}
@@ -804,6 +836,9 @@ class MedtronicHistoryData @Inject constructor(
private fun getSuspendResumeRecordsList(): List {
val filteredItems = getFilteredItems(newHistory, //
setOf(PumpHistoryEntryType.SuspendPump, PumpHistoryEntryType.ResumePump))
+
+ aapsLogger.debug(LTag.PUMP, "SuspendResume Records: $filteredItems")
+
val outList: MutableList = mutableListOf()
if (filteredItems.size > 0) {
val filtered2Items: MutableList = mutableListOf()
@@ -841,10 +876,16 @@ class MedtronicHistoryData @Inject constructor(
Collections.reverse(filtered2Items)
var i = 0
while (i < filtered2Items.size) {
- outList.add(TempBasalProcessDTO(
+ val tbrProcess = TempBasalProcessDTO(
itemOne = filtered2Items[i],
- itemTwo = filtered2Items[i + 1],
- processOperation = TempBasalProcessDTO.Operation.Add))
+ processOperation = TempBasalProcessDTO.Operation.Add,
+ aapsLogger = aapsLogger,
+ objectType = TempBasalProcessDTO.ObjectType.Suspend)
+
+ tbrProcess.itemTwo = filtered2Items[i + 1]
+
+ if (tbrProcess.itemTwo != null)
+ outList.add(tbrProcess)
i += 2
}
@@ -856,6 +897,9 @@ class MedtronicHistoryData @Inject constructor(
private fun getNoDeliveryRewindPrimeRecordsList(): List {
val primeItems: MutableList = getFilteredItems(newHistory, //
setOf(PumpHistoryEntryType.Prime))
+
+ aapsLogger.debug(LTag.PUMP, "Prime Records: $primeItems")
+
val outList: MutableList = ArrayList()
if (primeItems.size == 0) return outList
val filteredItems: MutableList = getFilteredItems(newHistory, //
@@ -865,6 +909,9 @@ class MedtronicHistoryData @Inject constructor(
PumpHistoryEntryType.Bolus,
PumpHistoryEntryType.TempBasalCombined)
)
+
+ aapsLogger.debug(LTag.PUMP, "Filtered Records: $filteredItems")
+
val tempData: MutableList = mutableListOf()
var startedItems = false
var finishedItems = false
@@ -903,22 +950,40 @@ class MedtronicHistoryData @Inject constructor(
}
showLogs("NoDeliveryRewindPrimeRecords: Records to evaluate: ", gson.toJson(tempData))
var items: MutableList = getFilteredItems(tempData, PumpHistoryEntryType.Prime)
- var itemTwo = items[0]
+ val itemTwo = items[0]
+
items = getFilteredItems(tempData, PumpHistoryEntryType.NoDeliveryAlarm)
if (items.size > 0) {
- outList.add(TempBasalProcessDTO(
+ val tbrProcess = TempBasalProcessDTO(
itemOne = items[items.size - 1],
- itemTwo = itemTwo,
- processOperation = TempBasalProcessDTO.Operation.Add))
+ processOperation = TempBasalProcessDTO.Operation.Add,
+ aapsLogger = aapsLogger,
+ objectType = TempBasalProcessDTO.ObjectType.Suspend)
+
+ tbrProcess.itemTwo = itemTwo
+
+ if (tbrProcess.itemTwo != null)
+ outList.add(tbrProcess)
+
return outList
}
+
items = getFilteredItems(tempData, PumpHistoryEntryType.Rewind)
if (items.size > 0) {
- outList.add(TempBasalProcessDTO(
+ val tbrProcess = TempBasalProcessDTO(
itemOne = items[0],
- processOperation = TempBasalProcessDTO.Operation.Add))
+ processOperation = TempBasalProcessDTO.Operation.Add,
+ aapsLogger = aapsLogger,
+ objectType = TempBasalProcessDTO.ObjectType.Suspend)
+
+ tbrProcess.itemTwo = itemTwo
+
+ if (tbrProcess.itemTwo != null)
+ outList.add(tbrProcess)
+
return outList
}
+
return outList
}
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/data/dto/TempBasalProcessDTO.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalProcessDTO.kt
index 02ddb39f46..a0ce5241de 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,26 @@
package info.nightscout.androidaps.plugins.pump.medtronic.data.dto
+import info.nightscout.androidaps.logging.AAPSLogger
+import info.nightscout.androidaps.logging.LTag
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 objectType: ObjectType = ObjectType.TemporaryBasal) {
+
+ var itemTwo: PumpHistoryEntry? = null
+ set(value) {
+ field = value
+ if (objectType == ObjectType.TemporaryBasal) {
+ itemTwoTbr = value!!.getDecodedDataEntry("Object") as TempBasalPair
+ }
+ }
+
+ var itemOneTbr: TempBasalPair? = null
+ var itemTwoTbr: TempBasalPair? = null
+
var cancelPresent: Boolean = false
val atechDateTime: Long
@@ -14,15 +29,50 @@ class TempBasalProcessDTO constructor(var itemOne: PumpHistoryEntry,
val pumpId: Long
get() = itemOne.pumpId
- val duration: Int
- get() = if (itemTwo == null) {
- val tbr = itemOne.getDecodedDataEntry("Object") as TempBasalPair
- tbr.durationMinutes
- } else {
- DateTimeUtil.getATechDateDiferenceAsMinutes(itemOne.atechDateTime, itemTwo!!.atechDateTime)
+ val durationAsSeconds: Int
+ get() {
+ aapsLogger.debug(LTag.PUMP, "durationAsSeconds: [objectType=$objectType]")
+ if (objectType == ObjectType.TemporaryBasal) {
+ if (itemTwo == null) {
+ if (itemOneTbr != null) {
+ aapsLogger.debug("TemporaryBasalPair - itemOneSingle: $itemOneTbr")
+ return itemOneTbr!!.durationMinutes * 60
+ } else {
+ aapsLogger.error("Couldn't find TempBasalPair in entry: $itemOne")
+ return 0
+ }
+ } else {
+ aapsLogger.debug(LTag.PUMP, "Found 2 items for duration: itemOne=$itemOne, itemTwo=$itemTwo")
+ val secondsDiff = DateTimeUtil.getATechDateDiferenceAsSeconds(itemOne.atechDateTime, itemTwo!!.atechDateTime)
+ aapsLogger.debug(LTag.PUMP, "Difference in seconds: $secondsDiff")
+ return secondsDiff
+ }
+ } else {
+ aapsLogger.debug(LTag.PUMP, "Found 2 items for duration (in SuspendMode): itemOne=$itemOne, itemTwo=$itemTwo")
+ val secondsDiff = DateTimeUtil.getATechDateDiferenceAsSeconds(itemOne.atechDateTime, itemTwo!!.atechDateTime)
+ aapsLogger.debug(LTag.PUMP, "Difference in seconds: $secondsDiff")
+ return secondsDiff
+ }
}
+ init {
+ if (objectType == ObjectType.TemporaryBasal) {
+ itemOneTbr = itemOne.getDecodedDataEntry("Object") as TempBasalPair
+ }
+ }
+
+ override fun toString(): String {
+ return "ItemOne: $itemOne, ItemTwo: $itemTwo, Duration: $durationAsSeconds, Operation: $processOperation, ObjectType: $objectType"
+ }
+
enum class Operation {
- None, Add, Edit
+ None,
+ Add,
+ Edit
+ }
+
+ enum class ObjectType {
+ TemporaryBasal,
+ Suspend,
}
}
\ No newline at end of file
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/medtronic/src/main/res/values-bg-rBG/strings.xml b/medtronic/src/main/res/values-bg-rBG/strings.xml
index 11b22095af..fcb54883c4 100644
--- a/medtronic/src/main/res/values-bg-rBG/strings.xml
+++ b/medtronic/src/main/res/values-bg-rBG/strings.xml
@@ -70,6 +70,7 @@
Приложи базалният профил
Получи временния базал
Приложи временен базал
+ Откажи временен базал
Стартирай болус
Помпата е недостъпна
Внимание
diff --git a/medtronic/src/main/res/values-de-rDE/strings.xml b/medtronic/src/main/res/values-de-rDE/strings.xml
index eef43f6c40..37d628e324 100644
--- a/medtronic/src/main/res/values-de-rDE/strings.xml
+++ b/medtronic/src/main/res/values-de-rDE/strings.xml
@@ -65,6 +65,8 @@
Hole Verlauf - Seite %1$d (%2$d/16)
Hole Verlauf - Seite %1$d
Hole Pumpen-Zeit
+ Pumpen-Zeit einstellen
+ Akku-Status abfragen
Hole Einstellungen
Hole Pumpenmodel
Hole Basal-Profil
@@ -73,6 +75,7 @@
Setze Temporäre Basalrate
Temp. Basalrate abbrechen
Setze Bolus
+ Verbleibendes Insulin abfragen
Pumpe nicht erreichbar
Warnung
@@ -86,4 +89,5 @@
Pumpenzeit aktualisiert
Neutrale TBR setzen
Wenn diese Option aktiviert ist, wird die TBR vor Ende jeder Stunde abgebrochen. Dies kann dazu beitragen, einige Pumpen davon abzuhalten, zur vollen Stunde zu vibrieren / zu piepsen.
+ %1$.1f U/h (%2$d Minuten verbleibend)
diff --git a/medtronic/src/main/res/values-it-rIT/strings.xml b/medtronic/src/main/res/values-it-rIT/strings.xml
index c4f633ede3..7d0e0e674e 100644
--- a/medtronic/src/main/res/values-it-rIT/strings.xml
+++ b/medtronic/src/main/res/values-it-rIT/strings.xml
@@ -65,13 +65,17 @@
Ottieni storico - Pagina %1$d (%2$d/16)
Ottieni storico - Pagina %1$d
Ottieni ora micro
+ Imposta ora del micro
+ Ottieni stato batteria
Ottieni impostazioni
Ottieni modello micro
Ottieni profilo basale
Imposta profilo basale
Ottieni basale temporanea
Imposta basale temporanea
+ Cancella basale temporanea
Imposta bolo
+ Ottieni insulina rimanente
Micro irraggiungibile
Avviso
@@ -85,4 +89,5 @@
Ora del micro aggiornata
Imposta basali temporanee neutre
Se abilitato, cancellerà una basale temporanea prima della fine di ogni ora. Questo metodo può aiutare a fermare alcuni micro dall\'emettere un suono/vibrare allo scoccare dell\'ora.
+ %1$.1f U/h (%2$d min rimanenti/e)
diff --git a/medtronic/src/main/res/values-ko-rKR/strings.xml b/medtronic/src/main/res/values-ko-rKR/strings.xml
index 1c671da12c..8128024b04 100644
--- a/medtronic/src/main/res/values-ko-rKR/strings.xml
+++ b/medtronic/src/main/res/values-ko-rKR/strings.xml
@@ -25,6 +25,7 @@
Bolus/관리 디버깅
+ 에러
일련번호 # 설정되지 않음
일련번호 # 유효하지않음.
펌프 타입이 설정되지 않았습니다.
@@ -47,6 +48,7 @@
+ 메드트로닉 펌프 이력
펌프에서 이미 설정된 Bolus를 취소했습니다. 메드트로닉 펌프는 취소를 지원하지 않으므로 수동으로 취소해야합니다. (여전히 취소하길 원한다면) 펌프를 일시 중단 모드로 전환 한 다음 다시 시작하십시오. 다음 업데이트시 (5 분 이내에) 변경 사항을 적용합니다.
현재 TBR을 읽을 수 없습니다.
@@ -69,9 +71,14 @@
임시 Basal 설정
Bolus 설정
펌프에 연결할 수 없습니다
+ 경고
+ 현재
+ 전
+ 펌프 시간 업데이트가 필요합니다.
+ 켜짐
끄기
펌프 시간 업데이트
diff --git a/medtronic/src/main/res/values-lt-rLT/strings.xml b/medtronic/src/main/res/values-lt-rLT/strings.xml
index 706db97a5a..7b4dabfb4d 100644
--- a/medtronic/src/main/res/values-lt-rLT/strings.xml
+++ b/medtronic/src/main/res/values-lt-rLT/strings.xml
@@ -25,6 +25,7 @@
NiMH (išplėstinis vaizdas)
Boluso/Terapijos Derinimas
+ RileyLink baterija
Klaidos
Serijos Nr. nenustatytas.
@@ -64,13 +65,17 @@
Gauti istoriją - Lapas %1$d (%2$d/16)
Gauti istoriją - Lapas %1$d
Gauti pompos laiką
+ Nustatyti pompos laiką
+ Parodyti baterijos būseną
Gauti parametrus
Gauti pompos modelį
Gauti bazės profilį
Nustatyti bazės profilį
Gauti laikiną bazę
Nustatyti laikiną bazę
+ Atšaukti laikiną bazę
Nustatyti bolusą
+ Parodyti insulino likutį
Pompa nepasiekiama
Perspėjimas
@@ -84,4 +89,5 @@
Pompos laikas pakeistas
Nustatyti neutralią laikiną bazę
Jei įjungta, laikina valandinė bazė bus anuliuota iki kiekvienos valandos pabaigos. Šis metodas gali padėti išvengti kai kurių pompų pypsėjimo ar vibravimo.
+ %1$.1f vv/h (liko %2$d min)
diff --git a/medtronic/src/main/res/values-no-rNO/strings.xml b/medtronic/src/main/res/values-no-rNO/strings.xml
index 0c93599b2e..cc3e35d7df 100644
--- a/medtronic/src/main/res/values-no-rNO/strings.xml
+++ b/medtronic/src/main/res/values-no-rNO/strings.xml
@@ -65,13 +65,17 @@
Henter historikk - side %1$d (%2$d/16)
Henter historikk - side %1$d
Henter pumpe tid
+ Still pumpens klokke
+ Les batteri status
Henter innstillinger
Henter pumpe modell
Henter basal profil
Angi basal profil
Henter Temp Basal
Angi Temp Basal
+ Avbryt temp basal
Angi Bolus
+ Oppdater status insulinvolum
Pumpe utilgjengelig
Advarsel
@@ -85,4 +89,5 @@
Pumpens tid ble oppdatert
Sett nøytrale temp basaler
Hvis aktivert så vil den stoppe en temp basal rett før hver hele time for å stoppe noen pumpers varsler/vibreringer på hver hele time.
+ %1$.1f E/t (%2$d min gjenstår)
diff --git a/medtronic/src/main/res/values-sk-rSK/strings.xml b/medtronic/src/main/res/values-sk-rSK/strings.xml
index 62ac7c4c3f..6f94f8ebe4 100644
--- a/medtronic/src/main/res/values-sk-rSK/strings.xml
+++ b/medtronic/src/main/res/values-sk-rSK/strings.xml
@@ -65,13 +65,17 @@
Načítanie histórie - Strana %1$d (%2$d/16)
Načítanie histórie - Strana %1$d
Načítanie času pumpy
+ Nastaviť čas pumpy
+ Stav batérie
Načítanie nastavení
Načítanie modelu pumpy
Načítanie bazálneho profilu
Nastavovanie bazálneho profilu
Načítanie dočasného bazálu
Nastavovanie dočasného bazálu
+ Zrušiť dočasný bazál
Nastavovanie bolusu
+ Zostávajúci inzulín
Pumpa nedostupná
Upozornenie
@@ -85,4 +89,5 @@
Čas v pumpe bol aktualizovaný
Nastaviť neutrálny dočasný bazál
Ak je povolená táto možnosť, zastaví sa dočasný bazál pred koncom každej hodiny. To môže u niektorých púmp pomôcť zastaviť pípanie/vibrácie na celú hodinu.
+ %1$.1f JI/h (%2$d min zostáva)
diff --git a/omnipod-common/build.gradle b/omnipod-common/build.gradle
index 19430b670c..aba1f22144 100644
--- a/omnipod-common/build.gradle
+++ b/omnipod-common/build.gradle
@@ -7,13 +7,7 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':core')
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-common/src/main/res/values-lt-rLT/strings.xml b/omnipod-common/src/main/res/values-lt-rLT/strings.xml
index e35fcaa95a..f1350859d8 100644
--- a/omnipod-common/src/main/res/values-lt-rLT/strings.xml
+++ b/omnipod-common/src/main/res/values-lt-rLT/strings.xml
@@ -2,17 +2,198 @@
+ Pod valdymas
+ Veiksmai
+ Įrankiai
+ Aktyvuoti Pod
+ Išjungti Pod
+ Išmesti Pod
+ Jei išmesite Pod, ryšio su juo nebebus galima atkurti. Darykite tai tik tada, kai pastoviai nepavyksta užmegzti ryšio. Jei ryšys visgi yra, naudokite Deaktyvuoti Pod funkciją. \n\nJei norite tęsti, pašalinkite Pod nuo savo kūno!
+ Paleisti bandomąjį signalą
+ Bandomasis signalas paleistas…
+ Pod istorija
+ Nėra aktyvaus Pod
+ Nepavyko nustatyti bazės profilio.
+ Bolusas nepavyko.
+ Nepavyko nustatyti bazinio profilio: gautas tuščias profilis. Įsitikinkite, kad aktyvavote savo bazės profilį.
+ Nėra aktyvaus profilio. Įsitikinkite, kad bazės profilis aktyvuotas.
+ Nepalaikoma pasirinktinė komanda: %1$s
+ Nepavyko atnaujinti būsenos
+ Nepavyko atnaujinti būsenos paleidžiant
+ Nepavyko nutildyti įspėjimų
+ Nepavyko sustabdyti suleidimo
+ Nepavyko nustatyti laiko
+ Nepavyko atnaujinti suleidimo
+ Nepavyko inicijuoti Pod
+ Nepavyko įvesti kaniulės
+ Pod aktyvavimo laikas buvo viršytas. Šis Pod nebegali būti aktyvuotas.
+ Nepavyko patvirtinti aktyvinimo eigos. Pabandykite pakartoti.
+ Pod sustabdyta
+ Nepavyko paleisti bandomojo signalo
+ Neatitinka laikas su Pod. Atnaujinkite laiką skirtuke Omnipod.
+ Įvyko netikėta klaida. Prašome pranešti! (%1$s: %2$s).
+ Patvirtinimas
+ Laikas ir/ar laiko zona Pod pakeista.
+ Įspėjimo konfigūracija Pod atnaujinta.
+ Laikas Pod buvo atnaujintas.
+ Insulino suleidimas buvo sustabdytas.
+ Aktyvūs perspėjimai buvo nutildyti.
+ Insulino suleidimas atnaujintas.
+ Nustatyti laiką
+ Sustabdyta
+ Atnaujinti suleidimą
+ Pod valdymas
+ Tylūs perpėjimai
+ Pod būklė
+ Iš viso suleista
+ %1$.2f vv
+ Unikalus ID
+ LOT numeris
+ Eilės Nr.
+ Pod laikas pasibaigs
+ Paskutinis prisijungimas
+ Paskutinis bolusas
+ Laikina valandinė bazė
+ Pagrindinė valandinė bazė
+ Rezervuaras
+ Aktyvaus Pod signalai
+ Programinės įrangos versija
+ Laikas Pod
+ %1$.2fvv/val @%2$s (%3$d/%4$d min)
+ liko %1$.2f vv
+ Liko daugiau nei 50 vv
+ Klaidos
+ Atšaukti
+ Užbaigti
+ Kitas
+ Bandyti dar kartą
+ Išjungti Pod
+ Išmesti Pod
+ Jūs dar nebaigėte visų veiksmų. Ar tikrai norite išeiti?
+ Išeiti
+ Užpildyti Pod
+ Inicijuoti Pod
+ Prijunkite Pod
+ Paruoškite infuzijos vietą. Nuimkite adatos apsauginį dangtelį, pleistro apsaugą ir užklijuokite Pod ant infuzijos vietos.\n\nJei kaniulė atšoks, paspauskite Atšaukti ir pakeiskite Pod.\n\nSpauskite Kitas, norėdami įvesti kaniulę ir pradėti leisti insuliną.
+ Kai paspausite OK, kaniulė bus įvesta. Įsitikinkite, kad prie infuzijos vietos pritvirtinote Pod.
+ Įvesti kaniulę
+ Mėginkite nustatyti pradinį bazės profilį ir įvesti kaniulę.\n\nKai kaniulė bus sėkmingai įvesta, galite paspausti Kitas.
+ Pod aktyvuotas
+ Naujasis Pod yra dabar aktyvus.\n\nJūsų bazės profilis yra suprogramuotas ir kaniulė įvesta.\n\nPatikrinkite, ar kaniulė buvo tinkamai įvesta, ir, jei jaučiate, kad taip nėra, pakeiskite Pod.
+ Išjungti Pod
+ SpustelėkiteKitas, kad išjungtumėte Pod.\n\nPastaba: Tai sustabdys insulino leidimą ir išjungs Pod.
+ Pod išjungiamas
+ Pod išjungiamas.\n\nKai išjungimas bus sėkmingai baigtas, galite spustelėti Kitas.
+ Pod išjungtas
+ Pod išjungtas.\n\nNuimkite Pod nuo kūno ir jį išmeskite.
+ Pod išmestas
+ Pod statusas atmestas. Insulino tiekimas nesustabdytas, nes Pod nebuvo teisingai deaktyvuotas. \n\nPašalinkite Pod nuo savo kūno ir jį utilizuokite.
+ Jei atmesite Pod, ryšio su juo nebebus galima užmegzti. Darykite tai tik tada, kai visi bandymai užmegzti ryšį nepavyksta. Ar esate tikras, kad norite atmesti Pod?
+ Išmesti Pod
+ Boluso signalai įjungti
+ Bazės signalai įjungti
+ SMB signalai įjungti
+ Laikinos bazės signalai įjungti
+ Omnipod skirtuke rodyti mygtuką Sustabdyti tiekimą
+ Vasaros laiko/Laiko juostos aptikimas įgalintas
+ Galiojimo pabaigos priminimas
+ Valandos prieš išsijungimą
+ Įgalintas įspėjimas apie žemą rezervuaro lygį
+ Vienetų skaičius
+ Automatiškai nutildyti Pod perspėjimus
+ Kiti
+ Perspėjimai
+ Patvirtinimo signalai
+ Nėra aktyvaus Pod
+ Vykdomas nustatymas (laukiama Pod aktyvavimo)
+ Vykdomas nustatymas (laukiama kaniulės įvedimo)
+ Vykdoma
+ Sustabdyta
+ Pod klaida
+ Viršytas aktyvinimo laikas
+ Neaktyvus
+ Pod klaida: %1$03d %2$s
+ Išjungti Pod
+ Išmesti Pod
+ Nustatyti bolusą
+ Atšaukti bolusą
+ Nustatyti laikiną bazę
+ Atšaukti laikiną bazę (vidinis valdiklis)
+ Atšaukti laikiną bazę
+ Nustatyti bazės tvarkaraštį
+ Gauti Pod būseną
+ Gauti Pod informaciją
+ Nustatyti laiką
+ Konfigūruoti perspėjimus
+ Tylūs perpėjimai
+ Sustabdyti suleidimą
+ Atnaujinti suleidimą
+ Nežinomas Įrašas
+ Inicijuoti Pod
+ Įvesti kaniulę
+ Skaityti Pulse žurnalą
+ Nustatykite netikrą laikiną bazę, nes Pod sustabdyta
+ Atšaukite netikrą laikiną bazę, kuri buvo nustatyta dėl to, kad Pod buvo sustabdyta
+ Laikina bazė padalinta dėl nežinomos klaidos atšaukiant ją
+ Signalo nustatymai
+ Paleisti bandomąjį signalą
+ Priminimas apie suporavimo pabaigą
+ Priminimas apie sąrankos pabaigą
+ Pod galiojimas greitai baigsis
+ Pod galiojimas greitai baigsis
+ Išjungimas yra neišvengiamas
+ Žemas rezervuaro lygis
+ Nežinomas perspėjimas
+ Nėra aktyvaus Pod
+ Pask. prisijung.: prieš %1$d min
+ Pask.Bolusas: %1$s @ %2$s
+ Laik.bazė: %1$s
+ Ištęstas: %1$s
+ Rezerv: %1$svv
+ Taip
+ Ne
+ OK
+ Atšaukti
+ Perspėjimas
+ Neseniai
+ Mažiau nei prieš minutę
+ %1$s ir %2$s
+ prieš %1$s
+
+ - %1$d min
+ - %1$d min
+ - %1$d min
+ - %1$d min
+
+
+ - %1$d val
+ - %1$d val
+ - %1$d val
+ - %1$d val
+
+
+ - %1$d d.
+ - %1$d d.
+ - %1$d d.
+ - %1$d d.
+
+
+ - Pod aliarmas: %1$s
+ - Pod aliarmai: %1$s
+ - Pod aliarmai: %1$s
+ - Pod aliarmai: %1$s
+
diff --git a/omnipod-dash/build.gradle b/omnipod-dash/build.gradle
index e48b09f3c7..2ad14d8d0d 100644
--- a/omnipod-dash/build.gradle
+++ b/omnipod-dash/build.gradle
@@ -9,13 +9,7 @@ apply plugin: "org.jlleitschuh.gradle.ktlint" // TODO move to `subprojects` sect
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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
allOpen {
annotation 'info.nightscout.androidaps.plugins.pump.omnipod.dash.annotations.OpenClass'
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt
index 2e54cd7f3d..24370e0053 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt
@@ -500,7 +500,6 @@ class OmnipodDashPumpPlugin @Inject constructor(
private fun updateBolusProgressDialog(msg: String, percent: Int) {
val progressUpdateEvent = EventOverviewBolusProgress
- val percent = percent
progressUpdateEvent.status = msg
progressUpdateEvent.percent = percent
rxBus.send(progressUpdateEvent)
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt
index 24885e70e2..68a4f54960 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt
@@ -69,7 +69,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(
emitter.tryOnError(MessageIOException("XXX random failure to test unconfirmed commands"))
return@create
}*/
- when (val readResult = session.readAndAckResponse(responseType)) {
+ when (val readResult = session.readAndAckResponse()) {
is CommandReceiveSuccess ->
emitter.onNext(PodEvent.ResponseReceived(cmd, readResult.result))
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapAkaAttribute.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapAkaAttribute.kt
index 3d035e37c6..94379b181c 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapAkaAttribute.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapAkaAttribute.kt
@@ -29,7 +29,7 @@ sealed class EapAkaAttribute {
const val SIZE_MULTIPLIER = 4 // The length for EAP-AKA attributes is a multiple of 4
- fun parseAttributes(aapsLogger: AAPSLogger, payload: ByteArray): List {
+ fun parseAttributes(payload: ByteArray): List {
var tail = payload
val ret = LinkedList()
while (tail.isNotEmpty()) {
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessage.kt
index 9c252b3eec..2b6bcd81f0 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessage.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/EapMessage.kt
@@ -82,7 +82,7 @@ data class EapMessage(
return EapMessage(
code = EapCode.byValue(payload[0]),
identifier = payload[1],
- attributes = EapAkaAttribute.parseAttributes(aapsLogger, attributesPayload).toTypedArray(),
+ attributes = EapAkaAttribute.parseAttributes(attributesPayload).toTypedArray(),
subType = payload[5],
)
}
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/Session.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/Session.kt
index 3819ee8d05..87fccc725e 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/Session.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/session/Session.kt
@@ -64,7 +64,7 @@ class Session(
}
@Suppress("ReturnCount")
- fun readAndAckResponse(responseType: KClass): CommandReceiveResult {
+ fun readAndAckResponse(): CommandReceiveResult {
var responseMsgPacket: MessagePacket? = null
for (i in 0..MAX_TRIES) {
val responseMsg = msgIO.receiveMessage()
@@ -113,10 +113,10 @@ class Session(
// TODO verify length
- val uniqueId = data.copyOfRange(0, 4)
- val lenghtAndSequenceNumber = data.copyOfRange(4, 6)
+ //val uniqueId = data.copyOfRange(0, 4)
+ //val lenghtAndSequenceNumber = data.copyOfRange(4, 6)
val payload = data.copyOfRange(6, data.size - 2)
- val crc = data.copyOfRange(data.size - 2, data.size)
+ //val crc = data.copyOfRange(data.size - 2, data.size)
// TODO validate uniqueId, sequenceNumber and crc
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt
index c363048557..5ce3028b0c 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt
@@ -199,7 +199,7 @@ object ProgramBasalUtil {
val index = ((hourOfDay * 60 + minuteOfHour) / 30).toByte()
val secondOfDay = secondOfMinute + hourOfDay * 3600 + minuteOfHour * 60
val secondsRemaining = ((index + 1) * 1800 - secondOfDay).toShort()
- val pulsesRemaining = (pulsesPerSlot!![index.toInt()].toDouble() * secondsRemaining / 1800).toShort()
+ val pulsesRemaining = (pulsesPerSlot!![index.toInt()].toDouble() * secondsRemaining / 1800).toInt().toShort()
return CurrentSlot(index, (secondsRemaining * 8).toShort(), pulsesRemaining)
}
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt
index 839a508615..fcb83b64de 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt
@@ -24,7 +24,7 @@ object ProgramTempBasalUtil {
val tenthPulsesPerSlot = ShortArray(durationInSlots)
var i = 0
while (durationInSlots > i) {
- tenthPulsesPerSlot[i] = (roundToHalf(pulsesPerHour / 2.0) * 10).toShort()
+ tenthPulsesPerSlot[i] = (roundToHalf(pulsesPerHour / 2.0) * 10).toInt().toShort()
i++
}
return tenthPulsesPerSlot
diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt
index ed2e9d88d4..2656a6149c 100644
--- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt
+++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt
@@ -444,6 +444,7 @@ class OmnipodDashPodStateManagerImpl @Inject constructor(
createdRealtime = now,
sentRealtime = now + 1
)
+ podState.activeCommand = newCommand
podState.lastStatusResponseReceived = 0
}
diff --git a/omnipod-dash/src/main/res/values-lt-rLT/strings.xml b/omnipod-dash/src/main/res/values-lt-rLT/strings.xml
index c690568d07..582abcf0f6 100644
--- a/omnipod-dash/src/main/res/values-lt-rLT/strings.xml
+++ b/omnipod-dash/src/main/res/values-lt-rLT/strings.xml
@@ -1,6 +1,9 @@
+ Pompos integracija Omnipod Dash (naujas, Bluetooth palaikantis modelis su mėlynu adatos dangteliu).
+ Bluetooth statusas
+ Bluetooth adresas
diff --git a/omnipod-eros/build.gradle b/omnipod-eros/build.gradle
index e530957c56..db27c83b0e 100644
--- a/omnipod-eros/build.gradle
+++ b/omnipod-eros/build.gradle
@@ -6,13 +6,7 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':core')
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 f150f6a560..743d5c4ca7 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 05989f9c08..e7db508773 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 ce16ca31f0..090e754eb2 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;
@@ -36,9 +35,6 @@ public class RileyLinkOmnipodService extends RileyLinkService {
@Inject OmnipodErosPumpPlugin omnipodErosPumpPlugin;
@Inject AapsOmnipodUtil aapsOmnipodUtil;
- @Inject ErosPodStateManager podStateManager;
- @Inject DatabaseHelperInterface databaseHelper;
- @Inject AapsOmnipodErosManager aapsOmnipodErosManager;
@Inject OmnipodRileyLinkCommunicationManager omnipodRileyLinkCommunicationManager;
private final IBinder mBinder = new LocalBinder();
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");
}
diff --git a/omnipod-eros/src/main/res/values-bg-rBG/strings.xml b/omnipod-eros/src/main/res/values-bg-rBG/strings.xml
index bc89093c83..5b26a40bd0 100644
--- a/omnipod-eros/src/main/res/values-bg-rBG/strings.xml
+++ b/omnipod-eros/src/main/res/values-bg-rBG/strings.xml
@@ -4,10 +4,68 @@
+ Конфигурация на RileyLink
+ Известия
+ Показване на PULSE LOG в менюто на Pod Management
+ Показване на RileyLink Stats бутон в меню Управление на Pod
+ Позволи на записване на смяна на батерията в Действия
+ RileyLink
+ Сигнал при неясни TBR известия, разрешен
+ Сигнал при неясни SMB известия, разрешен
+ Сигнал при неясни болус известия, разрешен
+ История в Pod
+ Описание
+ Източник
+ Дата
+ Тип:
+ %1$.2fЕ
+ %1$.2f Е, Вх=%2$.1f гр
+ Количество: %1$.2f U, Продължителност: %2$d мин
+ RL бат: %1$d
+ Грешен RileyLink адрес.
+ Неуспешна комуникация: проверката на цялостта на съобщението е неуспешна
+ Неуспешна комуникация: получиен невалиден пакет от под
+ Неуспешна комуникация: под е в грешно състояние
+ Неуспешна комуникация: получени грешен отговор от под
+ Неуспешна комуникация: получи съобщение с невалиден номер на последователност от Pod
+ Неуспешна комуникация: получено съобщение с невалиден адрес от Pod
+ Неуспешна комуникация: неуспешно декодиране на съобщение от Pod
+ Комуникацията е неуспешна: ресинхронизирането е неуспешно
+ Комуникацията е неуспешна: ресинхронизирането е неуспешно
+ Комуникацията е неуспешна: не достатъчно данни получени от Pod
+ Грешка на Pod (%1$03d %2$s). Моля, деактивирайте вашия Pod и стартирайте нов
+ Комуникацията е неуспешна: Pod върна отговор с грешка
+ Няма отговор от RileyLink
+ RileyLink прекъснат
+ Няма отговор от Pod
+ Неуспешно задаване на базален профил. Доставката на инсулин може да бъде спряна! Моля, ръчно опреснете състоянието на Pod от раздел Omnipod и възобновете доставката, ако е необходимо.
+ Неуспешно задаване на базален профил. Доставката на инсулин може да бъде спряна! Моля, ръчно опреснете състоянието на Pod от раздел Omnipod и възобновете доставката, ако е необходимо.
+ Неуспешно задаване на базален профил. Инсулинът е спрян! Моля, ръчно подновяване на доставката от раздела Omnipod.
+ Отменянето на временния базал може да е неуспешно. Моля, ръчно опреснете статуса на Pod от раздел Omnipod.
+ Задаването на временен базал е неуспешно. Ако преди това е изпълнявал временен базал, може да е бил отменен. Моля, ръчно опреснете статуса на Pod от раздела Omnipod.
+ Задаването на временен базал е неуспешно. Ако преди това е имало временен базал, може да е бил отменен. Моля, ръчно опреснете статуса на Pod от раздела Omnipod.
+ Продължителността трябва да бъде по-голяма от нула и кратно на %1$s минути.
+ Неуспешно задаване на базален профил. Доставката на инсулин може да бъде спряна! Моля, ръчно опреснете състоянието на Pod от раздел Omnipod и възобновете доставката, ако е необходимо.
+ Неуспешно задаване на време. Инсулинът е спрян! Моля, ръчно подновяване на доставката от раздела Omnipod.
+ Неуспешно прочитане на Pulse Log
+ Неуспешно променяне на времето на под. Трябва ръчно да синхронизирате времето в раздела Omnipod.
+ Забранено действие.\n\n Първо трябва да конфигурурате Omnipod , преди да използвате тази операция,.
+ Не може да се провери дали болус е поставен. Моля, уверете се ръчно, че Вашият Pod се активира чрез слушане на кликвания. Ако сте сигурни, че болус не е успял, вие трябва ръчно да изтриете болния запис от лечение, дори ако щракнете върху \'Отказ от болус\' сега!
+ Не може да се провери дали SMB болус(%1$.2f Е) е успешен. Ако сте сигурни, че не е успял, трябва ръчно да изтриете запис SMB от леченията.
+ В Pod има пуснат временен базал но AAPS не знае за него. Моля, отменете временния си базал ръчно.
+ RileyLink статистика
+ Изчакване на RileyLink връзка…
+ Изчисти RileyLink конфигурацията
+ Прочети Pulse log
+ Четене на Pulse log…
+ Pulse лог
+ Pulse log(копиран в клипборда)
+ Опитвам се да се сдвоя с Pod.\n\nКогато всички елементи са проверени, можете да натиснете Следващ.\n\nЗабележка: задръжте Pod много близо до RileyLink в този момент.
+ неизвестно
diff --git a/omnipod-eros/src/main/res/values-lt-rLT/strings.xml b/omnipod-eros/src/main/res/values-lt-rLT/strings.xml
index bc89093c83..eba4dded84 100644
--- a/omnipod-eros/src/main/res/values-lt-rLT/strings.xml
+++ b/omnipod-eros/src/main/res/values-lt-rLT/strings.xml
@@ -1,13 +1,73 @@
+ Pompos integravimas su Omnipod Eros (senesnis modelis su skaidriu adatos dangteliu). Reikalingas RileyLink įrenginys, su 2.0 ir naujesne programinės įrangos versija.
+ RileyLink konfigūravimas
+ Pranešimai
+ Pod valdymo meniu rodyti mygtuką Pulse log
+ Pod valdymo meniu rodyti mygtuką RileyLink Stats
+ Įgalinti baterijos keitimo registravimą veiksmuose
+ RileyLink
+ Įjungtas garsas neaiškiems laikinos bazės perspėjimams
+ Įjungtas garsas neaiškiems SMB perspėjimams
+ Įjungtas garsas neaiškiems bolusų perspėjimams
+ Pod istorija
+ Aprašymas
+ Šaltinis
+ Data
+ Tipas:
+ %1$.2f vv
+ %1$.2f vv, AV=%2$.1f g
+ Kiekis: %1$.2f vv, trukmė: %2$d min
+ RLBatt: %1$d
+ RileyLink adresas neteisingas.
+ Ryšio klaida: pranešimo vientisumo patikra nepavyko
+ Ryšio klaida: netinkami įvesties iš Pod parametrai
+ Ryšio klaida: Pod būklė yra netinkama
+ Ryšio klaida: gautas netinkamas atsakymas iš Pod
+ Ryšio klaida: iš Pod gautas pranešimas su negaliojančiu serijos numeriu
+ Ryšio klaida: iš Pod gautas pranešimas su netinkamu adresu
+ Ryšio klaida: nepavyko iššifruoti pranešimo iš Pod
+ Ryšio klaida: nepavyko iš naujo sinchronizuoti unikalų kodą
+ Ryšio klaida: unikalus kodas nebuvo sinchronizuotas
+ Ryšio klaida: iš Pod gauta nepakankamai duomenų
+ Aptikta Pod klaida (%1$03d %2$s). Deaktyvuokite Pod ir aktyvuokite naują
+ Ryšio klaida: Pod pateikė klaidos atsakymą
+ Nėra atsakymo iš RileyLink
+ RileyLink ryšys pertrauktas
+ Nėra atsakymo iš Pod
+ Nepavyko nustatyti bazės profilio. Insulino leidimas gali būti nutrauktas! Rankiniu būdu atnaujinkite Pod būseną Omnipod skirtuke ir, jei reikia, atnaujinkite insulino leidimą.
+ Gali būti, kad bazės profilis nebuvo nustatytas. Insulino leidimas gali būti nutrauktas! Rankiniu būdu atnaujinkite Pod būseną Omnipod skirtuke ir, jei reikia, atnaujinkite insulino leidimą.
+ Nepavyko nustatyti bazės profilio. Insulino leidimas buvo sustabdytas! Rankiniu būdu iš Omnipod skirtuko atnaujinkite insulino leidimą.
+ Gali būti, kad laikinos bazės atšaukti nepavyko. Omnipod skirtuke rankiniu būdu atnaujinkite Pod statusą.
+ Nepavyko nustatyti laikinos valandinės bazės. Jei laikina bazė buvo pradėta anksčiau, ji gali būti atšaukta. Rakiniu būdu atnaujinkite Pod būseną Omnipod skirtuke.
+ Gali būti, kad nepavyko nustatyti laikinos valandinės bazės. Jei laikina bazė buvo nustatyta anksčiau, ji yra atšaukta. Rakiniu būdu atnaujinkite Pod būseną Omnipod skirtuke.
+ Laikinos bazės trukmė turi būti didesnis už nulį %1$s min. kartotinis.
+ Gali būti, kad laikas nebuvo nustatytas. Insulino leidimas gali būti nutrauktas! Rankiniu būdu atnaujinkite Pod būseną Omnipod skirtuke ir, jei reikia, atnaujinkite insulino leidimą.
+ Nepavyko nustatyti laiko. Insulino leidimas sustabdytas! Rankiniu būdu atnaujinkite insulino leidimą iš Omnipod skirtuko.
+ Nepavyko perskaityti Pulse žurnalo
+ Nepavyko automatiškai pakeisti Pod laiko. Jūs turėtumėte sinchronizuoti laiką rankiniu būdu Omnipod skirtuke.
+ Operacija negalima.\n\nPirmiausia turite sukonfigūruoti Omnipod pompą prieš atliekant šią operaciją.
+ Nepavyko patikrinti, ar buvo suleistas bolusas. Patikrinkite, ar Pod leidžia bolusą (klausantis boluso garsų). Jei esate tikri, kad bolusas nebuvo suleistas, turite rankiniu būdu ištrinti boluso įrašą iš Terapijos, net jei dabar spustelėjote mygtuką „Atšaukti bolusą“!
+ Nepavyko patikrinti, ar SMB (%1$.2fvv) suleistas. Jei esate tikri, kad bolusas nebuvo suleistas, turite rankiniu būdu pašalinti SMB įrašą iš Terapijos.
+ Pod veikia laikina bazė, bet AAPS neinformuota apie šią laikiną bazę. Atšaukite laikiną bazę rankiniu būdu.
+ RileyLink statusas
+ Laukiama RileyLink ryšio…
+ Išvalyti RileyLink nustatymus
+ Skaityti Pulse žurnalą
+ Skaitomas Pulse žurnalas…
+ Pulse žurnalas
+ Pulse žurnalas (nukopijuotas į mainų sritį)
+ Užpildykite naują Pod insulinu, kurio pakaktų 3 dienoms.\n\nTaip pat atkreipkite dėmesį į du pyptelėjimus iš Pod, kai pildote. Tai rodo, kad rezervuaras buvo užpildytas mažiausiai 80vv. Visiškai ištuštinkite švirkštą, net jei girdėjote du pyptelėjimus.\n\nUžpildę Pod, spustelėkite Kitas.\n\nPastaba: vykdant šiuos veiksmus, nenuimkite Pod adatos apsauginio dangtelio.\nPastaba: padėkite RileyLink vertikalioje pozicijoje ir Pod kelių colių atstumu vienas nuo kito.
+ Pabandykite suporuoti naują Pod ir užpildykite jį.\n\nKai inicijavimo procesas bus užbaigtas sėkmingai, galite spustelėti Kitas.\n\n Pastaba: padėkite RileyLink vertikalioje pozicijoje ir Pod kelių colių atstumu vienas nuo kito.
+ neaiški
diff --git a/pump-common/build.gradle b/pump-common/build.gradle
index 996daf31dd..5bb1a09fa4 100644
--- a/pump-common/build.gradle
+++ b/pump-common/build.gradle
@@ -6,19 +6,13 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
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'
}
}
diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpDbEntry.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpDbEntry.kt
index e1b734b048..918fc9d3ee 100644
--- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpDbEntry.kt
+++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/sync/PumpDbEntry.kt
@@ -59,5 +59,5 @@ data class PumpDbEntryCarbs(var date: Long,
data class PumpDbEntryTBR(var rate: Double,
var isAbsolute: Boolean,
- var durationInMinutes: Int,
+ var durationInSeconds: Int,
var tbrType: PumpSync.TemporaryBasalType)
\ No newline at end of file
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..dd4a55dced 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
@@ -22,7 +22,7 @@ class PumpSyncStorage @Inject constructor(
val aapsLogger: AAPSLogger
) {
- val pumpSyncStorageKey: String = "pump_sync_storage_xstream"
+ val pumpSyncStorageKey: String = "pump_sync_storage_xstream_v2"
var pumpSyncStorage: MutableMap> = mutableMapOf()
var TBR: String = "TBR"
var BOLUS: String = "BOLUS"
@@ -32,6 +32,7 @@ class PumpSyncStorage @Inject constructor(
init {
initStorage()
+ cleanOldStorage();
}
fun initStorage() {
@@ -46,7 +47,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
}
}
@@ -64,6 +67,15 @@ class PumpSyncStorage @Inject constructor(
}
}
+ fun cleanOldStorage(): Unit {
+ val oldSpKeys = setOf("pump_sync_storage", "pump_sync_storage_xstream")
+
+ for (oldSpKey in oldSpKeys) {
+ if (sp.contains(oldSpKey))
+ sp.remove(oldSpKey)
+ }
+ }
+
fun isStorageEmpty(): Boolean {
return pumpSyncStorage[BOLUS]!!.isEmpty() && pumpSyncStorage[TBR]!!.isEmpty()
}
@@ -97,7 +109,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()
}
@@ -123,7 +139,7 @@ class PumpSyncStorage @Inject constructor(
val response = pumpSync.addTemporaryBasalWithTempId(
timenow,
temporaryBasal.rate,
- (temporaryBasal.durationInMinutes * 60L * 1000L),
+ (temporaryBasal.durationInSeconds * 1000L),
temporaryBasal.isAbsolute,
temporaryId,
temporaryBasal.tbrType,
diff --git a/rileylink/build.gradle b/rileylink/build.gradle
index 96f2bfa148..edbb3c241d 100644
--- a/rileylink/build.gradle
+++ b/rileylink/build.gradle
@@ -6,13 +6,7 @@ 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"
- }
-}
+apply from: "${project.rootDir}/gradle/jacoco_global.gradle"
dependencies {
implementation project(':core')
diff --git a/rileylink/src/main/res/values-it-rIT/strings.xml b/rileylink/src/main/res/values-it-rIT/strings.xml
index 6834a842e1..cdce27e5aa 100644
--- a/rileylink/src/main/res/values-it-rIT/strings.xml
+++ b/rileylink/src/main/res/values-it-rIT/strings.xml
@@ -64,6 +64,7 @@
Sì
No
+ Mostra livello batteria riportato da OrangeLink/EmaLink/DiaLink
NON funziona con il RileyLink originale. Potrebbe non funzionare con altre alternative al RileyLink.
- %1$d giorno
diff --git a/rileylink/src/main/res/values-lt-rLT/strings.xml b/rileylink/src/main/res/values-lt-rLT/strings.xml
index 634fc8393c..c269516114 100644
--- a/rileylink/src/main/res/values-lt-rLT/strings.xml
+++ b/rileylink/src/main/res/values-lt-rLT/strings.xml
@@ -22,15 +22,23 @@
Pompos statusas
RileyLink parametrai
RileyLink
+ Adresas:
+ Vardas:
+ Baterijos lygis:
+ %1$d%%
Ryšio būsena:
Prisijungimo klaida:
Įrenginys
Įrenginio tipas:
+ Nustatytas įrenginio modelis:
+ Prijungtas įrenginio modelis:
Paskutinis naudotas dažnis:
Paskutinis įrenginio kontaktas:
Programinės įrangos versija:
+ BLE113: %1$s\nCC110: %2$s
Pompos serijos Nr:
Pompos dažnis:
+ %1$.2f MHz
Inicijuojamas Bluetooth…
Bluetooth klaida
@@ -52,9 +60,12 @@
Pod nepasiekiamas
Pompa Medtronic
+ Omnipod (Eros)
Taip
Ne
+ Rodyti baterijos įkrovimo lygį, gautą iš OrangeLink/EmaLink/DiaLink
+ NEVEIKIA su originaliu RileyLink. Gali neveikti su kitomis RileyLink alternatyvomis.
- %1$d d.
- %1$d d.
diff --git a/rileylink/src/main/res/values-no-rNO/strings.xml b/rileylink/src/main/res/values-no-rNO/strings.xml
index ab5d3058ae..a9e91e1de2 100644
--- a/rileylink/src/main/res/values-no-rNO/strings.xml
+++ b/rileylink/src/main/res/values-no-rNO/strings.xml
@@ -64,6 +64,7 @@
Ja
Nei
+ Vis batterinivå rapportert av OrangeLink/EmaLink/DiaLink
Virker IKKE med RileyLink. Kan hende den ikke fungerer med andre RileyLink alternativer.
- %1$d dag
diff --git a/settings.gradle b/settings.gradle
index 15a8fcf539..97c317e0d3 100644
--- a/settings.gradle
+++ b/settings.gradle
@@ -14,4 +14,5 @@ include ':medtronic'
include ':omnipod-common'
include ':omnipod-eros'
include ':omnipod-dash'
+include ':diaconn'
diff --git a/wear/build.gradle b/wear/build.gradle
index 237d585dfc..c72db5dfa5 100644
--- a/wear/build.gradle
+++ b/wear/build.gradle
@@ -15,7 +15,12 @@ apply plugin: 'kotlin-android'
apply plugin: 'com.hiya.jacoco-android'
jacoco {
- toolVersion = "0.8.6"
+ toolVersion = "0.8.7"
+}
+
+tasks.withType(Test) {
+ jacoco.includeNoLocationClasses = true
+ jacoco.excludes = ['jdk.internal.*']
}
ext {
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);
diff --git a/wear/src/main/res/values-lt-rLT/strings.xml b/wear/src/main/res/values-lt-rLT/strings.xml
index 10de13c2dd..e8c4ea8e0b 100644
--- a/wear/src/main/res/values-lt-rLT/strings.xml
+++ b/wear/src/main/res/values-lt-rLT/strings.xml
@@ -89,6 +89,9 @@
PATVIRTINTI
laiko postūmis
bolusas
+ Leidžiamas bolusas
+ paspauskite atšaukimui
+ ATŠAUKTI BOLUSĄ
Pompa
Ciklas
CPP (Procentinis dienos profilis)