From 23874ebbd652d663cbb356dd66a496e78777394a Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Tue, 5 Dec 2017 01:24:43 +0100 Subject: [PATCH 01/21] 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/21] 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/21] 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 fa4e80444d73cac320b12e78d20c36dbbbc48aa9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 13 Dec 2017 20:03:24 +0100 Subject: [PATCH 04/21] 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 05/21] 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 06/21] 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 07/21] 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 88adc31dbcbcc0597c963cdc51683637272b9d8b Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Tue, 19 Dec 2017 07:16:41 +0100 Subject: [PATCH 08/21] 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 715366b2b4caaeef64a11f0480c7af98e36d2df4 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Tue, 19 Dec 2017 22:24:46 +0100 Subject: [PATCH 09/21] Don't consider pump initialized if updating basal profile on start failed. --- .../nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index c38d7d7827..d7d733e036 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -356,7 +356,10 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf Profile profile = MainApp.getConfigBuilder().getProfile(); if (!pump.basalProfile.equals(convertProfileToComboProfile(profile))) { - setNewBasalProfile(profile); + PumpEnactResult setNewBasalProfileResult = setNewBasalProfile(profile); + if (!setNewBasalProfileResult.success) { + return; + } } } From f4c1f4a3a15bddaffe3ddfd1c333ef12ab8826a5 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Tue, 19 Dec 2017 23:43:08 +0100 Subject: [PATCH 10/21] Make recovering from command failure more robust. --- .../jotomo/ruffyscripter/RuffyScripter.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java index 73258f931c..006fd38e5f 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java @@ -324,12 +324,12 @@ public class RuffyScripter implements RuffyCommands { return result; } catch (CommandException e) { log.error("CommandException while executing command", e); - recoverFromCommandFailure(); - return activeCmd.getResult().success(false).state(readPumpStateInternal()); + PumpState pumpState = recoverFromCommandFailure(); + return activeCmd.getResult().success(false).state(pumpState); } catch (Exception e) { log.error("Unexpected exception communication with ruffy", e); - recoverFromCommandFailure(); - return activeCmd.getResult().success(false).state(readPumpStateInternal()); + PumpState pumpState = recoverFromCommandFailure(); + return activeCmd.getResult().success(false).state(pumpState); } finally { Menu menu = this.currentMenu; if (activeCmd.getResult().success && menu != null && menu.getType() != MenuType.MAIN_MENU) { @@ -416,12 +416,12 @@ public class RuffyScripter implements RuffyCommands { /** * Returns to the main menu (if possible) after a command failure, so that subsequent commands - * reusing the connection won't fail. + * reusing the connection won't fail and returns the current PumpState (empty if unreadable). */ - private void recoverFromCommandFailure() { + private PumpState recoverFromCommandFailure() { Menu menu = this.currentMenu; if (menu == null) { - return; + return null; } MenuType type = menu.getType(); if (type != MenuType.WARNING_OR_ERROR && type != MenuType.MAIN_MENU) { @@ -432,6 +432,12 @@ public class RuffyScripter implements RuffyCommands { log.warn("Error returning to main menu, when trying to recover from command failure", e); } } + try { + return readPumpStateInternal(); + } catch (Exception e) { + log.debug("Reading pump state during recovery failed", e); + return new PumpState(); + } } /** @@ -480,6 +486,7 @@ public class RuffyScripter implements RuffyCommands { state.timestamp = System.currentTimeMillis(); Menu menu = currentMenu; if (menu == null) { + log.debug("Returning empty PumpState, menu is unavailable"); return state; } From 181338e9e2e66496081556c6b93d25cb9d978aa3 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 00:04:14 +0100 Subject: [PATCH 11/21] Another NPE check for failure scenarios. --- .../nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index d7d733e036..5a565a5645 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -804,6 +804,8 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf } private void checkForUnsafeUsage(CommandResult commandResult) { + if (commandResult == null) return; + long lastViolation = 0; if (commandResult.state.unsafeUsageDetected) { lastViolation = System.currentTimeMillis(); From ea1fd8fee875b466026d70e5aab2937aa142e71e Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 10:33:03 +0100 Subject: [PATCH 12/21] Don't declare connection unusable too quickly. --- .../main/java/de/jotomo/ruffyscripter/RuffyScripter.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java index 006fd38e5f..18604cb7b6 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java @@ -187,10 +187,10 @@ public class RuffyScripter implements RuffyCommands { if (!ruffyService.isConnected()) { return false; } - if (System.currentTimeMillis() - menuLastUpdated >= 500) { + if (System.currentTimeMillis() - menuLastUpdated >= 1500) { waitForScreenUpdate(); } - return System.currentTimeMillis() - menuLastUpdated < 500; + return System.currentTimeMillis() - menuLastUpdated < 1500; } catch (RemoteException e) { return false; } @@ -282,7 +282,9 @@ public class RuffyScripter implements RuffyCommands { // on connection loss try to reconnect, confirm warning alerts caused by // the disconnected and then return the command as failed (the caller // can retry if needed). - log.debug("Connection unusable, aborting command and attempting reconnect ..."); + log.debug("Connection unusable (ruffy connection: " + ruffyService.isConnected() + ", " + + "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms, " + + "aborting command and attempting reconnect ..."); cmdThread.interrupt(); activeCmd.getResult().success = false; From 40edb9ff5c5e2357520998fb012d5187f6124f8c Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 13:01:24 +0100 Subject: [PATCH 13/21] Don't update pump basal profile during startup. * Avoids issues of no profile being set yet * Making startup take minutes * KeepAlive will update profile as needed every 5m. --- .../plugins/PumpCombo/ComboPlugin.java | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index 5a565a5645..3df159b876 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -242,6 +242,8 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf @Override public synchronized PumpEnactResult setNewBasalProfile(Profile profile) { if (!isInitialized()) { + // note that this should not happen anymore since the queue is present, which + // issues a READSTATE when starting to issue commands which initializes the pump log.error("setNewBasalProfile not initialized"); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); @@ -283,9 +285,10 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf @Override public boolean isThisProfileSet(Profile profile) { if (!isInitialized()) { - // This is called too soon (for the Combo) on startup, so ignore this. - // The Combo init (refreshDataFromPump) will read the profile and update the pump's - // profile if the pref is set; + /* This might be called too soon during boot. Return true to prevent a request + to update the profile. KeepAlive is called every Constants.keepalivems + and will detect the need for a profile update and apply it. + */ return true; } return pump.basalProfile.equals(convertProfileToComboProfile(profile)); @@ -353,14 +356,6 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf return; } pump.basalProfile = readBasalResult.basalProfile; - - Profile profile = MainApp.getConfigBuilder().getProfile(); - if (!pump.basalProfile.equals(convertProfileToComboProfile(profile))) { - PumpEnactResult setNewBasalProfileResult = setNewBasalProfile(profile); - if (!setNewBasalProfileResult.success) { - return; - } - } } if (!pump.initialized) { From 81ca35515f265ec40a7add6ce472173198f714d9 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Wed, 20 Dec 2017 14:34:30 +0100 Subject: [PATCH 14/21] 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 15/21] 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 2054e76cde491c4d0d0197983aa734e065e94938 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 14:34:56 +0100 Subject: [PATCH 16/21] Handle edge case of setting basal rate in range 0.00 - 0.05. --- README-Combo.md | 2 ++ .../plugins/PumpCombo/ComboPlugin.java | 4 ++++ .../de/jotomo/ruffyscripter/RuffyScripter.java | 2 +- .../commands/SetBasalProfileCommand.java | 16 ++++++++++++---- 4 files changed, 19 insertions(+), 5 deletions(-) diff --git a/README-Combo.md b/README-Combo.md index b4c42f30aa..ced0a5e726 100644 --- a/README-Combo.md +++ b/README-Combo.md @@ -39,6 +39,8 @@ Limitations: pump solely through AAPS. Checking history, reservoir level etc on the pump causes no issues but should be avoided when the Bluetooth icon is displayed on the display, indicating that AAPS is communicating with the pump. +- Setting basal rates where U/h exceeds 10 are currently not supported. Values between 0.01 to 0.04 are rounded + to 0.05, values above have a granularity of 0.05 and values above 1.00 have a granularity of 0.10. Setup: - Configure pump using 360 config software. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index 3df159b876..d79b2737c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -81,6 +81,10 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf pumpDescription.isSetBasalProfileCapable = true; + // this applies to range >= 0.05 U/h && < 1.00 U/h, + // above 1.00 U/h step size is 0.05, + // above 10 U/h, step size is 0.1, + // the smallest non-zero amount is 0.05 U/h, so 0.00 U/h jumps to 0.05 U/h during input pumpDescription.basalStep = 0.01d; pumpDescription.basalMinimumRate = 0.0d; diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java index 18604cb7b6..5ca23cee05 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java @@ -283,7 +283,7 @@ public class RuffyScripter implements RuffyCommands { // the disconnected and then return the command as failed (the caller // can retry if needed). log.debug("Connection unusable (ruffy connection: " + ruffyService.isConnected() + ", " - + "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms, " + + "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms), " + "aborting command and attempting reconnect ..."); cmdThread.interrupt(); activeCmd.getResult().success = false; diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java index a5e42014b6..61114246b8 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java @@ -30,6 +30,7 @@ public class SetBasalProfileCommand extends BaseCommand { scripter.verifyMenuIsDisplayed(MenuType.BASAL_1_MENU); scripter.pressCheckKey(); + Double requestedTotal = 0d; // summary screen is shown; press menu to page through hours, wraps around to summary; scripter.verifyMenuIsDisplayed(MenuType.BASAL_TOTAL); for (int i = 0; i < 24; i++) { @@ -43,6 +44,11 @@ public class SetBasalProfileCommand extends BaseCommand { scripter.verifyMenuIsDisplayed(MenuType.BASAL_SET); double requestedRate = basalProfile.hourlyRates[i]; + if (requestedRate > 0 && requestedRate < 0.05) { + log.debug("rounding requested rate of " + requestedRate + " to supported value 0.05"); + requestedRate = 0.05; + } + requestedTotal += requestedRate; long change = inputBasalRate(requestedRate); if (change != 0) { verifyDisplayedRate(requestedRate, change); @@ -57,10 +63,6 @@ public class SetBasalProfileCommand extends BaseCommand { // check total basal total on pump matches requested total Double pumpTotal = (Double) scripter.getCurrentMenu().getAttribute(MenuAttribute.BASAL_TOTAL); - Double requestedTotal = 0d; - for (int i = 0; i < 24; i++) { - requestedTotal += basalProfile.hourlyRates[i]; - } if (Math.abs(pumpTotal - requestedTotal) > 0.001) { throw new CommandException("Basal total of " + pumpTotal + " differs from requested total of " + requestedTotal); } @@ -75,11 +77,17 @@ public class SetBasalProfileCommand extends BaseCommand { private long inputBasalRate(double requestedRate) { double currentRate = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE); log.debug("Current rate: " + currentRate + ", requested: " + requestedRate); + // the pump changes steps size from 0.01 to 0.05 when crossing 1.00 U long steps = stepsToOne(currentRate) - stepsToOne(requestedRate); if (steps == 0) { return 0; } + + // edge case: 0.00 to 0.05 (or back) is one step, not 5. + if (currentRate == 0 && requestedRate > 0) steps -= 4; + else if (currentRate > 0 && requestedRate == 0) steps += 4; + log.debug("Pressing " + (steps > 0 ? "up" : "down") + " " + Math.abs(steps) + " times"); for (int i = 0; i < Math.abs(steps); i++) { scripter.verifyMenuIsDisplayed(MenuType.BASAL_SET); From 7c04f528cc94e0e8315ff30abbeb90aedac1d893 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 18:03:21 +0100 Subject: [PATCH 17/21] Revert "Handle edge case of setting basal rate in range 0.00 - 0.05." This reverts commit 2054e76cde491c4d0d0197983aa734e065e94938. --- README-Combo.md | 2 -- .../plugins/PumpCombo/ComboPlugin.java | 4 ---- .../de/jotomo/ruffyscripter/RuffyScripter.java | 2 +- .../commands/SetBasalProfileCommand.java | 16 ++++------------ 4 files changed, 5 insertions(+), 19 deletions(-) diff --git a/README-Combo.md b/README-Combo.md index ced0a5e726..b4c42f30aa 100644 --- a/README-Combo.md +++ b/README-Combo.md @@ -39,8 +39,6 @@ Limitations: pump solely through AAPS. Checking history, reservoir level etc on the pump causes no issues but should be avoided when the Bluetooth icon is displayed on the display, indicating that AAPS is communicating with the pump. -- Setting basal rates where U/h exceeds 10 are currently not supported. Values between 0.01 to 0.04 are rounded - to 0.05, values above have a granularity of 0.05 and values above 1.00 have a granularity of 0.10. Setup: - Configure pump using 360 config software. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index d79b2737c9..3df159b876 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -81,10 +81,6 @@ public class ComboPlugin implements PluginBase, PumpInterface, ConstraintsInterf pumpDescription.isSetBasalProfileCapable = true; - // this applies to range >= 0.05 U/h && < 1.00 U/h, - // above 1.00 U/h step size is 0.05, - // above 10 U/h, step size is 0.1, - // the smallest non-zero amount is 0.05 U/h, so 0.00 U/h jumps to 0.05 U/h during input pumpDescription.basalStep = 0.01d; pumpDescription.basalMinimumRate = 0.0d; diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java index 5ca23cee05..18604cb7b6 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java @@ -283,7 +283,7 @@ public class RuffyScripter implements RuffyCommands { // the disconnected and then return the command as failed (the caller // can retry if needed). log.debug("Connection unusable (ruffy connection: " + ruffyService.isConnected() + ", " - + "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms), " + + "time since last menu update: " + (System.currentTimeMillis() - menuLastUpdated) + " ms, " + "aborting command and attempting reconnect ..."); cmdThread.interrupt(); activeCmd.getResult().success = false; diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java index 61114246b8..a5e42014b6 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/commands/SetBasalProfileCommand.java @@ -30,7 +30,6 @@ public class SetBasalProfileCommand extends BaseCommand { scripter.verifyMenuIsDisplayed(MenuType.BASAL_1_MENU); scripter.pressCheckKey(); - Double requestedTotal = 0d; // summary screen is shown; press menu to page through hours, wraps around to summary; scripter.verifyMenuIsDisplayed(MenuType.BASAL_TOTAL); for (int i = 0; i < 24; i++) { @@ -44,11 +43,6 @@ public class SetBasalProfileCommand extends BaseCommand { scripter.verifyMenuIsDisplayed(MenuType.BASAL_SET); double requestedRate = basalProfile.hourlyRates[i]; - if (requestedRate > 0 && requestedRate < 0.05) { - log.debug("rounding requested rate of " + requestedRate + " to supported value 0.05"); - requestedRate = 0.05; - } - requestedTotal += requestedRate; long change = inputBasalRate(requestedRate); if (change != 0) { verifyDisplayedRate(requestedRate, change); @@ -63,6 +57,10 @@ public class SetBasalProfileCommand extends BaseCommand { // check total basal total on pump matches requested total Double pumpTotal = (Double) scripter.getCurrentMenu().getAttribute(MenuAttribute.BASAL_TOTAL); + Double requestedTotal = 0d; + for (int i = 0; i < 24; i++) { + requestedTotal += basalProfile.hourlyRates[i]; + } if (Math.abs(pumpTotal - requestedTotal) > 0.001) { throw new CommandException("Basal total of " + pumpTotal + " differs from requested total of " + requestedTotal); } @@ -77,17 +75,11 @@ public class SetBasalProfileCommand extends BaseCommand { private long inputBasalRate(double requestedRate) { double currentRate = scripter.readBlinkingValue(Double.class, MenuAttribute.BASAL_RATE); log.debug("Current rate: " + currentRate + ", requested: " + requestedRate); - // the pump changes steps size from 0.01 to 0.05 when crossing 1.00 U long steps = stepsToOne(currentRate) - stepsToOne(requestedRate); if (steps == 0) { return 0; } - - // edge case: 0.00 to 0.05 (or back) is one step, not 5. - if (currentRate == 0 && requestedRate > 0) steps -= 4; - else if (currentRate > 0 && requestedRate == 0) steps += 4; - log.debug("Pressing " + (steps > 0 ? "up" : "down") + " " + Math.abs(steps) + " times"); for (int i = 0; i < Math.abs(steps); i++) { scripter.verifyMenuIsDisplayed(MenuType.BASAL_SET); From af4816453eb423892de879c9c315ee9360581214 Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 18:06:09 +0100 Subject: [PATCH 18/21] Add note on supported basal rate ranges. --- README-Combo.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README-Combo.md b/README-Combo.md index b4c42f30aa..096d94e697 100644 --- a/README-Combo.md +++ b/README-Combo.md @@ -39,6 +39,9 @@ Limitations: pump solely through AAPS. Checking history, reservoir level etc on the pump causes no issues but should be avoided when the Bluetooth icon is displayed on the display, indicating that AAPS is communicating with the pump. +- Currently only basal rates in the range of 0.05 to 10 U/h are supported (this also applies when modifying + a profile, e.g. when increasing to 200%, the highest basal rate must not exceed 5 U/h since it will be + doubled. Similarly, when reducing to 50%, the lowest basal rate must be at least 0.10 U/h). Setup: - Configure pump using 360 config software. From 096b2e93a310c8c912c62e88f7e903711422cec9 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 20 Dec 2017 18:26:47 +0100 Subject: [PATCH 19/21] 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 20/21] 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 cf9d55747e07c2d6b5ee6ea121fa70c56f1872ff Mon Sep 17 00:00:00 2001 From: Johannes Mockenhaupt Date: Wed, 20 Dec 2017 21:14:35 +0100 Subject: [PATCH 21/21] Fix NPE. --- .../src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java index 18604cb7b6..44deb879e8 100644 --- a/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java +++ b/ruffyscripter/src/main/java/de/jotomo/ruffyscripter/RuffyScripter.java @@ -241,7 +241,7 @@ public class RuffyScripter implements RuffyCommands { List violations = cmd.validateArguments(); if (!violations.isEmpty()) { log.error("Command argument violations: " + Joiner.on(", ").join(violations)); - return new CommandResult().success(false).state(readPumpStateInternal()); + return new CommandResult().success(false).state(new PumpState()); } synchronized (RuffyScripter.class) { @@ -423,7 +423,7 @@ public class RuffyScripter implements RuffyCommands { private PumpState recoverFromCommandFailure() { Menu menu = this.currentMenu; if (menu == null) { - return null; + return new PumpState(); } MenuType type = menu.getType(); if (type != MenuType.WARNING_OR_ERROR && type != MenuType.MAIN_MENU) {