From 23874ebbd652d663cbb356dd66a496e78777394a Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Tue, 5 Dec 2017 01:24:43 +0100 Subject: [PATCH 01/39] Remove 'sync to profile' pref. (cherry picked from commit 01c52e7) --- .../nightscout/androidaps/PreferencesActivity.java | 4 ---- .../CircadianPercentageProfilePlugin.java | 3 --- .../plugins/Wear/ActionStringHandler.java | 3 --- .../androidaps/receivers/KeepAliveReceiver.java | 2 +- app/src/main/res/values-bg/strings.xml | 1 - app/src/main/res/values-cs/strings.xml | 1 - app/src/main/res/values-de/strings.xml | 1 - app/src/main/res/values-es/strings.xml | 1 - app/src/main/res/values-it/strings.xml | 1 - app/src/main/res/values-ko/strings.xml | 1 - app/src/main/res/values-nl/strings.xml | 1 - app/src/main/res/values-ru/strings.xml | 1 - app/src/main/res/values-sv/strings.xml | 1 - app/src/main/res/values/strings.xml | 1 - app/src/main/res/xml/pref_profile.xml | 13 ------------- 15 files changed, 1 insertion(+), 34 deletions(-) delete mode 100644 app/src/main/res/xml/pref_profile.xml diff --git a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java index 6706e88fd9..ed201d7c97 100644 --- a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java @@ -149,10 +149,6 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), PluginBase.SENSITIVITY); addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginBase.SENSITIVITY); - if (!Config.NSCLIENT && !Config.G5UPLOADER) { - addPreferencesFromResource(R.xml.pref_profile); - } - if (Config.DANAR) { addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginBase.PUMP); addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginBase.PUMP); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java index 949e7d1cf3..5315910899 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileCircadianPercentage/CircadianPercentageProfilePlugin.java @@ -182,9 +182,6 @@ public class CircadianPercentageProfilePlugin implements PluginBase, ProfileInte if (timeshift < 0 || timeshift > 23) { msg += String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Timeshift") + "\n"; } - if (!SP.getBoolean("syncprofiletopump", false)) { - msg += MainApp.sResources.getString(R.string.syncprofiletopump_title) + " " + MainApp.sResources.getString(R.string.cpp_sync_setting_missing) + "\n"; - } final Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null || profile.getBasal() == null) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java index 6511cedbdf..dce7023afe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java @@ -582,9 +582,6 @@ public class ActionStringHandler { if (timeshift < 0 || timeshift > 23) { msg += String.format(MainApp.sResources.getString(R.string.openapsma_valueoutofrange), "Profile-Timeshift") + "\n"; } - if (!SP.getBoolean("syncprofiletopump", false)) { - msg += MainApp.sResources.getString(R.string.syncprofiletopump_title) + " " + MainApp.sResources.getString(R.string.cpp_sync_setting_missing) + "\n"; - } final Profile profile = MainApp.getConfigBuilder().getProfile(); if (profile == null || profile.getBasal() == null) { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index 38ca9ee2a1..83fa84e069 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -90,7 +90,7 @@ public class KeepAliveReceiver extends BroadcastReceiver { MainApp.bus().post(new EventNewNotification(n)); } - if (SP.getBoolean("syncprofiletopump", false) && !pump.isThisProfileSet(profile)) { + if (!pump.isThisProfileSet(profile)) { MainApp.getConfigBuilder().getCommandQueue().setProfile(profile, null); } else if (isStatusOutdated && !pump.isBusy()) { MainApp.getConfigBuilder().getCommandQueue().readStatus("KeepAlive. Status outdated.", null); diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 75d2cb20c2..5d46908f57 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -212,7 +212,6 @@ Свързване Свързана Не е сврзана - Синхронизирай помпата с профила DanaR настройки Nightscout End User License Agreement diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index c619655866..1d43753930 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -192,7 +192,6 @@ Odpojeno DanaR Bluetooth zařízení DanaR nastavení - Synchronizovat profil do pumpy Nightscout Absolutní Komentář diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 9a4d839fec..96e19bec97 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -226,7 +226,6 @@ vor h SMS Kommunikator erlaubte Telefonnummern - Profil zur Pumpe synchronisieren auf Pumpenergebnis warten Kein Bluetoothadapter gefunden Remote Bolus ist nicht erlaubt diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 3c8450676f..a87b40330f 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -201,7 +201,6 @@ Conectando Conectado Desconectado - Sincronizar perfil a bomba Ajustes de la bomba DanaR Nightscout Acuerdo de licencia de usuario final diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index f52357dd0a..5e72429865 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -372,7 +372,6 @@ Sospendi loop per 1h Sospendi loop per 2h Sospendi loop per 3h - Sincronizza profilo sul micro Target range: Adolescente IOB: diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index b4bd725ce4..538dbb2023 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -213,7 +213,6 @@ 연결중 연결됨 연결 끊김 - 프로파일을 펌프에 동기화하기 다나R 펌프 설정 Nightscout 최종 사용자 라이선스 동의서 diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 1bcfc2736f..a9151cde59 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -626,7 +626,6 @@ Standaard waarde: 2 Bolus snooze is actief nadat je een maaltijd bolus toegediend hebt, zodat de loop geen tegenvoorstel met een verlaagd tijdelijk basaal doet nadat je gegeten hebt. Het voorbeeld hier van van standaard 2; dus een 3 u DIA betekent dat de bolus snooze gemiddeld 1.5u actief is (3DIA/2). Standaard waarde: 4 Dit is een combinatie van enerzijds het OpenAPS veiligheid limieten en anderzijds van “3 x max dagelijks basaal ; 4x actueel”. Dit betekent dat het basaal niet hoger kan ingesteld worden dan het ingestelde nummer keer het actueel basaal waarbij de limiet in de pomp geen invloed heeft.Dit is een veiligheidsmaatregel om te vermijden dat patiënten in gevaarlijke laag bereik komen zonder te snappen hoe het algoritme werkt. Nogmaals de standaard waarde is 4x; de meeste zullen deze waarde nooit moeten aanpassen maar zullen eerder andere waardes moeten aanpassen als ze tegen een limiet aanstoten. Gedurende 1 week succesvol closed loop met KH ingave - Synchroniseer profiel met de pomp ACTIVITIJD & FEEDBACK Model: %02X Protokoll: %02X Code: %02X Verbonden gedurende %d s diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index a2084cb0cb..ba0e44644c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -486,7 +486,6 @@ приостановить цикл на 1 час приостановить цикл на 2 часа приостановить цикл на 3 часа - синхронизировать профиль с помпой целевой диапазон подросток ошибка доставки врем базала diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index b7527f85ad..9b84ac7660 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -362,7 +362,6 @@ Tonåring Mål saknas i profil. Använder grundinställning Mål gränser: - Uppdatera profil till pump Stäng av loop i 3 h Stäng av loop i 2 h Stäng av loop i 1 h diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e8918979b3..a3a7b76262 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -223,7 +223,6 @@ Connecting Connected Disconnected - Sync profile to pump DanaR pump settings Nightscout End User License Agreement diff --git a/app/src/main/res/xml/pref_profile.xml b/app/src/main/res/xml/pref_profile.xml deleted file mode 100644 index e8a1289047..0000000000 --- a/app/src/main/res/xml/pref_profile.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - \ No newline at end of file From ab456d5966b52163aa80a66c896773aed514110e Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 6 Dec 2017 12:05:39 +0100 Subject: [PATCH 02/39] Remove missed reference to pref in NSProfilePlugin. --- .../plugins/ProfileNS/NSProfilePlugin.java | 20 +++++++++---------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java index f4b4aaabcc..d3fedfd9c8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java @@ -120,19 +120,17 @@ public class NSProfilePlugin implements PluginBase, ProfileInterface { profile = new ProfileStore(newProfile.getData()); storeNSProfile(); MainApp.bus().post(new EventNSProfileUpdateGUI()); - if (SP.getBoolean("syncprofiletopump", false)) { - ConfigBuilderPlugin.getCommandQueue().setProfile(MainApp.getConfigBuilder().getProfile(), new Callback() { - @Override - public void run() { - if (result.enacted) { - SmsCommunicatorPlugin smsCommunicatorPlugin = MainApp.getSpecificPlugin(SmsCommunicatorPlugin.class); - if (smsCommunicatorPlugin != null && smsCommunicatorPlugin.isEnabled(PluginBase.GENERAL)) { - smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.sResources.getString(R.string.profile_set_ok)); - } + ConfigBuilderPlugin.getCommandQueue().setProfile(MainApp.getConfigBuilder().getProfile(), new Callback() { + @Override + public void run() { + if (result.enacted) { + SmsCommunicatorPlugin smsCommunicatorPlugin = MainApp.getSpecificPlugin(SmsCommunicatorPlugin.class); + if (smsCommunicatorPlugin != null && smsCommunicatorPlugin.isEnabled(PluginBase.GENERAL)) { + smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.sResources.getString(R.string.profile_set_ok)); } } - }); - } + } + }); } private static void storeNSProfile() { From b98c321cbc3d24ef5354342b2c27a298733dba97 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 12 Dec 2017 00:12:35 +0100 Subject: [PATCH 03/39] NS offline --- .../broadcasts/BroadcastTreatment.java | 49 ++++---- .../receivers/DBAccessReceiver.java | 23 +++- .../services/NSClientService.java | 112 +++++++++--------- 3 files changed, 96 insertions(+), 88 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java index c6158be296..43c46bf072 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java @@ -1,10 +1,7 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; -import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; -import android.os.TransactionTooLargeException; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONArray; @@ -19,9 +16,7 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.Services.Intents; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; import info.nightscout.utils.SP; -import info.nightscout.utils.ToastUtils; /** * Created by mike on 20.02.2016. @@ -29,31 +24,31 @@ import info.nightscout.utils.ToastUtils; public class BroadcastTreatment { private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class); - public static void handleNewTreatment(NSTreatment treatment, Context context, boolean isDelta) { + public static void handleNewTreatment(JSONObject treatment, boolean isDelta) { Bundle bundle = new Bundle(); - bundle.putString("treatment", treatment.getData().toString()); + bundle.putString("treatment", treatment.toString()); bundle.putBoolean("delta", isDelta); Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { + if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { bundle = new Bundle(); - bundle.putString("treatment", treatment.getData().toString()); + bundle.putString("treatment", treatment.toString()); bundle.putBoolean("delta", isDelta); intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); + MainApp.instance().getApplicationContext().sendBroadcast(intent); } } - public static void handleNewTreatment(JSONArray treatments, Context context, boolean isDelta) { + public static void handleNewTreatment(JSONArray treatments, boolean isDelta) { List splitted = splitArray(treatments); - for (JSONArray part: splitted) { + for (JSONArray part : splitted) { Bundle bundle = new Bundle(); bundle.putString("treatments", part.toString()); bundle.putBoolean("delta", isDelta); @@ -63,21 +58,21 @@ public class BroadcastTreatment { LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); } - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)){ + if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { splitted = splitArray(treatments); - for (JSONArray part: splitted) { + for (JSONArray part : splitted) { Bundle bundle = new Bundle(); bundle.putString("treatments", part.toString()); bundle.putBoolean("delta", isDelta); Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); + MainApp.instance().getApplicationContext().sendBroadcast(intent); } } } - public void handleChangedTreatment(JSONObject treatment, Context context, boolean isDelta) { + public void handleChangedTreatment(JSONObject treatment, boolean isDelta) { Bundle bundle = new Bundle(); bundle.putString("treatment", treatment.toString()); @@ -88,18 +83,18 @@ public class BroadcastTreatment { LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { + if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { bundle = new Bundle(); bundle.putString("treatment", treatment.toString()); bundle.putBoolean("delta", isDelta); intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); + MainApp.instance().getApplicationContext().sendBroadcast(intent); } } - public static void handleChangedTreatment(JSONArray treatments, Context context, boolean isDelta) { + public static void handleChangedTreatment(JSONArray treatments, boolean isDelta) { List splitted = splitArray(treatments); for (JSONArray part : splitted) { @@ -112,7 +107,7 @@ public class BroadcastTreatment { LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); } - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { + if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { splitted = splitArray(treatments); for (JSONArray part : splitted) { Bundle bundle = new Bundle(); @@ -121,12 +116,12 @@ public class BroadcastTreatment { Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); + MainApp.instance().getApplicationContext().sendBroadcast(intent); } } } - public static void handleRemovedTreatment(JSONObject treatment, Context context, boolean isDelta) { + public static void handleRemovedTreatment(JSONObject treatment, boolean isDelta) { Bundle bundle = new Bundle(); bundle.putString("treatment", treatment.toString()); @@ -137,18 +132,18 @@ public class BroadcastTreatment { LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { + if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { bundle = new Bundle(); bundle.putString("treatment", treatment.toString()); bundle.putBoolean("delta", isDelta); intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); + MainApp.instance().getApplicationContext().sendBroadcast(intent); } } - public static void handleRemovedTreatment(JSONArray treatments, Context context, boolean isDelta) { + public static void handleRemovedTreatment(JSONArray treatments, boolean isDelta) { Bundle bundle = new Bundle(); bundle.putString("treatments", treatments.toString()); @@ -159,14 +154,14 @@ public class BroadcastTreatment { LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { + if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { bundle = new Bundle(); bundle.putString("treatments", treatments.toString()); bundle.putBoolean("delta", isDelta); intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); + MainApp.instance().getApplicationContext().sendBroadcast(intent); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java index a9f3509213..a20a634394 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java @@ -11,16 +11,14 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Date; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientInternalPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; -import info.nightscout.androidaps.db.DbRequest; -import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck; -import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; +import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; +import info.nightscout.utils.DateUtil; import info.nightscout.utils.SP; public class DBAccessReceiver extends BroadcastReceiver { @@ -90,6 +88,8 @@ public class DBAccessReceiver extends BroadcastReceiver { } else { DbRequest dbr = new DbRequest(action, collection, nsclientid.toString(), data); UploadQueue.add(dbr); + if (collection.equals("treatments")) + genereateTreatmentOfflineBroadcast(dbr); } } finally { @@ -98,6 +98,19 @@ public class DBAccessReceiver extends BroadcastReceiver { } + public void genereateTreatmentOfflineBroadcast(DbRequest request) { + if (request.action.equals("dbAdd")) { + try { + JSONObject data = new JSONObject(request.data); + data.put("mills", DateUtil.fromISODateString(data.getString("created_at")).getTime()); + data.put("_id", data.get("NSCLIENT_ID")); // this is only fake id + BroadcastTreatment.handleNewTreatment(data, false); + } catch (Exception e) { + log.error("Unhadled exception", e); + } + } + } + private boolean isAllowedCollection(String collection) { // "treatments" || "entries" || "devicestatus" || "profile" || "food" if (collection.equals("treatments")) return true; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java index 3aa8acb17e..abd0f2b26b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java @@ -52,15 +52,15 @@ import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastS import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastUrgentAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.utils.DateUtil; import info.nightscout.utils.SP; import io.socket.client.IO; @@ -310,17 +310,17 @@ public class NSClientService extends Service { }; private Emitter.Listener onAnnouncement = new Emitter.Listener() { -/* -{ -"level":0, -"title":"Announcement", -"message":"test", -"plugin":{"name":"treatmentnotify","label":"Treatment Notifications","pluginType":"notification","enabled":true}, -"group":"Announcement", -"isAnnouncement":true, -"key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da" -} - */ + /* + { + "level":0, + "title":"Announcement", + "message":"test", + "plugin":{"name":"treatmentnotify","label":"Treatment Notifications","pluginType":"notification","enabled":true}, + "group":"Announcement", + "isAnnouncement":true, + "key":"9ac46ad9a1dcda79dd87dae418fce0e7955c68da" + } + */ @Override public void call(final Object... args) { JSONObject data; @@ -342,19 +342,19 @@ public class NSClientService extends Service { }; private Emitter.Listener onAlarm = new Emitter.Listener() { -/* -{ -"level":1, -"title":"Warning HIGH", -"message":"BG Now: 5 -0.2 → mmol\/L\nRaw BG: 4.8 mmol\/L Čistý\nBG 15m: 4.8 mmol\/L\nIOB: -0.02U\nCOB: 0g", -"eventName":"high", -"plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, -"pushoverSound":"climb", -"debug":{"lastSGV":5,"thresholds":{"bgHigh":180,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, -"group":"default", -"key":"simplealarms_1" -} - */ + /* + { + "level":1, + "title":"Warning HIGH", + "message":"BG Now: 5 -0.2 → mmol\/L\nRaw BG: 4.8 mmol\/L Čistý\nBG 15m: 4.8 mmol\/L\nIOB: -0.02U\nCOB: 0g", + "eventName":"high", + "plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, + "pushoverSound":"climb", + "debug":{"lastSGV":5,"thresholds":{"bgHigh":180,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, + "group":"default", + "key":"simplealarms_1" + } + */ @Override public void call(final Object... args) { if (Config.detailedLog) @@ -372,19 +372,19 @@ public class NSClientService extends Service { }; private Emitter.Listener onUrgentAlarm = new Emitter.Listener() { -/* -{ -"level":2, -"title":"Urgent HIGH", -"message":"BG Now: 5.2 -0.1 → mmol\/L\nRaw BG: 5 mmol\/L Čistý\nBG 15m: 5 mmol\/L\nIOB: 0.00U\nCOB: 0g", -"eventName":"high", -"plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, -"pushoverSound":"persistent", -"debug":{"lastSGV":5.2,"thresholds":{"bgHigh":80,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, -"group":"default", -"key":"simplealarms_2" -} - */ + /* + { + "level":2, + "title":"Urgent HIGH", + "message":"BG Now: 5.2 -0.1 → mmol\/L\nRaw BG: 5 mmol\/L Čistý\nBG 15m: 5 mmol\/L\nIOB: 0.00U\nCOB: 0g", + "eventName":"high", + "plugin":{"name":"simplealarms","label":"Simple Alarms","pluginType":"notification","enabled":true}, + "pushoverSound":"persistent", + "debug":{"lastSGV":5.2,"thresholds":{"bgHigh":80,"bgTargetTop":75,"bgTargetBottom":72,"bgLow":70}}, + "group":"default", + "key":"simplealarms_2" + } + */ @Override public void call(final Object... args) { JSONObject data; @@ -402,14 +402,14 @@ public class NSClientService extends Service { }; private Emitter.Listener onClearAlarm = new Emitter.Listener() { -/* -{ -"clear":true, -"title":"All Clear", -"message":"default - Urgent was ack'd", -"group":"default" -} - */ + /* + { + "clear":true, + "title":"All Clear", + "message":"default - Urgent was ack'd", + "group":"default" + } + */ @Override public void call(final Object... args) { JSONObject data; @@ -520,17 +520,17 @@ public class NSClientService extends Service { updatedTreatments.put(jsonTreatment); } else if (treatment.getAction().equals("remove")) { if (treatment.getMills() != null && treatment.getMills() > System.currentTimeMillis() - 24 * 60 * 60 * 1000L) // handle 1 day old deletions only - removedTreatments.put(jsonTreatment); + removedTreatments.put(jsonTreatment); } } if (removedTreatments.length() > 0) { - BroadcastTreatment.handleRemovedTreatment(removedTreatments, MainApp.instance().getApplicationContext(), isDelta); + BroadcastTreatment.handleRemovedTreatment(removedTreatments, isDelta); } if (updatedTreatments.length() > 0) { - BroadcastTreatment.handleChangedTreatment(updatedTreatments, MainApp.instance().getApplicationContext(), isDelta); + BroadcastTreatment.handleChangedTreatment(updatedTreatments, isDelta); } if (addedTreatments.length() > 0) { - BroadcastTreatment.handleNewTreatment(addedTreatments, MainApp.instance().getApplicationContext(), isDelta); + BroadcastTreatment.handleNewTreatment(addedTreatments, isDelta); } } if (data.has("devicestatus")) { @@ -634,12 +634,12 @@ public class NSClientService extends Service { } // Was that sgv more less 15 mins ago ? boolean lessThan15MinAgo = false; - if((System.currentTimeMillis()-latestDateInReceivedData)/(60 * 1000L) < 15L ) + if ((System.currentTimeMillis() - latestDateInReceivedData) / (60 * 1000L) < 15L) lessThan15MinAgo = true; - if(Notification.isAlarmForStaleData() && lessThan15MinAgo){ + if (Notification.isAlarmForStaleData() && lessThan15MinAgo) { MainApp.bus().post(new EventDismissNotification(Notification.NSALARM)); - } - BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta); + } + BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta); } MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); } catch (JSONException e) { @@ -757,7 +757,7 @@ public class NSClientService extends Service { public void run() { if (mSocket == null || !mSocket.connected()) return; - if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { + if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } From f6721f628cadb51bc7ce50a605daa4c71c90ae82 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Tue, 12 Dec 2017 22:30:42 +0100 Subject: [PATCH 04/39] Apply bolus constraint before applying. --- .../info/nightscout/androidaps/queue/CommandQueue.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index eea2635ae7..af768e4888 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -153,6 +153,10 @@ public class CommandQueue { // remove all unfinished boluses removeAll(Command.CommandType.BOLUS); + // apply constraints + detailedBolusInfo.insulin = MainApp.getConfigBuilder().applyBolusConstraints(detailedBolusInfo.insulin); + detailedBolusInfo.carbs = MainApp.getConfigBuilder().applyCarbsConstraints((int) detailedBolusInfo.carbs); + // add new command to queue add(new CommandBolus(detailedBolusInfo, callback)); @@ -162,12 +166,8 @@ public class CommandQueue { MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin)); // Bring up bolus progress dialog - detailedBolusInfo.insulin = MainApp.getConfigBuilder().applyBolusConstraints(detailedBolusInfo.insulin); - detailedBolusInfo.carbs = MainApp.getConfigBuilder().applyCarbsConstraints((int) detailedBolusInfo.carbs); - - BolusProgressDialog bolusProgressDialog = null; if (detailedBolusInfo.context != null) { - bolusProgressDialog = new BolusProgressDialog(); + BolusProgressDialog bolusProgressDialog = new BolusProgressDialog(); bolusProgressDialog.setInsulin(detailedBolusInfo.insulin); bolusProgressDialog.show(((AppCompatActivity) detailedBolusInfo.context).getSupportFragmentManager(), "BolusProgress"); } else { From fa4e80444d73cac320b12e78d20c36dbbbc48aa9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 13 Dec 2017 20:03:24 +0100 Subject: [PATCH 05/39] NSOffline remove from queue as well --- .../androidaps/plugins/NSClientInternal/UploadQueue.java | 2 ++ .../NSClientInternal/receivers/DBAccessReceiver.java | 3 +++ .../Treatments/fragments/TreatmentsBolusFragment.java | 7 +++++-- .../fragments/TreatmentsExtendedBolusesFragment.java | 7 +++++-- .../fragments/TreatmentsProfileSwitchFragment.java | 7 +++++-- .../Treatments/fragments/TreatmentsTempTargetFragment.java | 7 +++++-- .../fragments/TreatmentsTemporaryBasalsFragment.java | 7 +++++-- app/src/main/java/info/nightscout/utils/NSUpload.java | 7 +++++++ 8 files changed, 37 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java index 114ace4c30..889128abdc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java @@ -96,6 +96,8 @@ public class UploadQueue { } public static void removeID(final String action, final String _id) { + if (_id == null || _id.equals("")) + return; startService(); if (NSClientService.handler != null) { NSClientService.handler.post(new Runnable() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java index a20a634394..3411659d0d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java @@ -87,6 +87,9 @@ public class DBAccessReceiver extends BroadcastReceiver { UploadQueue.add(dbr); } else { DbRequest dbr = new DbRequest(action, collection, nsclientid.toString(), data); + // this is not used as mongo _id but only for searching in UploadQueue database + // if record has to be removed from queue before upload + dbr._id = nsclientid.toString(); UploadQueue.add(dbr); if (collection.equals("treatments")) genereateTreatmentOfflineBroadcast(dbr); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java index efe3f200aa..d096fd8549 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java @@ -36,6 +36,7 @@ import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; @@ -82,7 +83,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. holder.activity.setText(DecimalFormatter.to3Decimal(iob.activityContrib) + " U"); holder.mealOrCorrection.setText(t.mealBolus ? MainApp.sResources.getString(R.string.mealbolus) : MainApp.sResources.getString(R.string.correctionbous)); holder.ph.setVisibility(t.source == Source.PUMP ? View.VISIBLE : View.GONE); - holder.ns.setVisibility(t._id != null ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(NSUpload.isIdValid(t._id) ? View.VISIBLE : View.GONE); holder.invalid.setVisibility(t.isValid ? View.GONE : View.VISIBLE); if (iob.iobContrib != 0) holder.iob.setTextColor(ContextCompat.getColor(MainApp.instance(), R.color.colorActive)); @@ -146,8 +147,10 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. treatment.isValid = false; MainApp.getDbHelper().update(treatment); } else { - if (_id != null && !_id.equals("")) { + if (NSUpload.isIdValid(_id)) { NSUpload.removeCareportalEntryFromNS(_id); + } else { + UploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(treatment); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java index eb3bd49d89..4e21259dae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -31,6 +31,7 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.NSUpload; @@ -63,7 +64,7 @@ public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { public void onBindViewHolder(ExtendedBolusesViewHolder holder, int position) { ExtendedBolus extendedBolus = extendedBolusList.getReversed(position); holder.ph.setVisibility(extendedBolus.source == Source.PUMP ? View.VISIBLE : View.GONE); - holder.ns.setVisibility(extendedBolus._id != null ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(NSUpload.isIdValid(extendedBolus._id) ? View.VISIBLE : View.GONE); if (extendedBolus.isEndingEvent()) { holder.date.setText(DateUtil.dateAndTimeString(extendedBolus.date)); holder.duration.setText(MainApp.sResources.getString(R.string.cancel)); @@ -148,8 +149,10 @@ public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final String _id = extendedBolus._id; - if (_id != null && !_id.equals("")) { + if (NSUpload.isIdValid(_id)) { NSUpload.removeCareportalEntryFromNS(_id); + } else { + UploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(extendedBolus); Answers.getInstance().logCustom(new CustomEvent("RemoveExtendedBolus")); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java index e5655cdb18..591a8a6964 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -29,6 +29,7 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.NSUpload; @@ -66,7 +67,7 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen if (profile == null) return; ProfileSwitch profileSwitch = profileSwitchList.getReversed(position); holder.ph.setVisibility(profileSwitch.source == Source.PUMP ? View.VISIBLE : View.GONE); - holder.ns.setVisibility(profileSwitch._id != null ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(NSUpload.isIdValid(profileSwitch._id) ? View.VISIBLE : View.GONE); holder.date.setText(DateUtil.dateAndTimeString(profileSwitch.date)); if (!profileSwitch.isEndingEvent()) { @@ -131,8 +132,10 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final String _id = profileSwitch._id; - if (_id != null && !_id.equals("")) { + if (NSUpload.isIdValid(_id)) { NSUpload.removeCareportalEntryFromNS(_id); + } else { + UploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(profileSwitch); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java index 9e3836e118..61b6c05199 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java @@ -27,6 +27,7 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.NSUpload; @@ -67,7 +68,7 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements String units = MainApp.getConfigBuilder().getProfileUnits(); TempTarget tempTarget = tempTargetList.getReversed(position); holder.ph.setVisibility(tempTarget.source == Source.PUMP ? View.VISIBLE : View.GONE); - holder.ns.setVisibility(tempTarget._id != null ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(NSUpload.isIdValid(tempTarget._id) ? View.VISIBLE : View.GONE); if (!tempTarget.isEndingEvent()) { holder.date.setText(DateUtil.dateAndTimeString(tempTarget.date) + " - " + DateUtil.timeString(tempTarget.originalEnd())); holder.duration.setText(DecimalFormatter.to0Decimal(tempTarget.durationInMinutes) + " min"); @@ -149,8 +150,10 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final String _id = tempTarget._id; - if (_id != null && !_id.equals("")) { + if (NSUpload.isIdValid(_id)) { NSUpload.removeCareportalEntryFromNS(_id); + } else { + UploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(tempTarget); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 9127bf1e7a..bd6269e871 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -31,6 +31,7 @@ import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.NSUpload; @@ -65,7 +66,7 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { public void onBindViewHolder(TempBasalsViewHolder holder, int position) { TemporaryBasal tempBasal = tempBasalList.getReversed(position); holder.ph.setVisibility(tempBasal.source == Source.PUMP ? View.VISIBLE : View.GONE); - holder.ns.setVisibility(tempBasal._id != null ? View.VISIBLE : View.GONE); + holder.ns.setVisibility(NSUpload.isIdValid(tempBasal._id) ? View.VISIBLE : View.GONE); if (tempBasal.isEndingEvent()) { holder.date.setText(DateUtil.dateAndTimeString(tempBasal.date)); holder.duration.setText(MainApp.sResources.getString(R.string.cancel)); @@ -165,8 +166,10 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final String _id = tempBasal._id; - if (_id != null && !_id.equals("")) { + if (NSUpload.isIdValid(_id)) { NSUpload.removeCareportalEntryFromNS(_id); + } else { + UploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(tempBasal); Answers.getInstance().logCustom(new CustomEvent("RemoveTempBasal")); diff --git a/app/src/main/java/info/nightscout/utils/NSUpload.java b/app/src/main/java/info/nightscout/utils/NSUpload.java index d6e8254cd6..cca4cea1a5 100644 --- a/app/src/main/java/info/nightscout/utils/NSUpload.java +++ b/app/src/main/java/info/nightscout/utils/NSUpload.java @@ -449,4 +449,11 @@ public class NSUpload { } + public static boolean isIdValid(String _id) { + if (_id == null) + return false; + if (_id.length() == 24) + return true; + return false; + } } From 8cb4921babe85156087d15de6728d0c27223ea56 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 15 Dec 2017 01:03:31 +0100 Subject: [PATCH 06/39] BG viewer --- .../androidaps/Services/DataService.java | 6 +- .../nightscout/androidaps/db/BgReading.java | 1 + .../androidaps/db/DatabaseHelper.java | 30 ++- .../plugins/NSClientInternal/data/NSSgv.java | 1 + .../SourceDexcomG5/BGSourceFragment.java | 172 ++++++++++++++++++ .../SourceDexcomG5/SourceDexcomG5Plugin.java | 9 +- .../SourceGlimp/SourceGlimpPlugin.java | 10 +- .../SourceMM640g/SourceMM640gPlugin.java | 10 +- .../SourceNSClient/SourceNSClientPlugin.java | 12 +- .../SourceXdrip/SourceXdripPlugin.java | 13 +- app/src/main/res/layout/bgsource_fragment.xml | 22 +++ app/src/main/res/layout/bgsource_item.xml | 78 ++++++++ app/src/main/res/values/strings.xml | 1 + 13 files changed, 337 insertions(+), 28 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/BGSourceFragment.java create mode 100644 app/src/main/res/layout/bgsource_fragment.xml create mode 100644 app/src/main/res/layout/bgsource_item.xml diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java index c8d8dbe808..aeb1a7acf9 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -117,10 +117,8 @@ public class DataService extends IntentService { handleNewDataFromDexcomG5(intent); } } else if (Intents.ACTION_NEW_SGV.equals(action)) { - // always handle SGV if NS-Client is the source - if (nsClientEnabled) { - handleNewDataFromNSClient(intent); - } + // always backfill SGV from NS + handleNewDataFromNSClient(intent); // Objectives 0 ObjectivesPlugin.bgIsAvailableInNS = true; ObjectivesPlugin.saveProgress(); diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java index 4d43f942e3..c8d5295811 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -53,6 +53,7 @@ public class BgReading implements DataPointWithLabelInterface { value = sgv.getMgdl(); raw = sgv.getFiltered() != null ? sgv.getFiltered() : value; direction = sgv.getDirection(); + _id = sgv.getId(); } public Double valueToUnits(String units) { diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 79c52b1a50..566df6995b 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -367,6 +367,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return false; } + public void update(BgReading bgReading) { + bgReading.date = roundDateToSec(bgReading.date); + try { + getDaoBgReadings().update(bgReading); + } catch (SQLException e) { + e.printStackTrace(); + } + } + private static void scheduleBgChange() { class PostRunnable implements Runnable { public void run() { @@ -397,7 +406,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { QueryBuilder queryBuilder = daoBgReadings.queryBuilder(); queryBuilder.orderBy("date", false); queryBuilder.limit(1L); - queryBuilder.where().gt("value", 38); + queryBuilder.where().gt("value", 38).and().eq("isValid", true); PreparedQuery preparedQuery = queryBuilder.prepare(); bgList = daoBgReadings.query(preparedQuery); @@ -435,7 +444,24 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { QueryBuilder queryBuilder = daoBgreadings.queryBuilder(); queryBuilder.orderBy("date", ascending); Where where = queryBuilder.where(); - where.ge("date", mills).and().gt("value", 38); + where.ge("date", mills).and().gt("value", 38).and().eq("isValid", true); + PreparedQuery preparedQuery = queryBuilder.prepare(); + bgReadings = daoBgreadings.query(preparedQuery); + return bgReadings; + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + return new ArrayList(); + } + + public List getAllBgreadingsDataFromTime(long mills, boolean ascending) { + try { + Dao daoBgreadings = getDaoBgReadings(); + List bgReadings; + QueryBuilder queryBuilder = daoBgreadings.queryBuilder(); + queryBuilder.orderBy("date", ascending); + Where where = queryBuilder.where(); + where.ge("date", mills); PreparedQuery preparedQuery = queryBuilder.prepare(); bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java index af134ea50d..50336a5f52 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java @@ -63,5 +63,6 @@ public class NSSgv { public Long getMills () { return getLongOrNull("mills"); } public String getDevice () { return getStringOrNull("device"); } public String getDirection () { return getStringOrNull("direction"); } + public String getId () { return getStringOrNull("_id"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/BGSourceFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/BGSourceFragment.java new file mode 100644 index 0000000000..bd686ec96c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/BGSourceFragment.java @@ -0,0 +1,172 @@ +package info.nightscout.androidaps.plugins.SourceDexcomG5; + +import android.app.Activity; +import android.content.DialogInterface; +import android.graphics.Paint; +import android.os.Bundle; +import android.support.v7.app.AlertDialog; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import com.crashlytics.android.Crashlytics; +import com.squareup.otto.Subscribe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.db.BgReading; +import info.nightscout.androidaps.events.EventNewBG; +import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; +import info.nightscout.utils.DateUtil; +import info.nightscout.utils.NSUpload; + +/** + * Created by mike on 16.10.2017. + */ + +public class BGSourceFragment extends SubscriberFragment { + private static Logger log = LoggerFactory.getLogger(BGSourceFragment.class); + + RecyclerView recyclerView; + + Profile profile; + + final long MILLS_TO_THE_PAST = 12 * 60 * 60 * 1000L; + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + try { + View view = inflater.inflate(R.layout.bgsource_fragment, container, false); + + recyclerView = (RecyclerView) view.findViewById(R.id.bgsource_recyclerview); + recyclerView.setHasFixedSize(true); + LinearLayoutManager llm = new LinearLayoutManager(view.getContext()); + recyclerView.setLayoutManager(llm); + + long now = System.currentTimeMillis(); + RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)); + recyclerView.setAdapter(adapter); + + profile = ConfigBuilderPlugin.getActiveProfileInterface().getProfile().getDefaultProfile(); + + return view; + } catch (Exception e) { + Crashlytics.logException(e); + } + + return null; + } + + @Subscribe + @SuppressWarnings("unused") + public void onStatusEvent(final EventNewBG ev) { + updateGUI(); + } + + @Override + protected void updateGUI() { + Activity activity = getActivity(); + if (activity != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + long now = System.currentTimeMillis(); + recyclerView.swapAdapter(new BGSourceFragment.RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true); + } + }); + } + + public class RecyclerViewAdapter extends RecyclerView.Adapter { + + List bgReadings; + + RecyclerViewAdapter(List bgReadings) { + this.bgReadings = bgReadings; + } + + @Override + public BgReadingsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { + View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.bgsource_item, viewGroup, false); + return new BgReadingsViewHolder(v); + } + + @Override + public void onBindViewHolder(BgReadingsViewHolder holder, int position) { + BgReading bgReading = bgReadings.get(position); + holder.ns.setVisibility(NSUpload.isIdValid(bgReading._id) ? View.VISIBLE : View.GONE); + holder.invalid.setVisibility(!bgReading.isValid ? View.VISIBLE : View.GONE); + holder.date.setText(DateUtil.dateAndTimeString(bgReading.date)); + holder.value.setText(bgReading.valueToUnitsToString(profile.getUnits())); + holder.direction.setText(bgReading.directionToSymbol()); + holder.remove.setTag(bgReading); + } + + @Override + public int getItemCount() { + return bgReadings.size(); + } + + class BgReadingsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { + TextView date; + TextView value; + TextView direction; + TextView invalid; + TextView ns; + TextView remove; + + BgReadingsViewHolder(View itemView) { + super(itemView); + date = (TextView) itemView.findViewById(R.id.bgsource_date); + value = (TextView) itemView.findViewById(R.id.bgsource_value); + direction = (TextView) itemView.findViewById(R.id.bgsource_direction); + invalid = (TextView) itemView.findViewById(R.id.invalid_sign); + ns = (TextView) itemView.findViewById(R.id.ns_sign); + remove = (TextView) itemView.findViewById(R.id.bgsource_remove); + remove.setOnClickListener(this); + remove.setPaintFlags(remove.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + } + + @Override + public void onClick(View v) { + final BgReading bgReading = (BgReading) v.getTag(); + switch (v.getId()) { + + case R.id.bgsource_remove: + AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); + builder.setTitle(MainApp.sResources.getString(R.string.confirmation)); + builder.setMessage(MainApp.sResources.getString(R.string.removerecord) + "\n" + DateUtil.dateAndTimeString(bgReading.date) + "\n" + bgReading.valueToUnitsToString(profile.getUnits())); + builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + final String _id = bgReading._id; + if (NSUpload.isIdValid(_id)) { + NSUpload.removeFoodFromNS(_id); + } else { + UploadQueue.removeID("dbAdd", _id); + } + bgReading.isValid = false; + MainApp.getDbHelper().update(bgReading); + updateGUI(); + } + }); + builder.setNegativeButton(MainApp.sResources.getString(R.string.cancel), null); + builder.show(); + break; + + } + } + } + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/SourceDexcomG5Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/SourceDexcomG5Plugin.java index 56934d0081..04f5700dae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/SourceDexcomG5Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SourceDexcomG5/SourceDexcomG5Plugin.java @@ -12,6 +12,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; public class SourceDexcomG5Plugin implements PluginBase, BgSourceInterface { private boolean fragmentEnabled = false; + private boolean fragmentVisible = false; private static SourceDexcomG5Plugin plugin = null; @@ -23,7 +24,7 @@ public class SourceDexcomG5Plugin implements PluginBase, BgSourceInterface { @Override public String getFragmentClass() { - return null; + return BGSourceFragment.class.getName(); } @Override @@ -49,7 +50,7 @@ public class SourceDexcomG5Plugin implements PluginBase, BgSourceInterface { @Override public boolean isVisibleInTabs(int type) { - return false; + return Config.G5UPLOADER || type == BGSOURCE && fragmentVisible; } @Override @@ -59,7 +60,7 @@ public class SourceDexcomG5Plugin implements PluginBase, BgSourceInterface { @Override public boolean hasFragment() { - return false; + return true; } @Override @@ -74,7 +75,7 @@ public class SourceDexcomG5Plugin implements PluginBase, BgSourceInterface { @Override public void setFragmentVisible(int type, boolean fragmentVisible) { - + if (type == BGSOURCE) this.fragmentVisible = fragmentVisible; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SourceGlimp/SourceGlimpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SourceGlimp/SourceGlimpPlugin.java index 934635f03b..51fd755b07 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SourceGlimp/SourceGlimpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SourceGlimp/SourceGlimpPlugin.java @@ -4,12 +4,14 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.SourceDexcomG5.BGSourceFragment; /** * Created by mike on 05.08.2016. */ public class SourceGlimpPlugin implements PluginBase, BgSourceInterface { private boolean fragmentEnabled = false; + private boolean fragmentVisible = false; private static SourceGlimpPlugin plugin = null; @@ -21,7 +23,7 @@ public class SourceGlimpPlugin implements PluginBase, BgSourceInterface { @Override public String getFragmentClass() { - return null; + return BGSourceFragment.class.getName(); } @Override @@ -47,7 +49,7 @@ public class SourceGlimpPlugin implements PluginBase, BgSourceInterface { @Override public boolean isVisibleInTabs(int type) { - return false; + return type == BGSOURCE && fragmentVisible; } @Override @@ -57,7 +59,7 @@ public class SourceGlimpPlugin implements PluginBase, BgSourceInterface { @Override public boolean hasFragment() { - return false; + return true; } @Override @@ -72,7 +74,7 @@ public class SourceGlimpPlugin implements PluginBase, BgSourceInterface { @Override public void setFragmentVisible(int type, boolean fragmentVisible) { - + if (type == BGSOURCE) this.fragmentVisible = fragmentVisible; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SourceMM640g/SourceMM640gPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SourceMM640g/SourceMM640gPlugin.java index aba07ffe05..e530dd563b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SourceMM640g/SourceMM640gPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SourceMM640g/SourceMM640gPlugin.java @@ -4,12 +4,14 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.SourceDexcomG5.BGSourceFragment; /** * Created by mike on 05.08.2016. */ public class SourceMM640gPlugin implements PluginBase, BgSourceInterface { private boolean fragmentEnabled = false; + private boolean fragmentVisible = false; private static SourceMM640gPlugin plugin = null; @@ -21,7 +23,7 @@ public class SourceMM640gPlugin implements PluginBase, BgSourceInterface { @Override public String getFragmentClass() { - return null; + return BGSourceFragment.class.getName(); } @Override @@ -47,7 +49,7 @@ public class SourceMM640gPlugin implements PluginBase, BgSourceInterface { @Override public boolean isVisibleInTabs(int type) { - return false; + return type == BGSOURCE && fragmentVisible; } @Override @@ -57,7 +59,7 @@ public class SourceMM640gPlugin implements PluginBase, BgSourceInterface { @Override public boolean hasFragment() { - return false; + return true; } @Override @@ -72,7 +74,7 @@ public class SourceMM640gPlugin implements PluginBase, BgSourceInterface { @Override public void setFragmentVisible(int type, boolean fragmentVisible) { - + if (type == BGSOURCE) this.fragmentVisible = fragmentVisible; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SourceNSClient/SourceNSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SourceNSClient/SourceNSClientPlugin.java index 0e85793850..1928448f0e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SourceNSClient/SourceNSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SourceNSClient/SourceNSClientPlugin.java @@ -5,12 +5,14 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.SourceDexcomG5.BGSourceFragment; /** * Created by mike on 05.08.2016. */ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface { private boolean fragmentEnabled = true; + private boolean fragmentVisible = false; private static SourceNSClientPlugin plugin = null; @@ -22,7 +24,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface { @Override public String getFragmentClass() { - return null; + return BGSourceFragment.class.getName(); } @Override @@ -32,7 +34,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface { @Override public String getName() { - return MainApp.instance().getString(R.string.nsclient); + return MainApp.instance().getString(R.string.nsclientbg); } @Override @@ -49,7 +51,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface { @Override public boolean isVisibleInTabs(int type) { - return false; + return type == BGSOURCE && fragmentVisible; } @Override @@ -59,7 +61,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface { @Override public boolean hasFragment() { - return false; + return true; } @Override @@ -74,7 +76,7 @@ public class SourceNSClientPlugin implements PluginBase, BgSourceInterface { @Override public void setFragmentVisible(int type, boolean fragmentVisible) { - + if (type == BGSOURCE) this.fragmentVisible = fragmentVisible; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SourceXdrip/SourceXdripPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SourceXdrip/SourceXdripPlugin.java index 8363f13566..7f73d457e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SourceXdrip/SourceXdripPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SourceXdrip/SourceXdripPlugin.java @@ -4,12 +4,16 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.plugins.SourceDexcomG5.BGSourceFragment; /** * Created by mike on 05.08.2016. */ public class SourceXdripPlugin implements PluginBase, BgSourceInterface { + private boolean fragmentEnabled = false; + private boolean fragmentVisible = false; + private static SourceXdripPlugin plugin = null; public static SourceXdripPlugin getPlugin() { @@ -20,11 +24,9 @@ public class SourceXdripPlugin implements PluginBase, BgSourceInterface { @Override public String getFragmentClass() { - return null; + return BGSourceFragment.class.getName(); } - private boolean fragmentEnabled = false; - @Override public int getType() { return PluginBase.BGSOURCE; @@ -48,7 +50,7 @@ public class SourceXdripPlugin implements PluginBase, BgSourceInterface { @Override public boolean isVisibleInTabs(int type) { - return false; + return type == BGSOURCE && fragmentVisible; } @Override @@ -58,7 +60,7 @@ public class SourceXdripPlugin implements PluginBase, BgSourceInterface { @Override public boolean hasFragment() { - return false; + return true; } @Override @@ -73,6 +75,7 @@ public class SourceXdripPlugin implements PluginBase, BgSourceInterface { @Override public void setFragmentVisible(int type, boolean fragmentVisible) { + if (type == BGSOURCE) this.fragmentVisible = fragmentVisible; } @Override diff --git a/app/src/main/res/layout/bgsource_fragment.xml b/app/src/main/res/layout/bgsource_fragment.xml new file mode 100644 index 0000000000..dbd0ea4e67 --- /dev/null +++ b/app/src/main/res/layout/bgsource_fragment.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + diff --git a/app/src/main/res/layout/bgsource_item.xml b/app/src/main/res/layout/bgsource_item.xml new file mode 100644 index 0000000000..acd0454327 --- /dev/null +++ b/app/src/main/res/layout/bgsource_item.xml @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 7286003410..7306a49355 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -788,5 +788,6 @@ Send BG data to xDrip+ dexcomg5_xdripupload In xDrip+ select 640g/Eversense data source + NSClient BG From 9bd0a1f1447d41ff841d8ba7209d13befc5da51e Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sun, 17 Dec 2017 01:37:27 +0100 Subject: [PATCH 07/39] push next alert on read status --- .../info/nightscout/androidaps/MainApp.java | 3 +- .../queue/commands/CommandReadStatus.java | 3 +- .../receivers/KeepAliveReceiver.java | 80 +------------- .../nightscout/utils/LocalAlertUtils.java | 103 ++++++++++++++++++ 4 files changed, 113 insertions(+), 76 deletions(-) create mode 100644 app/src/main/java/info/nightscout/utils/LocalAlertUtils.java diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 7eac441726..603c74da4d 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -69,6 +69,7 @@ import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver; +import info.nightscout.utils.LocalAlertUtils; import info.nightscout.utils.NSUpload; import io.fabric.sdk.android.Fabric; @@ -213,7 +214,7 @@ public class MainApp extends Application { public void stopKeepAliveService() { if (keepAliveReceiver != null) - keepAliveReceiver.cancelAlarm(this); + LocalAlertUtils.cancelAlarm(this); } public static Bus bus() { diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java index d573cc44be..46c524fa29 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java @@ -1,8 +1,8 @@ package info.nightscout.androidaps.queue.commands; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; +import info.nightscout.utils.LocalAlertUtils; /** * Created by mike on 09.11.2017. @@ -20,6 +20,7 @@ public class CommandReadStatus extends Command { @Override public void execute() { ConfigBuilderPlugin.getActivePump().getPumpStatus(); + LocalAlertUtils.notifyPumpStatusRead(); if (callback != null) callback.result(null).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index 38ca9ee2a1..fc411372a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -16,61 +16,31 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; -import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.utils.SP; +import info.nightscout.utils.LocalAlertUtils; public class KeepAliveReceiver extends BroadcastReceiver { private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class); public static final long STATUS_UPDATE_FREQUENCY = 15 * 60 * 1000L; - // TODO consider moving this into an Alarms plugin that works offline and can be configured - // (e.g. override silent mode at night only) - - private static int missedReadingsThreshold() { - return SP.getInt(MainApp.sResources.getString(R.string.key_missed_bg_readings_threshold), 30) * 60 * 1000; - } - - private static int pumpUnreachableThreshold() { - return SP.getInt(MainApp.sResources.getString(R.string.key_pump_unreachable_threshold), 30) * 60 * 1000; - } - - @Override public void onReceive(Context context, Intent rIntent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""); wl.acquire(); - shortenSnoozeInterval(); - checkBg(); + LocalAlertUtils.shortenSnoozeInterval(); + LocalAlertUtils.checkStaleBGAlert(); checkPump(); log.debug("KeepAlive received"); wl.release(); } - private void checkBg() { - BgReading bgReading = DatabaseHelper.lastBg(); - if (SP.getBoolean(MainApp.sResources.getString(R.string.key_enable_missed_bg_readings_alert), false) - && bgReading != null && bgReading.date + missedReadingsThreshold() < System.currentTimeMillis() - && SP.getLong("nextMissedReadingsAlarm", 0l) < System.currentTimeMillis()) { - Notification n = new Notification(Notification.BG_READINGS_MISSED, MainApp.sResources.getString(R.string.missed_bg_readings), Notification.URGENT); - n.soundId = R.raw.alarm; - SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()); - MainApp.bus().post(new EventNewNotification(n)); - } - } - private void checkPump() { final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); final Profile profile = MainApp.getConfigBuilder().getProfile(); @@ -79,16 +49,7 @@ public class KeepAliveReceiver extends BroadcastReceiver { boolean isStatusOutdated = lastConnection.getTime() + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis(); boolean isBasalOutdated = Math.abs(profile.getBasal() - pump.getBaseBasalRate()) > pump.getPumpDescription().basalStep; - boolean alarmTimeoutExpired = lastConnection.getTime() + pumpUnreachableThreshold() < System.currentTimeMillis(); - boolean nextAlarmOccurrenceReached = SP.getLong("nextPumpDisconnectedAlarm", 0l) < System.currentTimeMillis(); - - if (Config.APS && SP.getBoolean(MainApp.sResources.getString(R.string.key_enable_pump_unreachable_alert), true) - && isStatusOutdated && alarmTimeoutExpired && nextAlarmOccurrenceReached && !ConfigBuilderPlugin.getActiveLoop().isDisconnected()) { - Notification n = new Notification(Notification.PUMP_UNREACHABLE, MainApp.sResources.getString(R.string.pump_unreachable), Notification.URGENT); - n.soundId = R.raw.alarm; - SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()); - MainApp.bus().post(new EventNewNotification(n)); - } + LocalAlertUtils.checkPumpUnreachableAlarm(lastConnection, isStatusOutdated); if (SP.getBoolean("syncprofiletopump", false) && !pump.isThisProfileSet(profile)) { MainApp.getConfigBuilder().getCommandQueue().setProfile(profile, null); @@ -103,8 +64,8 @@ public class KeepAliveReceiver extends BroadcastReceiver { //called by MainApp at first app start public void setAlarm(Context context) { - shortenSnoozeInterval(); - presnoozeAlarms(); + LocalAlertUtils.shortenSnoozeInterval(); + LocalAlertUtils.presnoozeAlarms(); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, KeepAliveReceiver.class); @@ -117,33 +78,4 @@ public class KeepAliveReceiver extends BroadcastReceiver { am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Constants.keepAliveMsecs, pi); } - /*Presnoozes the alarms with 5 minutes if no snooze exists. - * Call only at startup! - */ - public void presnoozeAlarms() { - if (SP.getLong("nextMissedReadingsAlarm", 0l) < System.currentTimeMillis()) { - SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + 5 * 60 * 1000); - } - if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < System.currentTimeMillis()) { - SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + 5 * 60 * 1000); - } - } - - public void cancelAlarm(Context context) { - Intent intent = new Intent(context, KeepAliveReceiver.class); - PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); - AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - alarmManager.cancel(sender); - } - - static void shortenSnoozeInterval() { - //shortens alarm times in case of setting changes or future data - long nextMissedReadingsAlarm = SP.getLong("nextMissedReadingsAlarm", 0L); - nextMissedReadingsAlarm = Math.min(System.currentTimeMillis() + missedReadingsThreshold(), nextMissedReadingsAlarm); - SP.putLong("nextMissedReadingsAlarm", nextMissedReadingsAlarm); - - long nextPumpDisconnectedAlarm = SP.getLong("nextPumpDisconnectedAlarm", 0L); - nextPumpDisconnectedAlarm = Math.min(System.currentTimeMillis() + pumpUnreachableThreshold(), nextPumpDisconnectedAlarm); - SP.putLong("nextPumpDisconnectedAlarm", nextPumpDisconnectedAlarm); - } } diff --git a/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java b/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java new file mode 100644 index 0000000000..a872b1d9ec --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java @@ -0,0 +1,103 @@ +package info.nightscout.utils; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.Context; +import android.content.Intent; + +import java.util.Date; + +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.db.BgReading; +import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.receivers.KeepAliveReceiver; + +/** + * Created by adrian on 17/12/17. + */ + +public class LocalAlertUtils { + public static int missedReadingsThreshold() { + return SP.getInt(MainApp.sResources.getString(R.string.key_missed_bg_readings_threshold), 30) * 60 * 1000; + } + + private static int pumpUnreachableThreshold() { + return SP.getInt(MainApp.sResources.getString(R.string.key_pump_unreachable_threshold), 30) * 60 * 1000; + } + + public static void checkPumpUnreachableAlarm(Date lastConnection, boolean isStatusOutdated) { + boolean alarmTimeoutExpired = lastConnection.getTime() + pumpUnreachableThreshold() < System.currentTimeMillis(); + boolean nextAlarmOccurrenceReached = SP.getLong("nextPumpDisconnectedAlarm", 0l) < System.currentTimeMillis(); + + if (Config.APS && SP.getBoolean(MainApp.sResources.getString(R.string.key_enable_pump_unreachable_alert), true) + && isStatusOutdated && alarmTimeoutExpired && nextAlarmOccurrenceReached && !ConfigBuilderPlugin.getActiveLoop().isDisconnected()) { + Notification n = new Notification(Notification.PUMP_UNREACHABLE, MainApp.sResources.getString(R.string.pump_unreachable), Notification.URGENT); + n.soundId = R.raw.alarm; + SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()); + MainApp.bus().post(new EventNewNotification(n)); + } + } + + /*Presnoozes the alarms with 5 minutes if no snooze exists. + * Call only at startup! + */ + public static void presnoozeAlarms() { + if (SP.getLong("nextMissedReadingsAlarm", 0l) < System.currentTimeMillis()) { + SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + 5 * 60 * 1000); + } + if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < System.currentTimeMillis()) { + SP.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + 5 * 60 * 1000); + } + } + + public static void cancelAlarm(Context context) { + Intent intent = new Intent(context, KeepAliveReceiver.class); + PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); + AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + alarmManager.cancel(sender); + } + + public static void shortenSnoozeInterval() { + //shortens alarm times in case of setting changes or future data + long nextMissedReadingsAlarm = SP.getLong("nextMissedReadingsAlarm", 0L); + nextMissedReadingsAlarm = Math.min(System.currentTimeMillis() + missedReadingsThreshold(), nextMissedReadingsAlarm); + SP.putLong("nextMissedReadingsAlarm", nextMissedReadingsAlarm); + + long nextPumpDisconnectedAlarm = SP.getLong("nextPumpDisconnectedAlarm", 0L); + nextPumpDisconnectedAlarm = Math.min(System.currentTimeMillis() + pumpUnreachableThreshold(), nextPumpDisconnectedAlarm); + SP.putLong("nextPumpDisconnectedAlarm", nextPumpDisconnectedAlarm); + } + + public static void notifyPumpStatusRead(){ + //TODO: persist the actual time the pump is read and simplify the whole logic when to alarm + + final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); + final Profile profile = MainApp.getConfigBuilder().getProfile(); + if (pump != null && profile != null && profile.getBasal() != null) { + Date lastConnection = pump.lastDataTime(); + long earliestAlarmTime = lastConnection.getTime() + pumpUnreachableThreshold(); + if (SP.getLong("nextPumpDisconnectedAlarm", 0l) < earliestAlarmTime) { + SP.putLong("nextPumpDisconnectedAlarm", earliestAlarmTime); + } + } + } + + public static void checkStaleBGAlert() { + BgReading bgReading = DatabaseHelper.lastBg(); + if (SP.getBoolean(MainApp.sResources.getString(R.string.key_enable_missed_bg_readings_alert), false) + && bgReading != null && bgReading.date + missedReadingsThreshold() < System.currentTimeMillis() + && SP.getLong("nextMissedReadingsAlarm", 0l) < System.currentTimeMillis()) { + Notification n = new Notification(Notification.BG_READINGS_MISSED, MainApp.sResources.getString(R.string.missed_bg_readings), Notification.URGENT); + n.soundId = R.raw.alarm; + SP.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()); + MainApp.bus().post(new EventNewNotification(n)); + } + } +} From 00f13d04793d2fa3b6086a6103db34324dec8d0f Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sun, 17 Dec 2017 01:40:27 +0100 Subject: [PATCH 08/39] refactor cancelAlarm back to KeepAliveReceiver --- app/src/main/java/info/nightscout/androidaps/MainApp.java | 3 +-- .../nightscout/androidaps/receivers/KeepAliveReceiver.java | 7 +++++++ .../main/java/info/nightscout/utils/LocalAlertUtils.java | 7 ------- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 603c74da4d..bd0ba7695e 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -69,7 +69,6 @@ import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver; -import info.nightscout.utils.LocalAlertUtils; import info.nightscout.utils.NSUpload; import io.fabric.sdk.android.Fabric; @@ -214,7 +213,7 @@ public class MainApp extends Application { public void stopKeepAliveService() { if (keepAliveReceiver != null) - LocalAlertUtils.cancelAlarm(this); + KeepAliveReceiver.cancelAlarm(this); } public static Bus bus() { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index fc411372a3..44d0da2c55 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -27,6 +27,13 @@ public class KeepAliveReceiver extends BroadcastReceiver { private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class); public static final long STATUS_UPDATE_FREQUENCY = 15 * 60 * 1000L; + public static void cancelAlarm(Context context) { + Intent intent = new Intent(context, KeepAliveReceiver.class); + PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); + AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); + alarmManager.cancel(sender); + } + @Override public void onReceive(Context context, Intent rIntent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); diff --git a/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java b/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java index a872b1d9ec..e74818d447 100644 --- a/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java +++ b/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java @@ -57,13 +57,6 @@ public class LocalAlertUtils { } } - public static void cancelAlarm(Context context) { - Intent intent = new Intent(context, KeepAliveReceiver.class); - PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); - AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); - alarmManager.cancel(sender); - } - public static void shortenSnoozeInterval() { //shortens alarm times in case of setting changes or future data long nextMissedReadingsAlarm = SP.getLong("nextMissedReadingsAlarm", 0L); From b180569695b6b71cc74500482757f45d71cb47b7 Mon Sep 17 00:00:00 2001 From: Andrew Warrington Date: Mon, 18 Dec 2017 21:58:02 +0100 Subject: [PATCH 09/39] Show watch basal rates, whether temporary or normal. --- .../wearintegration/WatchUpdaterService.java | 16 +++++++++------- .../androidaps/watchfaces/BaseWatchFace.java | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java index 944774baaa..d87ac2e69c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java @@ -533,7 +533,7 @@ public class WatchUpdaterService extends WearableListenerService implements String iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob); String iobDetail = "(" + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")"; String cobString = generateCOBString(); - String tempBasal = generateBasalString(treatmentsInterface); + String currentBasal = generateBasalString(treatmentsInterface); //bgi String bgiString = ""; @@ -543,7 +543,7 @@ public class WatchUpdaterService extends WearableListenerService implements bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to1Decimal(bgi); } - String status = generateStatusString(profile, tempBasal,iobSum, iobDetail, bgiString); + String status = generateStatusString(profile, currentBasal,iobSum, iobDetail, bgiString); //batteries int phoneBattery = getBatteryLevel(getApplicationContext()); @@ -567,7 +567,7 @@ public class WatchUpdaterService extends WearableListenerService implements dataMapRequest.getDataMap().putString("iobDetail", iobDetail); dataMapRequest.getDataMap().putBoolean("detailedIob", mPrefs.getBoolean("wear_detailediob", false)); dataMapRequest.getDataMap().putString("cob", cobString); - dataMapRequest.getDataMap().putString("tempBasal", tempBasal); + dataMapRequest.getDataMap().putString("currentBasal", currentBasal); dataMapRequest.getDataMap().putString("battery", "" + phoneBattery); dataMapRequest.getDataMap().putString("rigBattery", rigBattery); dataMapRequest.getDataMap().putLong("openApsStatus", openApsStatus); @@ -598,7 +598,7 @@ public class WatchUpdaterService extends WearableListenerService implements } @NonNull - private String generateStatusString(Profile profile, String tempBasal, String iobSum, String iobDetail, String bgiString) { + private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, String bgiString) { String status = ""; @@ -623,7 +623,7 @@ public class WatchUpdaterService extends WearableListenerService implements iobString = iobSum + "U"; } - status += tempBasal + " " + iobString; + status += currentBasal + " " + iobString; //add BGI if shown, otherwise return if (mPrefs.getBoolean("wear_showbgi", false)) { @@ -636,10 +636,12 @@ public class WatchUpdaterService extends WearableListenerService implements @NonNull private String generateBasalString(TreatmentsInterface treatmentsInterface) { - String basalStringResult = "-.--U/h"; + String basalStringResult; TemporaryBasal activeTemp = treatmentsInterface.getTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { - basalStringResult = activeTemp.toStringShort(); + basalStringResult = activeTemp.toStringVeryShort(); + } else { + basalStringResult = DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + "U/h"; } return basalStringResult; } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java index cb82daf3eb..c4b7c3c5f0 100644 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java @@ -257,7 +257,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen if (layoutSet && bundle != null) { DataMap dataMap = DataMap.fromBundle(bundle); wakeLock.acquire(50); - sBasalRate = dataMap.getString("tempBasal"); + sBasalRate = dataMap.getString("currentBasal"); sUploaderBattery = dataMap.getString("battery"); sRigBattery = dataMap.getString("rigBattery"); detailedIOB = dataMap.getBoolean("detailedIob"); From 88adc31dbcbcc0597c963cdc51683637272b9d8b Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Tue, 19 Dec 2017 07:16:41 +0100 Subject: [PATCH 10/39] Add SP to imports --- .../info/nightscout/androidaps/receivers/KeepAliveReceiver.java | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index 44d0da2c55..e8bc69281f 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.utils.LocalAlertUtils; +import info.nightscout.utils.SP; public class KeepAliveReceiver extends BroadcastReceiver { private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class); From 3342d9daa3b9bed877761e9638d173cbfefa502b Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Tue, 19 Dec 2017 14:47:55 +0100 Subject: [PATCH 11/39] don't show single connection timeouts on the watch --- .../info/nightscout/androidaps/plugins/Wear/WearPlugin.java | 2 ++ .../main/java/info/nightscout/androidaps/queue/QueueThread.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java index 00f62bd2c0..3316d68d12 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java @@ -215,6 +215,8 @@ public class WearPlugin implements PluginBase { @Subscribe public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) { + if(ev.result == null) return; + String status; if(ev.result.success){ status = MainApp.sResources.getString(R.string.success); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index 2c568cdccd..885d388db5 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -59,7 +59,7 @@ public class QueueThread extends Thread { } if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { - MainApp.bus().post(new EventDismissBolusprogressIfRunning(new PumpEnactResult())); + MainApp.bus().post(new EventDismissBolusprogressIfRunning(null)); MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.connectiontimedout))); log.debug("QUEUE: timed out"); pump.stopConnecting(); From e11a4f6d4222949c50c416867515d6f9b2e3f107 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Tue, 19 Dec 2017 22:41:43 +0100 Subject: [PATCH 12/39] Use autosensdata for wizard instead of APSResult --- .../plugins/Overview/Dialogs/WizardDialog.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index 464c422596..5e3e187d17 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -53,6 +53,8 @@ import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; +import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; @@ -439,7 +441,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com basalIobInsulin.setText(DecimalFormatter.to2Decimal(-basalIob.basaliob) + "U"); // COB only if AMA is selected - if (ConfigBuilderPlugin.getActiveAPS() instanceof OpenAPSAMAPlugin && ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(System.currentTimeMillis() - 11 * 60 * 1000L))) { + if (ConfigBuilderPlugin.getActiveAPS() instanceof OpenAPSAMAPlugin) { cobLayout.setVisibility(View.VISIBLE); cobAvailable = true; } else { @@ -483,12 +485,10 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com // COB Double c_cob = 0d; if (cobAvailable && cobCheckbox.isChecked()) { - if (ConfigBuilderPlugin.getActiveAPS().getLastAPSResult() != null && ConfigBuilderPlugin.getActiveAPS().getLastAPSRun().after(new Date(System.currentTimeMillis() - 11 * 60 * 1000L))) { - try { - c_cob = SafeParse.stringToDouble(ConfigBuilderPlugin.getActiveAPS().getLastAPSResult().json().getString("COB")); - } catch (JSONException e) { - log.error("Unhandled exception", e); - } + AutosensData autosensData = IobCobCalculatorPlugin.getAutosensData(System.currentTimeMillis()); + + if(autosensData != null && autosensData.time > System.currentTimeMillis() - 11 * 60 * 1000L) { + c_cob = autosensData.cob; } } From 81ca35515f265ec40a7add6ce472173198f714d9 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Wed, 20 Dec 2017 14:34:30 +0100 Subject: [PATCH 13/39] Old NS-Version non-urgent --- .../java/info/nightscout/androidaps/Services/DataService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java index c8d8dbe808..70bd8d71ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java @@ -301,7 +301,7 @@ public class DataService extends IntentService { log.error("Unhandled exception", e); } if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) { - Notification notification = new Notification(Notification.OLD_NS, MainApp.sResources.getString(R.string.unsupportednsversion), Notification.URGENT); + Notification notification = new Notification(Notification.OLD_NS, MainApp.sResources.getString(R.string.unsupportednsversion), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); } else { MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS)); From d1085c876e6f179ffb5c91b1c2cf51419c930841 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 16:15:55 +0100 Subject: [PATCH 14/39] Actions tab: show profile switch button for single profile too. --- .../nightscout/androidaps/plugins/Actions/ActionsFragment.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java index 18f092966e..910f032fc5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java @@ -127,8 +127,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL return; } final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); - boolean allowProfileSwitch = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile().getProfileList().size() > 1; - if (!pump.getPumpDescription().isSetBasalProfileCapable || !pump.isInitialized() || pump.isSuspended() || !allowProfileSwitch) + if (!pump.getPumpDescription().isSetBasalProfileCapable || !pump.isInitialized() || pump.isSuspended()) profileSwitch.setVisibility(View.GONE); else profileSwitch.setVisibility(View.VISIBLE); From 096b2e93a310c8c912c62e88f7e903711422cec9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 20 Dec 2017 18:26:47 +0100 Subject: [PATCH 15/39] wait a few sec before disconnection for another command --- .../androidaps/queue/QueueThread.java | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index 2c568cdccd..26597144b8 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -29,6 +29,7 @@ public class QueueThread extends Thread { CommandQueue queue; private long connectionStartTime = 0; + private long lastCommandTime = 0; private boolean connectLogged = false; private PowerManager.WakeLock mWakeLock; @@ -45,7 +46,7 @@ public class QueueThread extends Thread { public final void run() { mWakeLock.acquire(); MainApp.bus().post(new EventQueueChanged()); - connectionStartTime = System.currentTimeMillis(); + connectionStartTime = lastCommandTime = System.currentTimeMillis(); try { while (true) { @@ -107,17 +108,24 @@ public class QueueThread extends Thread { queue.performing().execute(); queue.resetPerforming(); MainApp.bus().post(new EventQueueChanged()); + lastCommandTime = System.currentTimeMillis(); SystemClock.sleep(100); continue; } } if (queue.size() == 0 && queue.performing() == null) { - log.debug("QUEUE: queue empty. disconnect"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); - pump.disconnect("Queue empty"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); - return; + long secondsFromLastCommand = (System.currentTimeMillis() - lastCommandTime) / 1000; + if (secondsFromLastCommand >= 5) { + log.debug("QUEUE: queue empty. disconnect"); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + pump.disconnect("Queue empty"); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + return; + } else { + log.debug("QUEUE: waiting for disconnect"); + SystemClock.sleep(1000); + } } } } finally { From c33dd1e7d71819d9726e8240b55e2494a6334ab3 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 20 Dec 2017 19:50:44 +0100 Subject: [PATCH 16/39] RS enable BT before scanning --- .../activities/BLEScanActivity.java | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java index 8e973903f9..2a113b3c8d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java @@ -7,8 +7,10 @@ import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.ScanCallback; import android.bluetooth.le.ScanResult; import android.content.Context; +import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; +import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; @@ -31,7 +33,6 @@ import info.nightscout.utils.SP; public class BLEScanActivity extends AppCompatActivity { private static Logger log = LoggerFactory.getLogger(BLEScanActivity.class); - private Context mContext = null; private ListView listView = null; private ListAdapter mListAdapter = null; @@ -53,26 +54,20 @@ public class BLEScanActivity extends AppCompatActivity { listView.setEmptyView(findViewById(R.id.danars_blescanner_nodevice)); listView.setAdapter(mListAdapter); - initView(); - } - - private void initView() { - mContext = getApplicationContext(); - - BluetoothManager bluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); - mBluetoothAdapter = bluetoothManager.getAdapter(); - mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); - - // MIKE: test mBluetoothLeScanner for null (bt disabled) - mListAdapter.notifyDataSetChanged(); - } @Override protected void onResume() { super.onResume(); + mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); + mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); + + if (mBluetoothLeScanner == null) { + mBluetoothAdapter.enable(); + mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); + } startScan(); } @@ -138,7 +133,7 @@ public class BLEScanActivity extends AppCompatActivity { ViewHolder holder; if (v == null) { - v = View.inflate(mContext, R.layout.danars_blescanner_item, null); + v = View.inflate(getApplicationContext(), R.layout.danars_blescanner_item, null); holder = new ViewHolder(v); v.setTag(holder); } else { From 63b0efede3d56545762b705a0e76638f5020d665 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 20 Dec 2017 20:45:21 +0100 Subject: [PATCH 17/39] allow to read status after every command --- .../nightscout/androidaps/queue/CommandQueue.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index af768e4888..b69c41e6c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -326,14 +326,14 @@ public class CommandQueue { // returns true if command is queued public boolean readStatus(String reason, Callback callback) { - if (isRunning(Command.CommandType.READSTATUS)) { - if (callback != null) - callback.result(executingNowError()).run(); - return false; - } + //if (isRunning(Command.CommandType.READSTATUS)) { + // if (callback != null) + // callback.result(executingNowError()).run(); + // return false; + //} // remove all unfinished - removeAll(Command.CommandType.READSTATUS); + //removeAll(Command.CommandType.READSTATUS); // add new command to queue add(new CommandReadStatus(reason, callback)); From adff0329dd4a47640ac3305bc92fb067a7cdc1b0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 20 Dec 2017 20:55:14 +0100 Subject: [PATCH 18/39] initialize lastCommandTime too after BT reset --- .../main/java/info/nightscout/androidaps/queue/QueueThread.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index 26597144b8..dd02c5e973 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -80,7 +80,7 @@ public class QueueThread extends Thread { mBluetoothAdapter.enable(); SystemClock.sleep(1000); //start over again once after watchdog barked - connectionStartTime = System.currentTimeMillis(); + connectionStartTime = lastCommandTime = System.currentTimeMillis(); } else { queue.clear(); return; From 2bdda9af430c5b848de80bb63746e16b0d4a6e4b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 21 Dec 2017 07:45:56 +0100 Subject: [PATCH 19/39] Rv2,RS fix loading events --- .../plugins/PumpDanaRS/services/DanaRSService.java | 5 ++++- .../PumpDanaRv2/services/DanaRv2ExecutionService.java | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java index a30e237672..bd6f5ca690 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java @@ -185,7 +185,10 @@ public class DanaRSService extends Service { while (!msg.done && bleComm.isConnected()) { SystemClock.sleep(100); } - lastHistoryFetched = DanaRS_Packet_APS_History_Events.lastEventTimeLoaded - 45 * 60 * 1000L; // always load last 45 min + if (DanaRS_Packet_APS_History_Events.lastEventTimeLoaded != 0) + lastHistoryFetched = DanaRS_Packet_APS_History_Events.lastEventTimeLoaded - 45 * 60 * 1000L; // always load last 45 min + else + lastHistoryFetched = 0; log.debug("Events loaded"); return new PumpEnactResult().success(true); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java index 4e5b85177a..6d6ba34838 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java @@ -527,7 +527,10 @@ public class DanaRv2ExecutionService extends Service { waitMsec(100); } waitMsec(200); - lastHistoryFetched = MsgHistoryEvents_v2.lastEventTimeLoaded - 45 * 60 * 1000L; //always load last 45 min; + if (MsgHistoryEvents_v2.lastEventTimeLoaded != 0) + lastHistoryFetched = MsgHistoryEvents_v2.lastEventTimeLoaded - 45 * 60 * 1000L; //always load last 45 min; + else + lastHistoryFetched = 0; return new PumpEnactResult().success(true); } From 2d2bd6d77a6d85e4641c20f12fbe11ef6540d930 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Thu, 21 Dec 2017 08:26:55 +0100 Subject: [PATCH 20/39] remove string with no default translation --- app/src/main/res/values-el/strings.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index d1738abd28..c986fdba7f 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -208,7 +208,6 @@ Σύνδεση Συνδέθηκε Αποσύνδεση - Συγχρονισμός προφίλ στην αντλία Ρυθμίσεις αντλίας DanaR Nightscout Άδεια χρήσης τελικού χρήστη @@ -675,4 +674,4 @@ Τοπικές Ειδοποιήσεις Ειδοποίησε αν δεν ληφθούν δεδομένα μετρήσεων BG Απενεργοποιεί το bluetooth του τηλεφώνου για ένα δευτερόλεπτο αν δεν είναι δυνατή η σύνδεση με την αντλία.Αυτό μπορεί να βοηθήσει σε ορισμένα τηλέφωνα όπου το bluetooth παγώνει - \ No newline at end of file + From 176c5f46ff5d5f1131a5e162de311d53404ad300 Mon Sep 17 00:00:00 2001 From: Andrew Warrington Date: Thu, 21 Dec 2017 09:50:16 +0100 Subject: [PATCH 21/39] Ensure basal rate shown as a percentage if required according to user preferences. --- .../plugins/Wear/wearintegration/WatchUpdaterService.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java index d87ac2e69c..8e37be92e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java @@ -639,9 +639,13 @@ public class WatchUpdaterService extends WearableListenerService implements String basalStringResult; TemporaryBasal activeTemp = treatmentsInterface.getTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { - basalStringResult = activeTemp.toStringVeryShort(); + basalStringResult = activeTemp.toStringShort(); } else { - basalStringResult = DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + "U/h"; + if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false)) { + basalStringResult = "100%"; + } else { + basalStringResult = DecimalFormatter.to2Decimal(MainApp.getConfigBuilder().getProfile().getBasal()) + "U/h"; + } } return basalStringResult; } From 771f9eac1aef8be77a8a0b87a14280b0b16cd75f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 00:12:40 +0100 Subject: [PATCH 22/39] LocalProfile TimeListEdit min, max --- .../plugins/ProfileLocal/LocalProfileFragment.java | 11 +++++++---- .../main/java/info/nightscout/utils/TimeListEdit.java | 10 +++++++--- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java index 8637b863fb..ebd31e915f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java @@ -23,6 +23,7 @@ import java.text.DecimalFormat; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventInitializationChanged; +import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.plugins.Careportal.CareportalFragment; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; @@ -84,15 +85,17 @@ public class LocalProfileFragment extends SubscriberFragment { } }; + PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription(); + View layout = inflater.inflate(R.layout.localprofile_fragment, container, false); diaView = (NumberPicker) layout.findViewById(R.id.localprofile_dia); diaView.setParams(localProfilePlugin.dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch); mgdlView = (RadioButton) layout.findViewById(R.id.localprofile_mgdl); mmolView = (RadioButton) layout.findViewById(R.id.localprofile_mmol); - icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.sResources.getString(R.string.nsprofileview_ic_label) + ":", getPlugin().ic, null, 0.1d, new DecimalFormat("0.0"), save); - isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.sResources.getString(R.string.nsprofileview_isf_label) + ":", getPlugin().isf, null, 0.1d, new DecimalFormat("0.0"), save); - basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.sResources.getString(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), getPlugin().basal, null, 0.01d, new DecimalFormat("0.00"), save); - targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.sResources.getString(R.string.nsprofileview_target_label) + ":", getPlugin().targetLow, getPlugin().targetHigh, 0.1d, new DecimalFormat("0.0"), save); + icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.sResources.getString(R.string.nsprofileview_ic_label) + ":", getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save); + isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.sResources.getString(R.string.nsprofileview_isf_label) + ":", getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save); + basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.sResources.getString(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save); + targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.sResources.getString(R.string.nsprofileview_target_label) + ":", getPlugin().targetLow, getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save); profileswitchButton = (Button) layout.findViewById(R.id.localprofile_profileswitch); if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) { diff --git a/app/src/main/java/info/nightscout/utils/TimeListEdit.java b/app/src/main/java/info/nightscout/utils/TimeListEdit.java index af3668310a..bc41ece59d 100644 --- a/app/src/main/java/info/nightscout/utils/TimeListEdit.java +++ b/app/src/main/java/info/nightscout/utils/TimeListEdit.java @@ -52,6 +52,8 @@ public class TimeListEdit { private JSONArray data1; private JSONArray data2; private double step; + private double min; + private double max; private NumberFormat formatter; private Runnable save; private LinearLayout layout; @@ -59,7 +61,7 @@ public class TimeListEdit { private int inflatedUntil = -1; - public TimeListEdit(Context context, View view, int resLayoutId, String label, JSONArray data1, JSONArray data2, double step, NumberFormat formatter, Runnable save) { + public TimeListEdit(Context context, View view, int resLayoutId, String label, JSONArray data1, JSONArray data2, double min, double max, double step, NumberFormat formatter, Runnable save) { this.context = context; this.view = view; this.resLayoutId = resLayoutId; @@ -67,6 +69,8 @@ public class TimeListEdit { this.data1 = data1; this.data2 = data2; this.step = step; + this.min = min; + this.max = max; this.formatter = formatter; this.save = save; buildView(); @@ -239,8 +243,8 @@ public class TimeListEdit { if (i == 0) next = ONEHOURINSECONDS; fillSpinner(timeSpinner, secondFromMidnight(i), previous, next); - editText1.setParams(value1(i), 0.1d, 100d, step, formatter, false); - editText2.setParams(value2(i), 0.1d, 100d, step, formatter, false); + editText1.setParams(value1(i), min, max, step, formatter, false); + editText2.setParams(value2(i), min, max, step, formatter, false); if (data2 == null) { editText2.setVisibility(View.GONE); From a5c4495a5d8bca9c2fa3c5d35f5e5ac9e1904c5b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 00:17:46 +0100 Subject: [PATCH 23/39] BolusWizard use 0 for insulin correction if in range --- app/src/main/java/info/nightscout/utils/BolusWizard.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/utils/BolusWizard.java b/app/src/main/java/info/nightscout/utils/BolusWizard.java index a97ed233ff..5a683f1aaa 100644 --- a/app/src/main/java/info/nightscout/utils/BolusWizard.java +++ b/app/src/main/java/info/nightscout/utils/BolusWizard.java @@ -71,7 +71,9 @@ public class BolusWizard { targetBGLow = Profile.fromMgdlToUnits(tempTarget.low, specificProfile.getUnits()); targetBGHigh = Profile.fromMgdlToUnits(tempTarget.high, specificProfile.getUnits()); } - if (bg <= targetBGLow) { + if (bg >= targetBGLow && bg <= targetBGHigh) { + bgDiff = 0d; + } else if (bg <= targetBGLow) { bgDiff = bg - targetBGLow; } else { bgDiff = bg - targetBGHigh; From 6b23ba10bd49a59ceb29a97b8307293cc8951246 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 00:37:22 +0100 Subject: [PATCH 24/39] format output date to be displayed on iDevices correctly --- app/src/main/java/info/nightscout/utils/DateUtil.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/info/nightscout/utils/DateUtil.java b/app/src/main/java/info/nightscout/utils/DateUtil.java index c406568730..68d28760d3 100644 --- a/app/src/main/java/info/nightscout/utils/DateUtil.java +++ b/app/src/main/java/info/nightscout/utils/DateUtil.java @@ -27,6 +27,8 @@ public class DateUtil { /** * The date format in iso. */ + private static String FORMAT_DATE_ISO_OUT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; + private static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ssZ"; private static String FORMAT_DATE_ISO_MSEC = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; private static String FORMAT_DATE_ISO_MSEC_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; @@ -79,7 +81,7 @@ public class DateUtil { * @return the iso-formatted date string */ public static String toISOString(Date date, String format, TimeZone tz) { - if (format == null) format = FORMAT_DATE_ISO; + if (format == null) format = FORMAT_DATE_ISO_OUT; if (tz == null) tz = TimeZone.getDefault(); DateFormat f = new SimpleDateFormat(format, Locale.getDefault()); f.setTimeZone(tz); @@ -87,11 +89,11 @@ public class DateUtil { } public static String toISOString(Date date) { - return toISOString(date, FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC")); + return toISOString(date, FORMAT_DATE_ISO_OUT, TimeZone.getTimeZone("UTC")); } public static String toISOString(long date) { - return toISOString(new Date(date), FORMAT_DATE_ISO, TimeZone.getTimeZone("UTC")); + return toISOString(new Date(date), FORMAT_DATE_ISO_OUT, TimeZone.getTimeZone("UTC")); } public static Date toDate(Integer seconds) { From 74abdc02712e3a4ba634d5f50456b8fa7c9e6c4f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 01:35:52 +0100 Subject: [PATCH 25/39] fix disconnecting pump --- .../androidaps/interfaces/PumpInterface.java | 2 +- .../plugins/Actions/dialogs/NewTempBasalDialog.java | 2 +- .../plugins/Overview/Dialogs/WizardDialog.java | 2 +- .../plugins/Overview/OverviewFragment.java | 13 ++++++++----- .../androidaps/plugins/PumpDanaR/DanaRPlugin.java | 6 +++--- .../plugins/PumpDanaRKorean/DanaRKoreanPlugin.java | 6 +++--- .../androidaps/plugins/PumpDanaRS/DanaRSPlugin.java | 4 ++-- .../plugins/PumpDanaRv2/DanaRv2Plugin.java | 4 ++-- .../androidaps/plugins/PumpMDI/MDIPlugin.java | 2 +- .../plugins/PumpVirtual/VirtualPumpPlugin.java | 2 +- .../nightscout/androidaps/queue/CommandQueue.java | 4 ++-- .../queue/commands/CommandTempBasalPercent.java | 6 ++++-- 12 files changed, 29 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java index a3ada67538..087a1dd0bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java @@ -36,7 +36,7 @@ public interface PumpInterface { PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo); void stopBolusDelivering(); PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, boolean enforceNew); - PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes); + PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew); PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes); //some pumps might set a very short temp close to 100% as cancelling a temp can be noisy //when the cancel request is requested by the user (forced), the pump should always do a real cancel diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java index e734cd4f96..e6c653b5ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java @@ -155,7 +155,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi } }; if (setAsPercent) { - ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(finalBasalPercent, finalDurationInMinutes, callback); + ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(finalBasalPercent, finalDurationInMinutes, true, callback); } else { ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(finalBasal, finalDurationInMinutes, true, callback); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index 464c422596..28dbf899c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -344,7 +344,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com activeloop.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000); MainApp.bus().post(new EventRefreshOverview("WizardDialog")); } - ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(0d, 120, true, new Callback() { + ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 120, true, new Callback() { @Override public void run() { if (!result.success) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 344804cf7f..088918c586 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -78,6 +78,7 @@ import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Careportal.CareportalFragment; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; @@ -330,6 +331,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, super.onCreateContextMenu(menu, v, menuInfo); if (v == apsModeView) { final LoopPlugin activeloop = ConfigBuilderPlugin.getActiveLoop(); + final PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription(); if (activeloop == null) return; menu.setHeaderTitle(MainApp.sResources.getString(R.string.loop)); @@ -340,7 +342,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, menu.add(MainApp.sResources.getString(R.string.suspendloopfor2h)); menu.add(MainApp.sResources.getString(R.string.suspendloopfor3h)); menu.add(MainApp.sResources.getString(R.string.suspendloopfor10h)); - menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor30m)); + if (pumpDescription.tempDurationStep <= 30) + menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor30m)); menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor1h)); menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor2h)); menu.add(MainApp.sResources.getString(R.string.disconnectpumpfor3h)); @@ -479,7 +482,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor30m))) { activeloop.disconnectTo(System.currentTimeMillis() + 30L * 60 * 1000); updateGUI("suspendmenu"); - ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(0d, 30, true, new Callback() { + ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 30, true, new Callback() { @Override public void run() { if (!result.success) { @@ -492,7 +495,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor1h))) { activeloop.disconnectTo(System.currentTimeMillis() + 1 * 60L * 60 * 1000); updateGUI("suspendmenu"); - ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(0d, 60, true, new Callback() { + ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 60, true, new Callback() { @Override public void run() { if (!result.success) { @@ -505,7 +508,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor2h))) { activeloop.disconnectTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000); updateGUI("suspendmenu"); - ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(0d, 2 * 60, true, new Callback() { + ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 2 * 60, true, new Callback() { @Override public void run() { if (!result.success) { @@ -518,7 +521,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } else if (item.getTitle().equals(MainApp.sResources.getString(R.string.disconnectpumpfor3h))) { activeloop.disconnectTo(System.currentTimeMillis() + 3 * 60L * 60 * 1000); updateGUI("suspendmenu"); - ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(0d, 3 * 60, true, new Callback() { + ConfigBuilderPlugin.getCommandQueue().tempBasalPercent(0, 3 * 60, true, new Callback() { @Override public void run() { if (!result.success) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java index 167c430a6e..affa668148 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java @@ -434,7 +434,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, DanaRInterface, C // Convert duration from minutes to hours if (Config.logPumpActions) log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); - return setTempBasalPercent(percentRate, durationInMinutes); + return setTempBasalPercent(percentRate, durationInMinutes, false); } if (doExtendedTemp) { // Check if some temp is already in progress @@ -499,7 +499,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, DanaRInterface, C } @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder(); percent = configBuilderPlugin.applyBasalConstraints(percent); @@ -514,7 +514,7 @@ public class DanaRPlugin implements PluginBase, PumpInterface, DanaRInterface, C if (percent > getPumpDescription().maxTempPercent) percent = getPumpDescription().maxTempPercent; TemporaryBasal runningTB = MainApp.getConfigBuilder().getRealTempBasalFromHistory(System.currentTimeMillis()); - if (runningTB != null && runningTB.percentRate == percent) { + if (runningTB != null && runningTB.percentRate == percent && !enforceNew) { result.enacted = false; result.success = true; result.isTempCancel = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java index 32c9f209ef..0caab03cc8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java @@ -436,7 +436,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, DanaRInterf // Convert duration from minutes to hours if (Config.logPumpActions) log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); - return setTempBasalPercent(percentRate, durationInMinutes); + return setTempBasalPercent(percentRate, durationInMinutes, false); } if (doExtendedTemp) { // Check if some temp is already in progress @@ -501,7 +501,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, DanaRInterf } @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder(); percent = configBuilderPlugin.applyBasalConstraints(percent); @@ -516,7 +516,7 @@ public class DanaRKoreanPlugin implements PluginBase, PumpInterface, DanaRInterf if (percent > getPumpDescription().maxTempPercent) percent = getPumpDescription().maxTempPercent; TemporaryBasal runningTB = MainApp.getConfigBuilder().getRealTempBasalFromHistory(System.currentTimeMillis()); - if (runningTB != null && runningTB.percentRate == percent) { + if (runningTB != null && runningTB.percentRate == percent && enforceNew) { result.enacted = false; result.success = true; result.isTempCancel = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java index 87d8ccad5d..fcbd89cfab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java @@ -580,7 +580,7 @@ public class DanaRSPlugin implements PluginBase, PumpInterface, DanaRInterface, } @Override - public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { + public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder(); percent = configBuilderPlugin.applyBasalConstraints(percent); @@ -595,7 +595,7 @@ public class DanaRSPlugin implements PluginBase, PumpInterface, DanaRInterface, if (percent > getPumpDescription().maxTempPercent) percent = getPumpDescription().maxTempPercent; TemporaryBasal runningTB = MainApp.getConfigBuilder().getTempBasalFromHistory(System.currentTimeMillis()); - if (runningTB != null && runningTB.percentRate == percent) { + if (runningTB != null && runningTB.percentRate == percent && !enforceNew) { result.enacted = false; result.success = true; result.isTempCancel = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java index 0c3ac39860..f074cb84c0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java @@ -437,7 +437,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, DanaRInterface, } @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); ConfigBuilderPlugin configBuilderPlugin = MainApp.getConfigBuilder(); percent = configBuilderPlugin.applyBasalConstraints(percent); @@ -452,7 +452,7 @@ public class DanaRv2Plugin implements PluginBase, PumpInterface, DanaRInterface, if (percent > getPumpDescription().maxTempPercent) percent = getPumpDescription().maxTempPercent; TemporaryBasal runningTB = MainApp.getConfigBuilder().getRealTempBasalFromHistory(System.currentTimeMillis()); - if (runningTB != null && runningTB.percentRate == percent) { + if (runningTB != null && runningTB.percentRate == percent && !enforceNew) { result.enacted = false; result.success = true; result.isTempCancel = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java index fd5d2bd270..564d29d53b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java @@ -204,7 +204,7 @@ public class MDIPlugin implements PluginBase, PumpInterface { } @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew) { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.instance().getString(R.string.pumperror); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java index c278f7fb16..13d3f134f4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java @@ -304,7 +304,7 @@ public class VirtualPumpPlugin implements PluginBase, PumpInterface { } @Override - public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes) { + public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, boolean enforceNew) { TreatmentsInterface treatmentsInterface = MainApp.getConfigBuilder(); PumpEnactResult result = new PumpEnactResult(); if (MainApp.getConfigBuilder().isTempBasalInProgress()) { diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index b69c41e6c4..1d5fa468a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -203,7 +203,7 @@ public class CommandQueue { } // returns true if command is queued - public boolean tempBasalPercent(int percent, int durationInMinutes, Callback callback) { + public boolean tempBasalPercent(int percent, int durationInMinutes, boolean enforceNew, Callback callback) { if (isRunning(Command.CommandType.TEMPBASAL)) { if (callback != null) callback.result(executingNowError()).run(); @@ -216,7 +216,7 @@ public class CommandQueue { Integer percentAfterConstraints = MainApp.getConfigBuilder().applyBasalConstraints(percent); // add new command to queue - add(new CommandTempBasalPercent(percentAfterConstraints, durationInMinutes, callback)); + add(new CommandTempBasalPercent(percentAfterConstraints, durationInMinutes, enforceNew, callback)); notifyAboutNewCommand(); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java index 663a20380d..e037f0b869 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java @@ -18,17 +18,19 @@ public class CommandTempBasalPercent extends Command { int durationInMinutes; int percent; + boolean enforceNew; - public CommandTempBasalPercent(int percent, int durationInMinutes, Callback callback) { + public CommandTempBasalPercent(int percent, int durationInMinutes, boolean enforceNew, Callback callback) { commandType = CommandType.TEMPBASAL; this.percent = percent; this.durationInMinutes = durationInMinutes; + this.enforceNew = enforceNew; this.callback = callback; } @Override public void execute() { - PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setTempBasalPercent(percent, durationInMinutes); + PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setTempBasalPercent(percent, durationInMinutes, enforceNew); if (Config.logCongigBuilderActions) log.debug("setTempBasalPercent percent: " + percent + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) From 31975396a2f2ffaf06ef72034588df1e5d132909 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 02:55:40 +0100 Subject: [PATCH 26/39] use joda-time --- app/build.gradle | 2 + .../info/nightscout/androidaps/MainApp.java | 3 ++ .../java/info/nightscout/utils/DateUtil.java | 42 ++++--------------- .../info/nightscout/utils/DateUtilTest.java | 15 +++++-- 4 files changed, 23 insertions(+), 39 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index ea54e3ac3b..00abdd64a0 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -188,4 +188,6 @@ dependencies { compile 'com.google.code.gson:gson:2.7' compile 'com.google.guava:guava:20.0' + compile 'net.danlew:android.joda:2.9.9.1' + testCompile 'joda-time:joda-time:2.9.4.2' } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index bd0ba7695e..4bba16080b 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -15,6 +15,8 @@ import com.squareup.otto.Bus; import com.squareup.otto.LoggingBus; import com.squareup.otto.ThreadEnforcer; +import net.danlew.android.joda.JodaTimeAndroid; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -96,6 +98,7 @@ public class MainApp extends Application { super.onCreate(); Fabric.with(this, new Crashlytics()); Fabric.with(this, new Answers()); + JodaTimeAndroid.init(this); Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION); log.info("Version: " + BuildConfig.VERSION_NAME); log.info("BuildVersion: " + BuildConfig.BUILDVERSION); diff --git a/app/src/main/java/info/nightscout/utils/DateUtil.java b/app/src/main/java/info/nightscout/utils/DateUtil.java index 68d28760d3..86965621d2 100644 --- a/app/src/main/java/info/nightscout/utils/DateUtil.java +++ b/app/src/main/java/info/nightscout/utils/DateUtil.java @@ -2,10 +2,12 @@ package info.nightscout.utils; import android.support.v4.util.LongSparseArray; import android.text.format.DateUtils; -import android.util.SparseIntArray; + +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; import java.text.DateFormat; -import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; @@ -29,10 +31,6 @@ public class DateUtil { */ private static String FORMAT_DATE_ISO_OUT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; - private static String FORMAT_DATE_ISO = "yyyy-MM-dd'T'HH:mm:ssZ"; - private static String FORMAT_DATE_ISO_MSEC = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private static String FORMAT_DATE_ISO_MSEC_UTC = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; - /** * Takes in an ISO date string of the following format: * yyyy-mm-ddThh:mm:ss.ms+HoMo @@ -43,33 +41,10 @@ public class DateUtil { */ public static Date fromISODateString(String isoDateString) throws Exception { - SimpleDateFormat f = new SimpleDateFormat(FORMAT_DATE_ISO, Locale.getDefault()); - Date date; - f.setTimeZone(TimeZone.getTimeZone("UTC")); - try { - date = f.parse(isoDateString); - return date; - } catch (ParseException e) { - } - - f = new SimpleDateFormat(FORMAT_DATE_ISO_MSEC, Locale.getDefault()); - f.setTimeZone(TimeZone.getTimeZone("UTC")); - try { - date = f.parse(isoDateString); - return date; - } catch (ParseException e) { - } - - f = new SimpleDateFormat(FORMAT_DATE_ISO_MSEC_UTC, Locale.getDefault()); - f.setTimeZone(TimeZone.getTimeZone("UTC")); - try { - date = f.parse(isoDateString); - return date; - } catch (ParseException e) { - } - - throw new ParseException("Unparseable date: " + isoDateString, 0); + DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser(); + DateTime dateTime = DateTime.parse(isoDateString, parser); + return dateTime.toDate(); } /** @@ -99,11 +74,8 @@ public class DateUtil { public static Date toDate(Integer seconds) { Calendar calendar = new GregorianCalendar(); calendar.set(Calendar.HOUR_OF_DAY, seconds / 60 / 60); - String a = calendar.getTime().toString(); calendar.set(Calendar.MINUTE, (seconds / 60) % 60); - String b = calendar.getTime().toString(); calendar.set(Calendar.SECOND, 0); - String c = calendar.getTime().toString(); return calendar.getTime(); } diff --git a/app/src/test/java/info/nightscout/utils/DateUtilTest.java b/app/src/test/java/info/nightscout/utils/DateUtilTest.java index 4b48148341..d720487201 100644 --- a/app/src/test/java/info/nightscout/utils/DateUtilTest.java +++ b/app/src/test/java/info/nightscout/utils/DateUtilTest.java @@ -3,7 +3,9 @@ package info.nightscout.utils; import org.junit.Test; -import static org.junit.Assert.*; +import java.util.Date; + +import static org.junit.Assert.assertEquals; /** * Created by mike on 20.11.2017. @@ -17,10 +19,15 @@ public class DateUtilTest { @Test public void fromISODateStringTest() throws Exception { - assertEquals( 1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").getTime()); - assertEquals( 1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").getTime()); - assertEquals( 1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").getTime()); + assertEquals(1511124634417L, DateUtil.fromISODateString("2017-11-19T22:50:34.417+0200").getTime()); + assertEquals(1511124634000L, DateUtil.fromISODateString("2017-11-19T22:50:34+0200").getTime()); + assertEquals(1512317365000L, DateUtil.fromISODateString("2017-12-03T16:09:25.000Z").getTime()); + assertEquals(1513902750000L, DateUtil.fromISODateString("2017-12-22T00:32:30Z").getTime()); } + @Test + public void toISOStringTest() throws Exception { + assertEquals("2017-12-22T00:32:30Z", DateUtil.toISOString(new Date(1513902750000L))); + } } From 5bc6ea04c2f361a9592baf7270ca2fe22119a57b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 03:27:13 +0100 Subject: [PATCH 27/39] Double -> double --- .../info/nightscout/androidaps/interfaces/InsulinInterface.java | 2 +- .../androidaps/plugins/Insulin/InsulinFastactingPlugin.java | 2 +- .../plugins/Insulin/InsulinFastactingProlongedPlugin.java | 2 +- .../androidaps/plugins/Insulin/InsulinOrefBasePlugin.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java index 0803f65373..48efa587d8 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java @@ -21,5 +21,5 @@ public interface InsulinInterface { String getFriendlyName(); String getComment(); double getDia(); - public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia); + public Iob iobCalcForTreatment(Treatment treatment, long time, double dia); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingPlugin.java index c7164ea60e..6218a2ecfe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingPlugin.java @@ -107,7 +107,7 @@ public class InsulinFastactingPlugin implements PluginBase, InsulinInterface { } @Override - public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) { + public Iob iobCalcForTreatment(Treatment treatment, long time, double dia) { Iob result = new Iob(); double scaleFactor = 3.0 / dia; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingProlongedPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingProlongedPlugin.java index 99c35a6c0b..4155a9be56 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingProlongedPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinFastactingProlongedPlugin.java @@ -107,7 +107,7 @@ public class InsulinFastactingProlongedPlugin implements PluginBase, InsulinInte } @Override - public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) { + public Iob iobCalcForTreatment(Treatment treatment, long time, double dia) { Iob result = new Iob(); //Double scaleFactor = 3.0 / dia; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java index 6210f91c9a..cbe5f2ff64 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java @@ -64,7 +64,7 @@ public abstract class InsulinOrefBasePlugin implements PluginBase, InsulinInterf } @Override - public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) { + public Iob iobCalcForTreatment(Treatment treatment, long time, double dia) { Iob result = new Iob(); int peak = getPeak(); From 25667bc79eebbd16e7add958001aef4f537cd2d1 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 11:57:59 +0100 Subject: [PATCH 28/39] RS fix crash when pairing is not confirmed on pump --- .../plugins/PumpDanaRS/activities/PairingProgressDialog.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java index 00cbdb4628..a663d14245 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java @@ -118,7 +118,7 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic @Override public void dismiss() { - super.dismiss(); + super.dismissAllowingStateLoss(); if (helperActivity != null) { helperActivity.finish(); } From 600e2ade1c9eabb8bf361940d8d08ca2e3588a13 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 22 Dec 2017 19:50:16 +0100 Subject: [PATCH 29/39] SingleClickButton --- .../plugins/Actions/ActionsFragment.java | 30 ++++----- .../plugins/Actions/dialogs/FillDialog.java | 2 + .../dialogs/NewExtendedBolusDialog.java | 9 +-- .../Actions/dialogs/NewTempBasalDialog.java | 2 + .../Dialogs/NewNSTreatmentDialog.java | 1 + .../Overview/Dialogs/CalibrationDialog.java | 1 + .../Overview/Dialogs/NewTreatmentDialog.java | 1 + .../Overview/Dialogs/WizardDialog.java | 1 + .../plugins/Overview/OverviewFragment.java | 23 ++++--- .../nightscout/utils/SingleClickButton.java | 67 +++++++++++++++++++ app/src/main/res/layout/actions_fragment.xml | 14 ++-- .../main/res/layout/careportal_fragment.xml | 40 +++++------ app/src/main/res/layout/overview_fragment.xml | 10 +-- .../res/layout/overview_fragment_nsclient.xml | 6 +- .../overview_fragment_nsclient_tablet.xml | 8 +-- .../layout/overview_fragment_smallheight.xml | 8 +-- .../overview_newextendedbolus_dialog.xml | 8 +++ 17 files changed, 155 insertions(+), 76 deletions(-) create mode 100644 app/src/main/java/info/nightscout/utils/SingleClickButton.java diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java index 910f032fc5..d6f56e501b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java @@ -8,7 +8,6 @@ import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.Button; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.answers.Answers; @@ -33,6 +32,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.utils.SingleClickButton; /** * A simple {@link Fragment} subclass. @@ -45,13 +45,13 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL return actionsPlugin; } - Button profileSwitch; - Button tempTarget; - Button extendedBolus; - Button extendedBolusCancel; - Button tempBasal; - Button tempBasalCancel; - Button fill; + SingleClickButton profileSwitch; + SingleClickButton tempTarget; + SingleClickButton extendedBolus; + SingleClickButton extendedBolusCancel; + SingleClickButton tempBasal; + SingleClickButton tempBasalCancel; + SingleClickButton fill; public ActionsFragment() { super(); @@ -64,13 +64,13 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL try { View view = inflater.inflate(R.layout.actions_fragment, container, false); - profileSwitch = (Button) view.findViewById(R.id.actions_profileswitch); - tempTarget = (Button) view.findViewById(R.id.actions_temptarget); - extendedBolus = (Button) view.findViewById(R.id.actions_extendedbolus); - extendedBolusCancel = (Button) view.findViewById(R.id.actions_extendedbolus_cancel); - tempBasal = (Button) view.findViewById(R.id.actions_settempbasal); - tempBasalCancel = (Button) view.findViewById(R.id.actions_canceltempbasal); - fill = (Button) view.findViewById(R.id.actions_fill); + profileSwitch = (SingleClickButton) view.findViewById(R.id.actions_profileswitch); + tempTarget = (SingleClickButton) view.findViewById(R.id.actions_temptarget); + extendedBolus = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus); + extendedBolusCancel = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus_cancel); + tempBasal = (SingleClickButton) view.findViewById(R.id.actions_settempbasal); + tempBasalCancel = (SingleClickButton) view.findViewById(R.id.actions_canceltempbasal); + fill = (SingleClickButton) view.findViewById(R.id.actions_fill); profileSwitch.setOnClickListener(this); tempTarget.setOnClickListener(this); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java index 8391f93492..2901ad862f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java @@ -100,6 +100,8 @@ public class FillDialog extends DialogFragment implements OnClickListener { if (button1.getVisibility() == View.GONE && button2.getVisibility() == View.GONE && button3.getVisibility() == View.GONE) { divider.setVisibility(View.GONE); } + + setCancelable(false); return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java index fbb9fafd9b..aea4f4f4aa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewExtendedBolusDialog.java @@ -54,14 +54,9 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli view.findViewById(R.id.ok).setOnClickListener(this); view.findViewById(R.id.cancel).setOnClickListener(this); - return view; - } - @Override - public void onResume() { - super.onResume(); - if (getDialog() != null) - getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); + setCancelable(false); + return view; } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java index e6c653b5ef..0337166fd6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java @@ -102,6 +102,8 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi view.findViewById(R.id.ok).setOnClickListener(this); view.findViewById(R.id.cancel).setOnClickListener(this); basalTypeRadioGroup.setOnCheckedChangeListener(this); + + setCancelable(false); return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java index b284acff91..92c287f888 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java @@ -360,6 +360,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_reuse_layout), options.profile && ps != null && ps.isCPP); showOrHide((ViewGroup) view.findViewById(R.id.careportal_newnstreatment_temptarget_layout), options.tempTarget); + setCancelable(false); return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java index fdc58e92f4..32b34b6f85 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java @@ -76,6 +76,7 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis unitsView = (TextView) view.findViewById(R.id.overview_calibration_units); unitsView.setText(units); + setCancelable(false); return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java index 3b50ae9950..55dc39fc11 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewTreatmentDialog.java @@ -102,6 +102,7 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, textWatcher); editInsulin.setParams(0d, 0d, maxInsulin, ConfigBuilderPlugin.getActivePump().getPumpDescription().bolusStep, new DecimalFormat("0.00"), false, textWatcher); + setCancelable(false); return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index 28dbf899c4..4869300742 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -251,6 +251,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false); initDialog(); + setCancelable(false); return view; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 088918c586..c531b080c0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -52,7 +52,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -113,6 +112,7 @@ import info.nightscout.utils.NSUpload; import info.nightscout.utils.OKDialog; import info.nightscout.utils.Profiler; import info.nightscout.utils.SP; +import info.nightscout.utils.SingleClickButton; import info.nightscout.utils.ToastUtils; public class OverviewFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { @@ -156,11 +156,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, LinearLayoutManager llm; LinearLayout acceptTempLayout; - Button treatmentButton; - Button wizardButton; - Button calibrationButton; - Button acceptTempButton; - Button quickWizardButton; + SingleClickButton treatmentButton; + SingleClickButton wizardButton; + SingleClickButton calibrationButton; + SingleClickButton acceptTempButton; + SingleClickButton quickWizardButton; CheckBox lockScreen; @@ -244,16 +244,16 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph); - treatmentButton = (Button) view.findViewById(R.id.overview_treatmentbutton); + treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton); treatmentButton.setOnClickListener(this); - wizardButton = (Button) view.findViewById(R.id.overview_wizardbutton); + wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton); wizardButton.setOnClickListener(this); - acceptTempButton = (Button) view.findViewById(R.id.overview_accepttempbutton); + acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton); if (acceptTempButton != null) acceptTempButton.setOnClickListener(this); - quickWizardButton = (Button) view.findViewById(R.id.overview_quickwizardbutton); + quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton); quickWizardButton.setOnClickListener(this); - calibrationButton = (Button) view.findViewById(R.id.overview_calibrationbutton); + calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton); if (calibrationButton != null) calibrationButton.setOnClickListener(this); @@ -320,6 +320,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, return view; } catch (Exception e) { Crashlytics.logException(e); + log.debug("Runtime Exception", e); } return null; diff --git a/app/src/main/java/info/nightscout/utils/SingleClickButton.java b/app/src/main/java/info/nightscout/utils/SingleClickButton.java new file mode 100644 index 0000000000..ef0d4d3aec --- /dev/null +++ b/app/src/main/java/info/nightscout/utils/SingleClickButton.java @@ -0,0 +1,67 @@ +package info.nightscout.utils; + +import android.app.Activity; +import android.content.Context; +import android.os.SystemClock; +import android.support.annotation.Nullable; +import android.util.AttributeSet; +import android.view.View; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Created by mike on 22.12.2017. + */ + +public class SingleClickButton extends android.support.v7.widget.AppCompatButton implements View.OnClickListener { + private static Logger log = LoggerFactory.getLogger(SingleClickButton.class); + + Context context; + OnClickListener listener = null; + + public SingleClickButton(Context context) { + super(context); + this.context = context; + super.setOnClickListener(this); + } + + public SingleClickButton(Context context, AttributeSet attrs) { + super(context, attrs); + this.context = context; + super.setOnClickListener(this); + } + + public SingleClickButton(Context context, AttributeSet attrs, int defStyleAttr) { + super(context, attrs, defStyleAttr); + this.context = context; + super.setOnClickListener(this); + } + + @Override + public void setOnClickListener(@Nullable OnClickListener l) { + listener = l; + } + + @Override + public void onClick(final View v) { + setEnabled(false); + new Thread(new Runnable() { + @Override + public void run() { + SystemClock.sleep(3000); + Activity activity = (Activity) context; + if (activity != null) + activity.runOnUiThread(new Runnable() { + @Override + public void run() { + setEnabled(true); + log.debug("Button enabled"); + } + }); + } + }).start(); + if (listener != null) + listener.onClick(v); + } +} diff --git a/app/src/main/res/layout/actions_fragment.xml b/app/src/main/res/layout/actions_fragment.xml index bc8f416770..6673099110 100644 --- a/app/src/main/res/layout/actions_fragment.xml +++ b/app/src/main/res/layout/actions_fragment.xml @@ -13,7 +13,7 @@ android:layout_height="wrap_content" android:orientation="vertical"> -