From ff2f6a8bfb352775c076113c3b7c88c825ca1ea3 Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Thu, 25 Oct 2018 16:33:29 +1300 Subject: [PATCH 001/316] Add UAMSMB Basal Minutes with Min Bolus Increment --- .../main/assets/OpenAPSSMB/determine-basal.js | 18 ++++++++++++------ .../OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 3 +++ .../plugins/OpenAPSSMB/SMBDefaults.java | 2 ++ app/src/main/res/values/strings.xml | 2 ++ app/src/main/res/xml/pref_openapssmb.xml | 16 +++++++++++++++- 5 files changed, 34 insertions(+), 7 deletions(-) diff --git a/app/src/main/assets/OpenAPSSMB/determine-basal.js b/app/src/main/assets/OpenAPSSMB/determine-basal.js index c2db0f270b..bb620bf5c9 100644 --- a/app/src/main/assets/OpenAPSSMB/determine-basal.js +++ b/app/src/main/assets/OpenAPSSMB/determine-basal.js @@ -995,8 +995,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // eventual BG is at/above target // if iob is over max, just cancel any temps - // if we're not here because of SMB, eventual BG is at/above target - if (! (microBolusAllowed && rT.COB)) { + if ( eventualBG >= max_bg ) { rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " >= " + convert_bg(max_bg, profile) + ", "; } if (iob_data.iob > max_iob) { @@ -1047,20 +1046,27 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // if IOB covers more than COB, limit maxBolus to 30m of basal } else if ( iob_data.iob > mealInsulinReq && iob_data.iob > 0 ) { console.error("IOB",iob_data.iob,"> COB",meal_data.mealCOB+"; mealInsulinReq =",mealInsulinReq); - maxBolus = round( profile.current_basal * 30 / 60 ,1); + if (profile.maxUAMSMBBasalMinutes) { + console.error("profile.maxUAMSMBBasalMinutes:",profile.maxUAMSMBBasalMinutes,"profile.current_basal:",profile.current_basal); + maxBolus = round( profile.current_basal * profile.maxUAMSMBBasalMinutes / 60 ,1); + } else { + console.error("profile.maxUAMSMBBasalMinutes undefined: defaulting to 30m"); + maxBolus = round( profile.current_basal * 30 / 60 ,1); + } } else { console.error("profile.maxSMBBasalMinutes:",profile.maxSMBBasalMinutes,"profile.current_basal:",profile.current_basal); maxBolus = round( profile.current_basal * profile.maxSMBBasalMinutes / 60 ,1); } - // bolus 1/2 the insulinReq, up to maxBolus, rounding down to nearest 0.1U - microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*10)/10; + // bolus 1/2 the insulinReq, up to maxBolus, rounding down to nearest bolus increment + var roundSMBTo = 1 / profile.bolus_increment; + microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*roundSMBTo)/roundSMBTo; // calculate a long enough zero temp to eventually correct back up to target var smbTarget = target_bg; var worstCaseInsulinReq = (smbTarget - (naive_eventualBG + minIOBPredBG)/2 ) / sens; var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); // if insulinReq > 0 but not enough for a microBolus, don't set an SMB zero temp - if (insulinReq > 0 && microBolus < 0.1) { + if (insulinReq > 0 && microBolus < profile.bolus_increment) { durationReq = 0; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index 7ede714c10..b284d258b0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -44,6 +44,7 @@ public class DetermineBasalAdapterSMBJS { private JSONObject mMealData; private JSONObject mCurrentTemp; private JSONObject mAutosensData = null; + private long mCurrentTime; private boolean mMicrobolusAllowed; private boolean mSMBAlwaysAllowed; @@ -255,6 +256,8 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_always", SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering); mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); + mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); + mProfile.put("bolus_increment", SMBDefaults.bolus_increment); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java index 0ce8d2bb94..234aa4e12a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java @@ -56,9 +56,11 @@ public class SMBDefaults { //public final static boolean enableSMB_after_carbs = false; // enable supermicrobolus for 6h after carbs, even with 0 COB //public final static boolean allowSMB_with_high_temptarget = false; // allow supermicrobolus (if otherwise enabled) even with high temp targets public final static int maxSMBBasalMinutes = 30; // maximum minutes of basal that can be delivered as a single SMB with uncovered COB + public final static int maxUAMSMBBasalMinutes = 30; // maximum minutes of basal that can be delivered as a single SMB when IOB exceeds COB // curve:"rapid-acting" // Supported curves: "bilinear", "rapid-acting" (Novolog, Novorapid, Humalog, Apidra) and "ultra-rapid" (Fiasp) // useCustomPeakTime:false // allows changing insulinPeakTime // insulinPeakTime:75 // number of minutes after a bolus activity peaks. defaults to 55m for Fiasp if useCustomPeakTime: false public final static int carbsReqThreshold = 1; // grams of carbsReq to trigger a pushover // offline_hotspot:false // enabled an offline-only local wifi hotspot if no Internet available + public final static double bolus_increment = 0.1; // minimum bolus that can be delivered as an SMB } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ae4e572392..46c583c847 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -802,6 +802,8 @@ Show delta with one more decimal place 45 60 75 90 105 120 Max minutes of basal to limit SMB to + 45 60 75 90 105 120 + Max minutes of basal to limit SMB to when UAM is active Unsupported pump firmware Send BG data to xDrip+ dexcomg5_xdripupload diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index e23a364cb8..53e1deef17 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -79,6 +79,20 @@ validate:minNumber="15" validate:testType="numericRange" /> + + - \ No newline at end of file + From 4bc8025ad4f85391ce7e2453d4ee59fe6a144475 Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Thu, 25 Oct 2018 18:27:21 +1300 Subject: [PATCH 002/316] Make min SMB Bolus configurable --- .../OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 2 +- app/src/main/res/values/strings.xml | 3 ++- app/src/main/res/xml/pref_openapssmb.xml | 14 ++++++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index b284d258b0..a05b5aae45 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -257,7 +257,7 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); - mProfile.put("bolus_increment", SMBDefaults.bolus_increment); + mProfile.put("bolus_increment", SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment)); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 46c583c847..f675c3b613 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -803,7 +803,8 @@ 45 60 75 90 105 120 Max minutes of basal to limit SMB to 45 60 75 90 105 120 - Max minutes of basal to limit SMB to when UAM is active + Max minutes of basal to limit SMB to for UAM + Minimum bolus that can be delivered as an SMB Unsupported pump firmware Send BG data to xDrip+ dexcomg5_xdripupload diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index 53e1deef17..cc09aa707d 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -93,6 +93,20 @@ validate:minNumber="15" validate:testType="numericRange" /> + + + Date: Thu, 25 Oct 2018 18:47:50 +1300 Subject: [PATCH 003/316] use number as numberDecimal does not apply restrictions --- app/src/main/res/xml/pref_openapssmb.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index cc09aa707d..87bb5bb5ce 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -96,7 +96,7 @@ Date: Thu, 25 Oct 2018 20:02:02 +1300 Subject: [PATCH 004/316] get SMB bolus limits working --- .../plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 2 +- app/src/main/res/values/strings.xml | 1 + app/src/main/res/xml/pref_openapssmb.xml | 9 ++++----- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index a05b5aae45..311aa12bd2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -257,7 +257,7 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); - mProfile.put("bolus_increment", SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment)); + mProfile.put("bolus_increment", SP.getDouble("bolus_increment", SMBDefaults.bolus_increment)); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f675c3b613..11960880b5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -804,6 +804,7 @@ Max minutes of basal to limit SMB to 45 60 75 90 105 120 Max minutes of basal to limit SMB to for UAM + 0.1 Minimum bolus that can be delivered as an SMB Unsupported pump firmware Send BG data to xDrip+ diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index 87bb5bb5ce..d74c9ef9aa 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -95,15 +95,14 @@ From 4592f290db4097e017ca34ebe1c4b157ae7c88d0 Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Thu, 25 Oct 2018 20:13:19 +1300 Subject: [PATCH 005/316] remove stuff thats not needed --- .../plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 1 - 1 file changed, 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index 311aa12bd2..7e17c387a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -44,7 +44,6 @@ public class DetermineBasalAdapterSMBJS { private JSONObject mMealData; private JSONObject mCurrentTemp; private JSONObject mAutosensData = null; - private long mCurrentTime; private boolean mMicrobolusAllowed; private boolean mSMBAlwaysAllowed; From 84716eb7775f8cb4c1979ea9b3f5ffd7c1bb47ac Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Fri, 26 Oct 2018 18:49:18 +1300 Subject: [PATCH 006/316] change to using key convention --- .../plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 2 +- app/src/main/res/values/strings.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index 7e17c387a0..ffa1954bad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -256,7 +256,7 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); - mProfile.put("bolus_increment", SP.getDouble("bolus_increment", SMBDefaults.bolus_increment)); + mProfile.put("bolus_increment", SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment)); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 11960880b5..e640191b23 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -804,7 +804,7 @@ Max minutes of basal to limit SMB to 45 60 75 90 105 120 Max minutes of basal to limit SMB to for UAM - 0.1 + bolus_increment Minimum bolus that can be delivered as an SMB Unsupported pump firmware Send BG data to xDrip+ From 7c4c42669087a858c64503ba0631fe6e2d41bfa9 Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Fri, 26 Oct 2018 18:50:01 +1300 Subject: [PATCH 007/316] remove string --- app/src/main/res/xml/pref_openapssmb.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index d74c9ef9aa..f26a58ffd0 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -96,7 +96,7 @@ Date: Fri, 26 Oct 2018 20:23:25 +1300 Subject: [PATCH 008/316] SMB Interval addition --- app/src/main/assets/OpenAPSSMB/determine-basal.js | 14 ++++++++++---- .../OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 1 + .../plugins/OpenAPSSMB/SMBDefaults.java | 1 + app/src/main/res/values/strings.xml | 2 ++ app/src/main/res/xml/pref_openapssmb.xml | 15 ++++++++++++++- 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/app/src/main/assets/OpenAPSSMB/determine-basal.js b/app/src/main/assets/OpenAPSSMB/determine-basal.js index c2db0f270b..1f6499ee87 100644 --- a/app/src/main/assets/OpenAPSSMB/determine-basal.js +++ b/app/src/main/assets/OpenAPSSMB/determine-basal.js @@ -1085,17 +1085,23 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } rT.reason += ". "; - //allow SMBs every 3 minutes - var nextBolusMins = round(3-lastBolusAge,1); + //allow SMBs every 3 minutes by default + var SMBInterval = 3; + if (profile.SMBInterval) { + // allow SMBIntervals between 1 and 10 minutes + SMBInterval = Math.min(10,Math.max(1,profile.SMBInterval)); + } + var nextBolusMins = round(SMBInterval-lastBolusAge,0); + var nextBolusSeconds = round((SMBInterval - lastBolusAge) * 60, 0) % 60; //console.error(naive_eventualBG, insulinReq, worstCaseInsulinReq, durationReq); console.error("naive_eventualBG",naive_eventualBG+",",durationReq+"m "+smbLowTempReq+"U/h temp needed; last bolus",lastBolusAge+"m ago; maxBolus: "+maxBolus); - if (lastBolusAge > 3) { + if (lastBolusAge > SMBInterval) { if (microBolus > 0) { rT.units = microBolus; rT.reason += "Microbolusing " + microBolus + "U. "; } } else { - rT.reason += "Waiting " + nextBolusMins + "m to microbolus again. "; + rT.reason += "Waiting " + nextBolusMins + "m " + nextBolusSeconds + "s to microbolus again. "; } //rT.reason += ". "; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index 7ede714c10..d82e98a7b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -249,6 +249,7 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap); mProfile.put("enableUAM", SP.getBoolean(R.string.key_use_uam, false)); mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable); + mProfile.put("SMBInterval", SP.getInt("key_smbinterval", SMBDefaults.SMBInterval)); mProfile.put("enableSMB_with_COB", SP.getBoolean(R.string.key_enableSMB_with_COB, false)); mProfile.put("enableSMB_with_temptarget", SP.getBoolean(R.string.key_enableSMB_with_temptarget, false)); mProfile.put("allowSMB_with_high_temptarget", SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java index 0ce8d2bb94..b203add063 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java @@ -55,6 +55,7 @@ public class SMBDefaults { // *** WARNING *** DO NOT USE enableSMB_always or enableSMB_after_carbs with xDrip+, Libre, or similar //public final static boolean enableSMB_after_carbs = false; // enable supermicrobolus for 6h after carbs, even with 0 COB //public final static boolean allowSMB_with_high_temptarget = false; // allow supermicrobolus (if otherwise enabled) even with high temp targets + public final static int SMBInterval = 3; // minimum interval between SMBs, in minutes. (limited between 1 and 10 min) public final static int maxSMBBasalMinutes = 30; // maximum minutes of basal that can be delivered as a single SMB with uncovered COB // curve:"rapid-acting" // Supported curves: "bilinear", "rapid-acting" (Novolog, Novorapid, Humalog, Apidra) and "ultra-rapid" (Fiasp) // useCustomPeakTime:false // allows changing insulinPeakTime diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ae4e572392..b465213583 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -800,6 +800,8 @@ Poctech upload settings Show detailed delta Show delta with one more decimal place + key_smbinterval + How frequently SMBs will be given in min 45 60 75 90 105 120 Max minutes of basal to limit SMB to Unsupported pump firmware diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index e23a364cb8..1b22e4322b 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -65,6 +65,19 @@ android:summary="@string/enablesmbaftercarbs_summary" android:title="@string/enablesmbaftercarbs" /> + + - \ No newline at end of file + From 7a95adca299568ccf798293908a1ca7cf7a5a022 Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Sat, 27 Oct 2018 12:33:32 +1300 Subject: [PATCH 009/316] Find Bolus incrument on pump, make sure the pump can support the minSMB bolus setting --- .../plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index ffa1954bad..e307156223 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -25,6 +25,7 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.ScriptReader; @@ -215,7 +216,8 @@ public class DetermineBasalAdapterSMBJS { ) throws JSONException { String units = profile.getUnits(); - + Double bolusincrument = SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment); + Double pumpbolusstep = MainApp.getConfigBuilder().getActivePump().getPumpDescription().bolusStep; mProfile = new JSONObject(); mProfile.put("max_iob", maxIob); @@ -256,7 +258,11 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); - mProfile.put("bolus_increment", SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment)); + if (bolusincrument < pumpbolusstep){ + //the bolus incrument is less than what the pump can support (by pump settings or pump restriction), set to value supported by the pump + bolusincrument = pumpbolusstep; + } + mProfile.put("bolus_increment", bolusincrument); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); From f24318c105812b54f213759dbae9e9a59db8b877 Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Thu, 1 Nov 2018 20:05:14 +1300 Subject: [PATCH 010/316] use diff plugin --- .../plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index e307156223..e8c7bc62cc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -27,6 +27,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; @@ -217,7 +218,7 @@ public class DetermineBasalAdapterSMBJS { String units = profile.getUnits(); Double bolusincrument = SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment); - Double pumpbolusstep = MainApp.getConfigBuilder().getActivePump().getPumpDescription().bolusStep; + Double pumpbolusstep = ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().bolusStep; mProfile = new JSONObject(); mProfile.put("max_iob", maxIob); From 0f3d9327475f4d1519daf8856d3e47a6ad9ac1df Mon Sep 17 00:00:00 2001 From: Tim Gunn Date: Thu, 1 Nov 2018 20:16:01 +1300 Subject: [PATCH 011/316] correct var spelling --- .../plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java index e8c7bc62cc..477a8dba71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java @@ -217,7 +217,7 @@ public class DetermineBasalAdapterSMBJS { ) throws JSONException { String units = profile.getUnits(); - Double bolusincrument = SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment); + Double bolusincrement = SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment); Double pumpbolusstep = ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().bolusStep; mProfile = new JSONObject(); @@ -259,11 +259,11 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); - if (bolusincrument < pumpbolusstep){ + if (bolusincrement < pumpbolusstep){ //the bolus incrument is less than what the pump can support (by pump settings or pump restriction), set to value supported by the pump - bolusincrument = pumpbolusstep; + bolusincrement = pumpbolusstep; } - mProfile.put("bolus_increment", bolusincrument); + mProfile.put("bolus_increment", bolusincrement); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("current_basal", basalrate); From 354071348ceb590f9f0ca15c54603d0ce8eff545 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 10 Aug 2019 20:16:30 +1200 Subject: [PATCH 012/316] prelim commit --- .../main/assets/OpenAPSSMB/determine-basal.js | 335 +++++++++--------- .../DetermineBasalAdapterSMBJS.java | 13 +- 2 files changed, 178 insertions(+), 170 deletions(-) diff --git a/app/src/main/assets/OpenAPSSMB/determine-basal.js b/app/src/main/assets/OpenAPSSMB/determine-basal.js index 9839f6bb1d..4d9ed4122c 100644 --- a/app/src/main/assets/OpenAPSSMB/determine-basal.js +++ b/app/src/main/assets/OpenAPSSMB/determine-basal.js @@ -31,14 +31,13 @@ function calculate_expected_delta(target_bg, eventual_bg, bgi) { // (hours * mins_per_hour) / 5 = how many 5 minute periods in 2h = 24 var five_min_blocks = (2 * 60) / 5; var target_delta = target_bg - eventual_bg; - var expectedDelta = round(bgi + (target_delta / five_min_blocks), 1); - return expectedDelta; + return /* expectedDelta */ round(bgi + (target_delta / five_min_blocks), 1); } function convert_bg(value, profile) { - if (profile.out_units == "mmol/L") + if (profile.out_units === "mmol/L") { return round(value / 18, 1).toFixed(1); } @@ -48,10 +47,13 @@ function convert_bg(value, profile) } } -var determine_basal = function determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, microBolusAllowed, reservoir_data) { +var determine_basal = function determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, microBolusAllowed, reservoir_data, currentTime) { var rT = {}; //short for requestedTemp var deliverAt = new Date(); + if (currentTime) { + deliverAt = currentTime; + } if (typeof profile === 'undefined' || typeof profile.current_basal === 'undefined') { rT.error ='Error: could not get current basal rate'; @@ -61,26 +63,39 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var basal = profile_current_basal; var systemTime = new Date(); + if (currentTime) { + systemTime = currentTime; + } var bgTime = new Date(glucose_status.date); var minAgo = round( (systemTime - bgTime) / 60 / 1000 ,1); var bg = glucose_status.glucose; - if (bg < 39) { //Dexcom is in ??? mode or calibrating - rT.reason = "CGM is calibrating or in ??? state"; + var noise = glucose_status.noise; + // 38 is an xDrip error state that usually indicates sensor failure + // all other BG values between 11 and 37 mg/dL reflect non-error-code BG values, so we should zero temp for those + if (bg <= 10 || bg === 38 || noise >= 3) { //Dexcom is in ??? mode or calibrating, or xDrip reports high noise + rT.reason = "CGM is calibrating, in ??? state, or noise is high"; } if (minAgo > 12 || minAgo < -5) { // Dexcom data is too old, or way in the future rT.reason = "If current system time "+systemTime+" is correct, then BG data is too old. The last BG data was read "+minAgo+"m ago at "+bgTime; + // if BG is too old/noisy, or is changing less than 1 mg/dL/5m for 45m, cancel any high temps and shorten any long zero temps + } else if ( bg > 60 && glucose_status == 0 && glucose_status.short_avgdelta > -1 && glucose_status.short_avgdelta < 1 && glucose_status.long_avgdelta > -1 && glucose_status.long_avgdelta < 1 ) { + if ( glucose_status.last_cal && glucose_status.last_cal < 3 ) { + rT.reason = "CGM was just calibrated"; + } else { + rT.reason = "Error: CGM data is unchanged for the past ~45m"; + } } - if (bg < 39 || minAgo > 12 || minAgo < -5) { - if (currenttemp.rate >= basal) { // high temp is running - rT.reason += ". Canceling high temp basal of "+currenttemp.rate; + if (bg <= 10 || bg === 38 || noise >= 3 || minAgo > 12 || minAgo < -5 || ( bg > 60 && glucose_status == 0 && glucose_status.short_avgdelta > -1 && glucose_status.short_avgdelta < 1 && glucose_status.long_avgdelta > -1 && glucose_status.long_avgdelta < 1 ) ) { + if (currenttemp.rate > basal) { // high temp is running + rT.reason += ". Replacing high temp basal of "+currenttemp.rate+" with neutral temp of "+basal; rT.deliverAt = deliverAt; rT.temp = 'absolute'; - rT.duration = 0; - rT.rate = 0; + rT.duration = 30; + rT.rate = basal; return rT; //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); - } else if ( currenttemp.rate == 0 && currenttemp.duration > 30 ) { //shorten long zero temps to 30m + } else if ( currenttemp.rate === 0 && currenttemp.duration > 30 ) { //shorten long zero temps to 30m rT.reason += ". Shortening " + currenttemp.duration + "m long zero temp to 30m. "; rT.deliverAt = deliverAt; rT.temp = 'absolute'; @@ -119,10 +134,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ if ( profile.half_basal_exercise_target ) { var halfBasalTarget = profile.half_basal_exercise_target; } else { - var halfBasalTarget = 160; // when temptarget is 160 mg/dL, run 50% basal (120 = 75%; 140 = 60%) + halfBasalTarget = 160; // when temptarget is 160 mg/dL, run 50% basal (120 = 75%; 140 = 60%) // 80 mg/dL with low_temptarget_lowers_sensitivity would give 1.5x basal, but is limited to autosens_max (1.2x by default) } - if ( high_temptarget_raises_sensitivity && profile.temptargetSet && target_bg > normalTarget + 10 + if ( high_temptarget_raises_sensitivity && profile.temptargetSet && target_bg > normalTarget || profile.low_temptarget_lowers_sensitivity && profile.temptargetSet && target_bg < normalTarget ) { // w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44 // e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6 @@ -132,36 +147,36 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // limit sensitivityRatio to profile.autosens_max (1.2x by default) sensitivityRatio = Math.min(sensitivityRatio, profile.autosens_max); sensitivityRatio = round(sensitivityRatio,2); - console.error("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+target_bg+"; "); - } else if (typeof autosens_data !== 'undefined' ) { + process.stderr.write("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+target_bg+"; "); + } else if (typeof autosens_data !== 'undefined' && autosens_data) { sensitivityRatio = autosens_data.ratio; - console.error("Autosens ratio: "+sensitivityRatio+"; "); + process.stderr.write("Autosens ratio: "+sensitivityRatio+"; "); } if (sensitivityRatio) { basal = profile.current_basal * sensitivityRatio; basal = round_basal(basal, profile); - if (basal != profile_current_basal) { - console.error("Adjusting basal from "+profile_current_basal+" to "+basal+"; "); + if (basal !== profile_current_basal) { + process.stderr.write("Adjusting basal from "+profile_current_basal+" to "+basal+"; "); } else { - console.error("Basal unchanged: "+basal+"; "); + process.stderr.write("Basal unchanged: "+basal+"; "); } } // adjust min, max, and target BG for sensitivity, such that 50% increase in ISF raises target from 100 to 120 if (profile.temptargetSet) { - //console.error("Temp Target set, not adjusting with autosens; "); - } else if (typeof autosens_data !== 'undefined' ) { + //process.stderr.write("Temp Target set, not adjusting with autosens; "); + } else if (typeof autosens_data !== 'undefined' && autosens_data) { if ( profile.sensitivity_raises_target && autosens_data.ratio < 1 || profile.resistance_lowers_target && autosens_data.ratio > 1 ) { // with a target of 100, default 0.7-1.2 autosens min/max range would allow a 93-117 target range min_bg = round((min_bg - 60) / autosens_data.ratio) + 60; max_bg = round((max_bg - 60) / autosens_data.ratio) + 60; - new_target_bg = round((target_bg - 60) / autosens_data.ratio) + 60; + var new_target_bg = round((target_bg - 60) / autosens_data.ratio) + 60; // don't allow target_bg below 80 new_target_bg = Math.max(80, new_target_bg); - if (target_bg == new_target_bg) { - console.error("target_bg unchanged: "+new_target_bg+"; "); + if (target_bg === new_target_bg) { + process.stderr.write("target_bg unchanged: "+new_target_bg+"; "); } else { - console.error("target_bg from "+target_bg+" to "+new_target_bg+"; "); + process.stderr.write("target_bg from "+target_bg+" to "+new_target_bg+"; "); } target_bg = new_target_bg; } @@ -197,34 +212,33 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var profile_sens = round(profile.sens,1) var sens = profile.sens; - if (typeof autosens_data !== 'undefined' ) { + if (typeof autosens_data !== 'undefined' && autosens_data) { sens = profile.sens / sensitivityRatio; sens = round(sens, 1); - if (sens != profile_sens) { - console.error("ISF from "+profile_sens+" to "+sens); + if (sens !== profile_sens) { + process.stderr.write("ISF from "+profile_sens+" to "+sens); } else { - console.error("ISF unchanged: "+sens); + process.stderr.write("ISF unchanged: "+sens); } - //console.error(" (autosens ratio "+sensitivityRatio+")"); + //process.stderr.write(" (autosens ratio "+sensitivityRatio+")"); } console.error("; CR:",profile.carb_ratio); // compare currenttemp to iob_data.lastTemp and cancel temp if they don't match var lastTempAge; if (typeof iob_data.lastTemp !== 'undefined' ) { - lastTempAge = round(( new Date().getTime() - iob_data.lastTemp.date ) / 60000); // in minutes - // } ---- added to not produce errors + lastTempAge = round(( new Date(systemTime).getTime() - iob_data.lastTemp.date ) / 60000); // in minutes } else { lastTempAge = 0; } //console.error("currenttemp:",currenttemp,"lastTemp:",JSON.stringify(iob_data.lastTemp),"lastTempAge:",lastTempAge,"m"); - tempModulus = (lastTempAge + currenttemp.duration) % 30; + var tempModulus = (lastTempAge + currenttemp.duration) % 30; console.error("currenttemp:",currenttemp,"lastTempAge:",lastTempAge,"m","tempModulus:",tempModulus,"m"); rT.temp = 'absolute'; rT.deliverAt = deliverAt; - if ( microBolusAllowed && currenttemp && iob_data.lastTemp && currenttemp.rate != iob_data.lastTemp.rate ) { - rT.reason = "Warning: currenttemp rate "+currenttemp.rate+" != lastTemp rate "+iob_data.lastTemp.rate+" from pumphistory; setting neutral temp of "+basal+"."; - return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + if ( microBolusAllowed && currenttemp && iob_data.lastTemp && currenttemp.rate !== iob_data.lastTemp.rate && lastTempAge > 10 && currenttemp.duration ) { + rT.reason = "Warning: currenttemp rate "+currenttemp.rate+" != lastTemp rate "+iob_data.lastTemp.rate+" from pumphistory; canceling temp"; + return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp); } if ( currenttemp && iob_data.lastTemp && currenttemp.duration > 0 ) { // TODO: fix this (lastTemp.duration is how long it has run; currenttemp.duration is time left @@ -234,10 +248,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ //} //console.error(lastTempAge, round(iob_data.lastTemp.duration,1), round(lastTempAge - iob_data.lastTemp.duration,1)); var lastTempEnded = lastTempAge - iob_data.lastTemp.duration - if ( lastTempEnded > 5 ) { - rT.reason = "Warning: currenttemp running but lastTemp from pumphistory ended "+lastTempEnded+"m ago; setting neutral temp of "+basal+"."; + if ( lastTempEnded > 5 && lastTempAge > 10 ) { + rT.reason = "Warning: currenttemp running but lastTemp from pumphistory ended "+lastTempEnded+"m ago; canceling temp"; //console.error(currenttemp, round(iob_data.lastTemp,1), round(lastTempAge,1)); - return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); + return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp); } // TODO: figure out a way to do this check that doesn't fail across basal schedule boundaries //if ( tempModulus < 25 && tempModulus > 5 ) { @@ -264,37 +278,44 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ if (iob_data.iob > 0) { var naive_eventualBG = round( bg - (iob_data.iob * sens) ); } else { // if IOB is negative, be more conservative and use the lower of sens, profile.sens - var naive_eventualBG = round( bg - (iob_data.iob * Math.min(sens, profile.sens) ) ); + naive_eventualBG = round( bg - (iob_data.iob * Math.min(sens, profile.sens) ) ); } // and adjust it for the deviation above var eventualBG = naive_eventualBG + deviation; - // calculate what portion of that is due to bolussnooze - //var bolusContrib = iob_data.bolussnooze * sens; - // and add it back in to get snoozeBG, plus another 50% to avoid low-temping at mealtime - //var naive_snoozeBG = round( naive_eventualBG + 1.5 * bolusContrib ); - // adjust that for deviation like we did eventualBG - //var snoozeBG = naive_snoozeBG + deviation; - // adjust target BG range if needed to safely bring down high BG faster without causing lows - if ( bg > max_bg && profile.adv_target_adjustments && ! profile.temptargetSet ) { + // raise target for noisy / raw CGM data + if (glucose_status.noise >= 2) { + // increase target at least 10% (default 30%) for raw / noisy data + var noisyCGMTargetMultiplier = Math.max( 1.1, profile.noisyCGMTargetMultiplier ); + // don't allow maxRaw above 250 + var maxRaw = Math.min( 250, profile.maxRaw ); + var adjustedMinBG = round(Math.min(200, min_bg * noisyCGMTargetMultiplier )); + var adjustedTargetBG = round(Math.min(200, target_bg * noisyCGMTargetMultiplier )); + var adjustedMaxBG = round(Math.min(200, max_bg * noisyCGMTargetMultiplier )); + process.stderr.write("Raising target_bg for noisy / raw CGM data, from "+target_bg+" to "+adjustedTargetBG+"; "); + min_bg = adjustedMinBG; + target_bg = adjustedTargetBG; + max_bg = adjustedMaxBG; + // adjust target BG range if configured to bring down high BG faster + } else if ( bg > max_bg && profile.adv_target_adjustments && ! profile.temptargetSet ) { // with target=100, as BG rises from 100 to 160, adjustedTarget drops from 100 to 80 - var adjustedMinBG = round(Math.max(80, min_bg - (bg - min_bg)/3 ),0); - var adjustedTargetBG =round( Math.max(80, target_bg - (bg - target_bg)/3 ),0); - var adjustedMaxBG = round(Math.max(80, max_bg - (bg - max_bg)/3 ),0); + adjustedMinBG = round(Math.max(80, min_bg - (bg - min_bg)/3 ),0); + adjustedTargetBG =round( Math.max(80, target_bg - (bg - target_bg)/3 ),0); + adjustedMaxBG = round(Math.max(80, max_bg - (bg - max_bg)/3 ),0); // if eventualBG, naive_eventualBG, and target_bg aren't all above adjustedMinBG, don’t use it //console.error("naive_eventualBG:",naive_eventualBG+", eventualBG:",eventualBG); if (eventualBG > adjustedMinBG && naive_eventualBG > adjustedMinBG && min_bg > adjustedMinBG) { - console.error("Adjusting targets for high BG: min_bg from "+min_bg+" to "+adjustedMinBG+"; "); + process.stderr.write("Adjusting targets for high BG: min_bg from "+min_bg+" to "+adjustedMinBG+"; "); min_bg = adjustedMinBG; } else { - console.error("min_bg unchanged: "+min_bg+"; "); + process.stderr.write("min_bg unchanged: "+min_bg+"; "); } // if eventualBG, naive_eventualBG, and target_bg aren't all above adjustedTargetBG, don’t use it if (eventualBG > adjustedTargetBG && naive_eventualBG > adjustedTargetBG && target_bg > adjustedTargetBG) { - console.error("target_bg from "+target_bg+" to "+adjustedTargetBG+"; "); + process.stderr.write("target_bg from "+target_bg+" to "+adjustedTargetBG+"; "); target_bg = adjustedTargetBG; } else { - console.error("target_bg unchanged: "+target_bg+"; "); + process.stderr.write("target_bg unchanged: "+target_bg+"; "); } // if eventualBG, naive_eventualBG, and max_bg aren't all above adjustedMaxBG, don’t use it if (eventualBG > adjustedMaxBG && naive_eventualBG > adjustedMaxBG && max_bg > adjustedMaxBG) { @@ -321,7 +342,6 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ , 'bg': bg , 'tick': tick , 'eventualBG': eventualBG - //, 'snoozeBG': snoozeBG , 'insulinReq': 0 , 'reservoir' : reservoir_data // The expected reservoir volume at which to deliver the microbolus (the reservoir volume from right before the last pumphistory run) , 'deliverAt' : deliverAt // The time at which the microbolus should be delivered @@ -353,7 +373,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // enable SMB/UAM (if enabled in preferences) while we have COB } else if (profile.enableSMB_with_COB === true && meal_data.mealCOB) { if (meal_data.bwCarbs) { - if (profile.A52_risk_enable) { + if (profile.A52_risk_enable === true) { console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard") enableSMB=true; } else { @@ -365,9 +385,9 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } // enable SMB/UAM (if enabled in preferences) for a full 6 hours after any carb entry // (6 hours is defined in carbWindow in lib/meal/total.js) - } else if (profile.enableSMB_after_carbs === true && meal_data.carbs ) { + } else if ((profile.enableSMB_after_carbs === true || profile.enableSMB_with_carbs === true) && meal_data.carbs ) { if (meal_data.bwCarbs) { - if (profile.A52_risk_enable) { + if (profile.A52_risk_enable === true) { console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard") enableSMB=true; } else { @@ -380,7 +400,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // enable SMB/UAM (if enabled in preferences) if a low temptarget is set } else if (profile.enableSMB_with_temptarget === true && (profile.temptargetSet && target_bg < 100)) { if (meal_data.bwFound) { - if (profile.A52_risk_enable) { + if (profile.A52_risk_enable === true) { console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard") enableSMB=true; } else { @@ -404,7 +424,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ enableSMB=true; } } else { - console.error("SMB disabled (no enableSMB preferences active)"); + console.error("SMB disabled for this run (no selected enableSMB criteria met)"); } // enable UAM (if enabled in preferences) var enableUAM=(profile.enableUAM); @@ -417,43 +437,48 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // calculate current carb absorption rate, and how long to absorb all carbs // CI = current carb impact on BG in mg/dL/5m ci = round((minDelta - bgi),1); - uci = round((minDelta - bgi),1); + var uci = round((minDelta - bgi),1); // ISF (mg/dL/U) / CR (g/U) = CSF (mg/dL/g) - if (profile.temptargetSet) { + + // TODO: remove commented-out code for old behavior + //if (profile.temptargetSet) { // if temptargetSet, use unadjusted profile.sens to allow activity mode sensitivityRatio to adjust CR - var csf = profile.sens / profile.carb_ratio; - } else { + //var csf = profile.sens / profile.carb_ratio; + //} else { // otherwise, use autosens-adjusted sens to counteract autosens meal insulin dosing adjustments // so that autotuned CR is still in effect even when basals and ISF are being adjusted by autosens - var csf = sens / profile.carb_ratio; - } + //var csf = sens / profile.carb_ratio; + //} + // use autosens-adjusted sens to counteract autosens meal insulin dosing adjustments so that + // autotuned CR is still in effect even when basals and ISF are being adjusted by TT or autosens + // this avoids overdosing insulin for large meals when low temp targets are active + csf = sens / profile.carb_ratio; + console.error("profile.sens:",profile.sens,"sens:",sens,"CSF:",csf); + var maxCarbAbsorptionRate = 30; // g/h; maximum rate to assume carbs will absorb if no CI observed // limit Carb Impact to maxCarbAbsorptionRate * csf in mg/dL per 5m - maxCI = round(maxCarbAbsorptionRate*csf*5/60,1) + var maxCI = round(maxCarbAbsorptionRate*csf*5/60,1) if (ci > maxCI) { console.error("Limiting carb impact from",ci,"to",maxCI,"mg/dL/5m (",maxCarbAbsorptionRate,"g/h )"); ci = maxCI; } - // set meal_carbimpact high enough to absorb all meal carbs over 6 hours - // total_impact (mg/dL) = CSF (mg/dL/g) * carbs (g) - //console.error(csf * meal_data.carbs); - // meal_carbimpact (mg/dL/5m) = CSF (mg/dL/g) * carbs (g) / 6 (h) * (1h/60m) * 5 (m/5m) * 2 (for linear decay) - //var meal_carbimpact = round((csf * meal_data.carbs / 6 / 60 * 5 * 2),1) - var remainingCATimeMin = 3; // h; before carb absorption starts - // adjust remainingCATime (instead of CR) for autosens - remainingCATimeMin = remainingCATimeMin / sensitivityRatio; + var remainingCATimeMin = 3; // h; duration of expected not-yet-observed carb absorption + // adjust remainingCATime (instead of CR) for autosens if sensitivityRatio defined + if (sensitivityRatio){ + remainingCATimeMin = remainingCATimeMin / sensitivityRatio; + } // 20 g/h means that anything <= 60g will get a remainingCATimeMin, 80g will get 4h, and 120g 6h // when actual absorption ramps up it will take over from remainingCATime var assumedCarbAbsorptionRate = 20; // g/h; maximum rate to assume carbs will absorb if no CI observed - var remainingCATime = remainingCATimeMin; // added by mike https://github.com/openaps/oref0/issues/884 + var remainingCATime = remainingCATimeMin; if (meal_data.carbs) { // if carbs * assumedCarbAbsorptionRate > remainingCATimeMin, raise it // so <= 90g is assumed to take 3h, and 120g=4h remainingCATimeMin = Math.max(remainingCATimeMin, meal_data.mealCOB/assumedCarbAbsorptionRate); - var lastCarbAge = round(( new Date().getTime() - meal_data.lastCarbTime ) / 60000); + var lastCarbAge = round(( new Date(systemTime).getTime() - meal_data.lastCarbTime ) / 60000); //console.error(meal_data.lastCarbTime, lastCarbAge); - fractionCOBAbsorbed = ( meal_data.carbs - meal_data.mealCOB ) / meal_data.carbs; + var fractionCOBAbsorbed = ( meal_data.carbs - meal_data.mealCOB ) / meal_data.carbs; remainingCATime = remainingCATimeMin + 1.5 * lastCarbAge/60; remainingCATime = round(remainingCATime,1); //console.error(fractionCOBAbsorbed, remainingCATimeAdjustment, remainingCATime) @@ -478,7 +503,6 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // remainingCIpeak (mg/dL/5m) = remainingCarbs (g) * CSF (mg/dL/g) * 5 (m/5m) * 1h/60m / (remainingCATime/2) (h) var remainingCIpeak = remainingCarbs * csf * 5 / 60 / (remainingCATime/2); //console.error(profile.min_5m_carbimpact,ci,totalCI,totalCA,remainingCarbs,remainingCI,remainingCATime); - //if (meal_data.mealCOB * 3 > meal_data.carbs) { } // calculate peak deviation in last hour, and slope from that to current deviation var slopeFromMaxDeviation = round(meal_data.slopeFromMaxDeviation,2); @@ -488,17 +512,17 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var slopeFromDeviations = Math.min(slopeFromMaxDeviation,-slopeFromMinDeviation/3); //console.error(slopeFromMaxDeviation); - aci = 10; + var aci = 10; //5m data points = g * (1U/10g) * (40mg/dL/1U) / (mg/dL/5m) // duration (in 5m data points) = COB (g) * CSF (mg/dL/g) / ci (mg/dL/5m) // limit cid to remainingCATime hours: the reset goes to remainingCI - if (ci == 0) { + if (ci === 0) { // avoid divide by zero cid = 0; } else { cid = Math.min(remainingCATime*60/5/2,Math.max(0, meal_data.mealCOB * csf / ci )); } - acid = Math.max(0, meal_data.mealCOB * csf / aci ); + var acid = Math.max(0, meal_data.mealCOB * csf / aci ); // duration (hours) = duration (5m) * 5 / 60 * 2 (to account for linear decay) console.error("Carb Impact:",ci,"mg/dL per 5m; CI Duration:",round(cid*5/60*2,1),"hours; remaining CI (~2h peak):",round(remainingCIpeak,1),"mg/dL per 5m"); //console.error("Accel. Carb Impact:",aci,"mg/dL per 5m; ACI Duration:",round(acid*5/60*2,1),"hours"); @@ -529,18 +553,18 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ try { iobArray.forEach(function(iobTick) { //console.error(iobTick); - predBGI = round(( -iobTick.activity * sens * 5 ), 2); - predZTBGI = round(( -iobTick.iobWithZeroTemp.activity * sens * 5 ), 2); + var predBGI = round(( -iobTick.activity * sens * 5 ), 2); + var predZTBGI = round(( -iobTick.iobWithZeroTemp.activity * sens * 5 ), 2); // for IOBpredBGs, predicted deviation impact drops linearly from current deviation down to zero // over 60 minutes (data points every 5m) - predDev = ci * ( 1 - Math.min(1,IOBpredBGs.length/(60/5)) ); + var predDev = ci * ( 1 - Math.min(1,IOBpredBGs.length/(60/5)) ); IOBpredBG = IOBpredBGs[IOBpredBGs.length-1] + predBGI + predDev; // calculate predBGs with long zero temp without deviations - ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + predZTBGI; + var ZTpredBG = ZTpredBGs[ZTpredBGs.length-1] + predZTBGI; // for COBpredBGs, predicted carb impact drops linearly from current carb impact down to zero // eventually accounting for all carbs (if they can be absorbed over DIA) - predCI = Math.max(0, Math.max(0,ci) * ( 1 - COBpredBGs.length/Math.max(cid*2,1) ) ); - predACI = Math.max(0, Math.max(0,aci) * ( 1 - COBpredBGs.length/Math.max(acid*2,1) ) ); + var predCI = Math.max(0, Math.max(0,ci) * ( 1 - COBpredBGs.length/Math.max(cid*2,1) ) ); + var predACI = Math.max(0, Math.max(0,aci) * ( 1 - COBpredBGs.length/Math.max(acid*2,1) ) ); // if any carbs aren't absorbed after remainingCATime hours, assume they'll absorb in a /\ shaped // bilinear curve peaking at remainingCIpeak at remainingCATime/2 hours (remainingCATime/2*12 * 5m) // and ending at remainingCATime h (remainingCATime*12 * 5m intervals) @@ -549,18 +573,18 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ remainingCItotal += predCI+remainingCI; remainingCIs.push(round(remainingCI,0)); predCIs.push(round(predCI,0)); - //console.error(round(predCI,1)+"+"+round(remainingCI,1)+" "); + //process.stderr.write(round(predCI,1)+"+"+round(remainingCI,1)+" "); COBpredBG = COBpredBGs[COBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predCI + remainingCI; - aCOBpredBG = aCOBpredBGs[aCOBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predACI; + var aCOBpredBG = aCOBpredBGs[aCOBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predACI; // for UAMpredBGs, predicted carb impact drops at slopeFromDeviations // calculate predicted CI from UAM based on slopeFromDeviations - predUCIslope = Math.max(0, uci + ( UAMpredBGs.length*slopeFromDeviations ) ); + var predUCIslope = Math.max(0, uci + ( UAMpredBGs.length*slopeFromDeviations ) ); // if slopeFromDeviations is too flat, predicted deviation impact drops linearly from // current deviation down to zero over 3h (data points every 5m) - predUCImax = Math.max(0, uci * ( 1 - UAMpredBGs.length/Math.max(3*60/5,1) ) ); + var predUCImax = Math.max(0, uci * ( 1 - UAMpredBGs.length/Math.max(3*60/5,1) ) ); //console.error(predUCIslope, predUCImax); // predicted CI from UAM is the lesser of CI based on deviationSlope or DIA - predUCI = Math.min(predUCIslope, predUCImax); + var predUCI = Math.min(predUCIslope, predUCImax); if(predUCI>0) { //console.error(UAMpredBGs.length,slopeFromDeviations, predUCI); UAMduration=round((UAMpredBGs.length+1)*5/60,1); @@ -599,19 +623,18 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // set eventualBG to include effect of carbs //console.error("PredBGs:",JSON.stringify(predBGs)); } catch (e) { - console.error("Problem with iobArray. Optional feature Advanced Meal Assist disabled:",e); + console.error("Problem with iobArray. Optional feature Advanced Meal Assist disabled"); } if (meal_data.mealCOB) { console.error("predCIs (mg/dL/5m):",predCIs.join(" ")); console.error("remainingCIs: ",remainingCIs.join(" ")); } - //,"totalCA:",round(totalCA,2),"remainingCItotal/csf+totalCA:",round(remainingCItotal/csf+totalCA,2)); rT.predBGs = {}; IOBpredBGs.forEach(function(p, i, theArray) { theArray[i] = round(Math.min(401,Math.max(39,p))); }); for (var i=IOBpredBGs.length-1; i > 12; i--) { - if (IOBpredBGs[i-1] != IOBpredBGs[i]) { break; } + if (IOBpredBGs[i-1] !== IOBpredBGs[i]) { break; } else { IOBpredBGs.pop(); } } rT.predBGs.IOB = IOBpredBGs; @@ -619,10 +642,9 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ ZTpredBGs.forEach(function(p, i, theArray) { theArray[i] = round(Math.min(401,Math.max(39,p))); }); - for (var i=ZTpredBGs.length-1; i > 6; i--) { - //if (ZTpredBGs[i-1] != ZTpredBGs[i]) { break; } + for (i=ZTpredBGs.length-1; i > 6; i--) { // stop displaying ZTpredBGs once they're rising and above target - if (ZTpredBGs[i-1] >= ZTpredBGs[i] || ZTpredBGs[i] < target_bg) { break; } + if (ZTpredBGs[i-1] >= ZTpredBGs[i] || ZTpredBGs[i] <= target_bg) { break; } else { ZTpredBGs.pop(); } } rT.predBGs.ZT = ZTpredBGs; @@ -631,19 +653,17 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ aCOBpredBGs.forEach(function(p, i, theArray) { theArray[i] = round(Math.min(401,Math.max(39,p))); }); - for (var i=aCOBpredBGs.length-1; i > 12; i--) { - if (aCOBpredBGs[i-1] != aCOBpredBGs[i]) { break; } + for (i=aCOBpredBGs.length-1; i > 12; i--) { + if (aCOBpredBGs[i-1] !== aCOBpredBGs[i]) { break; } else { aCOBpredBGs.pop(); } } - // disable for now. may want to add a preference to re-enable - //rT.predBGs.aCOB = aCOBpredBGs; } if (meal_data.mealCOB > 0 && ( ci > 0 || remainingCIpeak > 0 )) { COBpredBGs.forEach(function(p, i, theArray) { theArray[i] = round(Math.min(401,Math.max(39,p))); }); - for (var i=COBpredBGs.length-1; i > 12; i--) { - if (COBpredBGs[i-1] != COBpredBGs[i]) { break; } + for (i=COBpredBGs.length-1; i > 12; i--) { + if (COBpredBGs[i-1] !== COBpredBGs[i]) { break; } else { COBpredBGs.pop(); } } rT.predBGs.COB = COBpredBGs; @@ -655,8 +675,8 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ UAMpredBGs.forEach(function(p, i, theArray) { theArray[i] = round(Math.min(401,Math.max(39,p))); }); - for (var i=UAMpredBGs.length-1; i > 12; i--) { - if (UAMpredBGs[i-1] != UAMpredBGs[i]) { break; } + for (i=UAMpredBGs.length-1; i > 12; i--) { + if (UAMpredBGs[i-1] !== UAMpredBGs[i]) { break; } else { UAMpredBGs.pop(); } } rT.predBGs.UAM = UAMpredBGs; @@ -666,7 +686,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } } - // set eventualBG and snoozeBG based on COB or UAM predBGs + // set eventualBG based on COB or UAM predBGs rT.eventualBG = eventualBG; } @@ -733,14 +753,6 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ //console.error("minUAMPredBG:",minUAMPredBG,"minZTGuardBG:",minZTGuardBG,"minZTUAMPredBG:",minZTUAMPredBG); // if any carbs have been entered recently if (meal_data.carbs) { - // average the minIOBPredBG and minUAMPredBG if available - /* - if ( minUAMPredBG < 999 ) { - avgMinPredBG = round( (minIOBPredBG+minUAMPredBG)/2 ); - } else { - avgMinPredBG = minIOBPredBG; - } - */ // if UAM is disabled, use max of minIOBPredBG, minCOBPredBG if ( ! enableUAM && minCOBPredBG < 999 ) { @@ -748,30 +760,27 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // if we have COB, use minCOBPredBG, or blendedMinPredBG if it's higher } else if ( minCOBPredBG < 999 ) { // calculate blendedMinPredBG based on how many carbs remain as COB - //blendedMinPredBG = fractionCarbsLeft*minCOBPredBG + (1-fractionCarbsLeft)*minUAMPredBG; - blendedMinPredBG = fractionCarbsLeft*minCOBPredBG + (1-fractionCarbsLeft)*minZTUAMPredBG; + var blendedMinPredBG = fractionCarbsLeft*minCOBPredBG + (1-fractionCarbsLeft)*minZTUAMPredBG; // if blendedMinPredBG > minCOBPredBG, use that instead minPredBG = round(Math.max(minIOBPredBG, minCOBPredBG, blendedMinPredBG)); // if carbs have been entered, but have expired, use minUAMPredBG } else { - //minPredBG = minUAMPredBG; minPredBG = minZTUAMPredBG; } // in pure UAM mode, use the higher of minIOBPredBG,minUAMPredBG } else if ( enableUAM ) { - //minPredBG = round(Math.max(minIOBPredBG,minUAMPredBG)); minPredBG = round(Math.max(minIOBPredBG,minZTUAMPredBG)); } // make sure minPredBG isn't higher than avgPredBG minPredBG = Math.min( minPredBG, avgPredBG ); - console.error("minPredBG: "+minPredBG+" minIOBPredBG: "+minIOBPredBG+" minZTGuardBG: "+minZTGuardBG); + process.stderr.write("minPredBG: "+minPredBG+" minIOBPredBG: "+minIOBPredBG+" minZTGuardBG: "+minZTGuardBG); if (minCOBPredBG < 999) { - console.error(" minCOBPredBG: "+minCOBPredBG); + process.stderr.write(" minCOBPredBG: "+minCOBPredBG); } if (minUAMPredBG < 999) { - console.error(" minUAMPredBG: "+minUAMPredBG); + process.stderr.write(" minUAMPredBG: "+minUAMPredBG); } console.error(" avgPredBG:",avgPredBG,"COB:",meal_data.mealCOB,"/",meal_data.carbs); // But if the COB line falls off a cliff, don't trust UAM too much: @@ -790,9 +799,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ rT.reason += ", UAMpredBG " + convert_bg(lastUAMpredBG, profile) } rT.reason += "; "; - //var bgUndershoot = threshold - Math.min(minGuardBG, Math.max( naive_eventualBG, eventualBG )); // use naive_eventualBG if above 40, but switch to minGuardBG if both eventualBGs hit floor of 39 - //var carbsReqBG = Math.max( naive_eventualBG, eventualBG ); var carbsReqBG = naive_eventualBG; if ( carbsReqBG < 40 ) { carbsReqBG = Math.min( minGuardBG, carbsReqBG ); @@ -802,14 +809,14 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var minutesAboveMinBG = 240; var minutesAboveThreshold = 240; if (meal_data.mealCOB > 0 && ( ci > 0 || remainingCIpeak > 0 )) { - for (var i=0; i= 55 ) { + rT.reason += "; Canceling temp at " + rT.deliverAt.getMinutes() + "m past the hour. "; + return tempBasalFunctions.setTempBasal(0, 0, profile, rT, currenttemp); + } + if (eventualBG < min_bg) { // if eventual BG is below target: rT.reason += "Eventual BG " + convert_bg(eventualBG, profile) + " < " + convert_bg(min_bg, profile); // if 5m or 30m avg BG is rising faster than expected delta @@ -904,9 +917,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } // calculate 30m low-temp required to get projected BG up to target - // use snoozeBG to more gradually ramp in any counteraction of the user's boluses // multiply by 2 to low-temp faster for increased hypo safety - //var insulinReq = 2 * Math.min(0, (snoozeBG - target_bg) / sens); var insulinReq = 2 * Math.min(0, (eventualBG - target_bg) / sens); insulinReq = round( insulinReq , 2); // calculate naiveInsulinReq based on naive_eventualBG @@ -914,7 +925,6 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ naiveInsulinReq = round( naiveInsulinReq , 2); if (minDelta < 0 && minDelta > expectedDelta) { // if we're barely falling, newinsulinReq should be barely negative - //rT.reason += ", Snooze BG " + convert_bg(snoozeBG, profile); var newinsulinReq = round(( insulinReq * (minDelta / expectedDelta) ), 2); //console.error("Increasing insulinReq from " + insulinReq + " to " + newinsulinReq); insulinReq = newinsulinReq; @@ -922,6 +932,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // rate required to deliver insulinReq less insulin over 30m: var rate = basal + (2 * insulinReq); rate = round_basal(rate, profile); + // if required temp < existing temp basal var insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60; // if current temp would deliver a lot (30% of basal) less than the required insulin, @@ -937,18 +948,17 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } else { // calculate a long enough zero temp to eventually correct back up to target if ( rate <=0 ) { - var bgUndershoot = target_bg - naive_eventualBG; - var worstCaseInsulinReq = bgUndershoot / sens; - var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); + bgUndershoot = target_bg - naive_eventualBG; + worstCaseInsulinReq = bgUndershoot / sens; + durationReq = round(60*worstCaseInsulinReq / profile.current_basal); if (durationReq < 0) { durationReq = 0; - // don't set an SMB zero temp longer than 60 minutess + // don't set a temp longer than 120 minutes } else { durationReq = round(durationReq/30)*30; - durationReq = Math.min(60,Math.max(0,durationReq)); + durationReq = Math.min(120,Math.max(0,durationReq)); } //console.error(durationReq); - //rT.reason += "insulinReq " + insulinReq + "; " if (durationReq > 0) { rT.reason += ", setting " + durationReq + "m zero temp. "; return tempBasalFunctions.setTempBasal(rate, durationReq, profile, rT, currenttemp); @@ -1011,15 +1021,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // insulinReq is the additional insulin required to get minPredBG down to target_bg //console.error(minPredBG,eventualBG); - //var insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2); - var insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2); - // when dropping, but not as fast as expected, reduce insulinReq proportionally - // to the what fraction of expectedDelta we're dropping at - //if (minDelta < 0 && minDelta > expectedDelta) { - //var newinsulinReq = round(( insulinReq * (1 - (minDelta / expectedDelta)) ), 2); - //console.error("Reducing insulinReq from " + insulinReq + " to " + newinsulinReq + " for minDelta " + minDelta + " vs. expectedDelta " + expectedDelta); - //insulinReq = newinsulinReq; - //} + insulinReq = round( (Math.min(minPredBG,eventualBG) - target_bg) / sens, 2); // if that would put us over max_iob, then reduce accordingly if (insulinReq > max_iob-iob_data.iob) { rT.reason += "max_iob " + max_iob + ", "; @@ -1027,21 +1029,21 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } // rate required to deliver insulinReq more insulin over 30m: - var rate = basal + (2 * insulinReq); + rate = basal + (2 * insulinReq); rate = round_basal(rate, profile); insulinReq = round(insulinReq,3); rT.insulinReq = insulinReq; //console.error(iob_data.lastBolusTime); // minutes since last bolus - var lastBolusAge = round(( new Date().getTime() - iob_data.lastBolusTime ) / 60000,1); + var lastBolusAge = round(( new Date(systemTime).getTime() - iob_data.lastBolusTime ) / 60000,1); //console.error(lastBolusAge); //console.error(profile.temptargetSet, target_bg, rT.COB); // only allow microboluses with COB or low temp targets, or within DIA hours of a bolus if (microBolusAllowed && enableSMB && bg > threshold) { // never bolus more than maxSMBBasalMinutes worth of basal - mealInsulinReq = round( meal_data.mealCOB / profile.carb_ratio ,3); - if (typeof profile.maxSMBBasalMinutes == 'undefined' ) { - maxBolus = round( profile.current_basal * 30 / 60 ,1); + var mealInsulinReq = round( meal_data.mealCOB / profile.carb_ratio ,3); + if (typeof profile.maxSMBBasalMinutes === 'undefined' ) { + var maxBolus = round( profile.current_basal * 30 / 60 ,1); console.error("profile.maxSMBBasalMinutes undefined: defaulting to 30m"); // if IOB covers more than COB, limit maxBolus to 30m of basal } else if ( iob_data.iob > mealInsulinReq && iob_data.iob > 0 ) { @@ -1059,11 +1061,11 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ } // bolus 1/2 the insulinReq, up to maxBolus, rounding down to nearest bolus increment var roundSMBTo = 1 / profile.bolus_increment; - microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*roundSMBTo)/roundSMBTo; + var microBolus = Math.floor(Math.min(insulinReq/2,maxBolus)*roundSMBTo)/roundSMBTo; // calculate a long enough zero temp to eventually correct back up to target var smbTarget = target_bg; - var worstCaseInsulinReq = (smbTarget - (naive_eventualBG + minIOBPredBG)/2 ) / sens; - var durationReq = round(60*worstCaseInsulinReq / profile.current_basal); + worstCaseInsulinReq = (smbTarget - (naive_eventualBG + minIOBPredBG)/2 ) / sens; + durationReq = round(60*worstCaseInsulinReq / profile.current_basal); // if insulinReq > 0 but not enough for a microBolus, don't set an SMB zero temp if (insulinReq > 0 && microBolus < profile.bolus_increment) { @@ -1073,10 +1075,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var smbLowTempReq = 0; if (durationReq <= 0) { durationReq = 0; - // don't set a temp longer than 120 minutes + // don't set an SMB zero temp longer than 60 minutes } else if (durationReq >= 30) { durationReq = round(durationReq/30)*30; - durationReq = Math.min(120,Math.max(0,durationReq)); + durationReq = Math.min(60,Math.max(0,durationReq)); } else { // if SMB durationReq is less than 30m, set a nonzero low temp smbLowTempReq = round( basal * durationReq/30 ,2); @@ -1118,11 +1120,6 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ return rT; } - // if insulinReq is negative, snoozeBG > target_bg, and lastCOBpredBG > target_bg, set a neutral temp - //if (insulinReq < 0 && snoozeBG > target_bg && lastCOBpredBG > target_bg) { - //rT.reason += "; SMB bolus snooze: setting current basal of " + basal + " as temp. "; - //return tempBasalFunctions.setTempBasal(basal, 30, profile, rT, currenttemp); - //} } var maxSafeBasal = tempBasalFunctions.getMaxSafeBasal(profile); @@ -1132,13 +1129,13 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ rate = round_basal(maxSafeBasal, profile); } - var insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60; + insulinScheduled = currenttemp.duration * (currenttemp.rate - basal) / 60; if (insulinScheduled >= insulinReq * 2) { // if current temp would deliver >2x more than the required insulin, lower the rate rT.reason += currenttemp.duration + "m@" + (currenttemp.rate).toFixed(2) + " > 2 * insulinReq. Setting temp basal of " + rate + "U/hr. "; return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); } - if (typeof currenttemp.duration == 'undefined' || currenttemp.duration == 0) { // no temp is set + if (typeof currenttemp.duration === 'undefined' || currenttemp.duration === 0) { // no temp is set rT.reason += "no temp, setting " + rate + "U/hr. "; return tempBasalFunctions.setTempBasal(rate, 30, profile, rT, currenttemp); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index e445a1043d..4701665f0a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -48,6 +48,7 @@ public class DetermineBasalAdapterSMBJS { private JSONObject mAutosensData = null; private boolean mMicrobolusAllowed; private boolean mSMBAlwaysAllowed; + private long mCurrentTime; private String storedCurrentTemp = null; private String storedIobData = null; @@ -58,6 +59,7 @@ public class DetermineBasalAdapterSMBJS { private String storedAutosens_data = null; private String storedMicroBolusAllowed = null; private String storedSMBAlwaysAllowed = null; + private String storedCurrentTime = null; private String scriptDebug = ""; @@ -87,6 +89,7 @@ public class DetermineBasalAdapterSMBJS { log.debug("Reservoir data: " + "undefined"); log.debug("MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed)); log.debug("SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed)); +// log.debug("Current Time: " + (storedCurrentTime = "" + mCurrentTime)); } DetermineBasalResultSMB determineBasalResultSMB = null; @@ -129,7 +132,8 @@ public class DetermineBasalAdapterSMBJS { makeParam(mMealData, rhino, scope), setTempBasalFunctionsObj, new Boolean(mMicrobolusAllowed), - makeParam(null, rhino, scope) // reservoir data as undefined + makeParam(null, rhino, scope), // reservoir data as undefined + mCurrentTime }; @@ -163,6 +167,7 @@ public class DetermineBasalAdapterSMBJS { storedCurrentTemp = mCurrentTemp.toString(); storedProfile = mProfile.toString(); storedMeal_data = mMealData.toString(); + //storedCurrentTime = "" + mCurrentTime; return determineBasalResultSMB; @@ -172,6 +177,10 @@ public class DetermineBasalAdapterSMBJS { return storedGlucoseStatus; } + // String getCurrentTimeParam() { + // return storedCurrentTime; + // } + String getCurrentTempParam() { return storedCurrentTemp; } @@ -332,6 +341,8 @@ public class DetermineBasalAdapterSMBJS { mMicrobolusAllowed = microBolusAllowed; mSMBAlwaysAllowed = advancedFiltering; + mCurrentTime = System.currentTimeMillis(); + } private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { From 2c956f43ba8991d7e59ca062209932e244aae8c5 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 26 Oct 2019 22:29:41 +0200 Subject: [PATCH 013/316] biometrics support for Preferences --- app/build.gradle | 1 + .../nightscout/androidaps/MainActivity.java | 10 +-- .../activities/PreferencesActivity.java | 50 ++++++++++---- .../activities/SingleFragmentActivity.java | 9 ++- .../configBuilder/ConfigBuilderFragment.kt | 16 +++-- .../plugins/configBuilder/PluginViewHolder.kt | 14 ++-- .../androidaps/setupwizard/SWDefinition.java | 22 +++--- .../androidaps/utils/PasswordProtection.java | 68 ------------------- .../utils/protection/BiometricCheck.kt | 50 ++++++++++++++ .../utils/protection/PasswordCheck.kt | 49 +++++++++++++ .../utils/protection/ProtectionCheck.kt | 56 +++++++++++++++ app/src/main/res/values/protection.xml | 36 ++++++++++ app/src/main/res/values/strings.xml | 2 - app/src/main/res/xml/pref_password.xml | 50 +++++++++++--- 14 files changed, 309 insertions(+), 124 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/utils/PasswordProtection.java create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/protection/PasswordCheck.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt create mode 100644 app/src/main/res/values/protection.xml diff --git a/app/build.gradle b/app/build.gradle index 86709bfdd2..a71692d30f 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -235,6 +235,7 @@ dependencies { implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.cardview:cardview:1.0.0' implementation 'androidx.recyclerview:recyclerview:1.0.0' + implementation 'androidx.biometric:biometric:1.0.0-rc02' implementation 'androidx.gridlayout:gridlayout:1.0.0' implementation 'com.google.android.material:material:1.0.0' implementation 'androidx.percentlayout:percentlayout:1.0.0' diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 64c2656086..f6b2d7456c 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -60,8 +60,8 @@ import info.nightscout.androidaps.utils.AndroidPermission; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.OKDialog; -import info.nightscout.androidaps.utils.PasswordProtection; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.protection.ProtectionCheck; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; @@ -333,11 +333,11 @@ public class MainActivity extends NoSplashAppCompatActivity { int id = item.getItemId(); switch (id) { case R.id.nav_preferences: - PasswordProtection.QueryPassword(this, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(this, PreferencesActivity.class); i.putExtra("id", -1); startActivity(i); - }, null); + }); return true; case R.id.nav_historybrowser: startActivity(new Intent(this, HistoryBrowseActivity.class)); @@ -375,11 +375,11 @@ public class MainActivity extends NoSplashAppCompatActivity { case R.id.nav_plugin_preferences: ViewPager viewPager = findViewById(R.id.pager); final PluginBase plugin = ((TabPageAdapter) viewPager.getAdapter()).getPluginAt(viewPager.getCurrentItem()); - PasswordProtection.QueryPassword(this, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(this, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); startActivity(i); - }, null); + }); return true; } return actionBarDrawerToggle.onOptionsItemSelected(item); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java index 367429dbbf..d551cc4b7a 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -15,21 +15,25 @@ import android.text.TextUtils; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRebuildTabs; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin; -import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; -import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin; -import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader; -import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; -import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; +import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; +import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin; +import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin; +import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; +import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin; +import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader; +import info.nightscout.androidaps.plugins.general.wear.WearPlugin; +import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; +import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; @@ -42,14 +46,10 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; -import info.nightscout.androidaps.plugins.general.wear.WearPlugin; -import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin; -import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.SP; -import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin; +import info.nightscout.androidaps.utils.protection.ProtectionCheck; public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { MyPreferenceFragment myPreferenceFragment; @@ -87,6 +87,30 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre if (pref instanceof ListPreference) { ListPreference listPref = (ListPreference) pref; pref.setSummary(listPref.getEntry()); + // Preferences + if (pref.getKey().equals(MainApp.gs(R.string.key_settings_protection))) { + Preference pass = pref.getPreferenceManager().findPreference(MainApp.gs(R.string.key_settings_password)); + if (pass != null) + if (((ListPreference) pref).getValue().equals(Integer.toString(ProtectionCheck.ProtectionType.PASSWORD.ordinal()))) + pass.setEnabled(true); + else pass.setEnabled(false); + } + // Application + if (pref.getKey().equals(MainApp.gs(R.string.key_application_protection))) { + Preference pass = pref.getPreferenceManager().findPreference(MainApp.gs(R.string.key_application_password)); + if (pass != null) + if (((ListPreference) pref).getValue().equals(Integer.toString(ProtectionCheck.ProtectionType.PASSWORD.ordinal()))) + pass.setEnabled(true); + else pass.setEnabled(false); + } + // Bolus + if (pref.getKey().equals(MainApp.gs(R.string.key_bolus_protection))) { + Preference pass = pref.getPreferenceManager().findPreference(MainApp.gs(R.string.key_bolus_password)); + if (pass != null) + if (((ListPreference) pref).getValue().equals(Integer.toString(ProtectionCheck.ProtectionType.PASSWORD.ordinal()))) + pass.setEnabled(true); + else pass.setEnabled(false); + } } if (pref instanceof EditTextPreference) { EditTextPreference editTextPref = (EditTextPreference) pref; @@ -97,7 +121,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre } else if (editTextPref.getText() != null) { ((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage()); pref.setSummary(editTextPref.getText()); - } else if (pref.getKey().contains("smscommunicator_allowednumbers") && (editTextPref.getText() == null || TextUtils.isEmpty(editTextPref.getText().trim()))) { + } else if (pref.getKey().contains(SP.getString(R.string.key_smscommunicator_allowednumbers, "")) && (editTextPref.getText() == null || TextUtils.isEmpty(editTextPref.getText().trim()))) { pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java index 688ba82c6a..79768359c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java @@ -12,7 +12,7 @@ import androidx.fragment.app.Fragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.utils.PasswordProtection; +import info.nightscout.androidaps.utils.protection.ProtectionCheck; public class SingleFragmentActivity extends AppCompatActivity { @@ -39,13 +39,12 @@ public class SingleFragmentActivity extends AppCompatActivity { if (item.getItemId() == android.R.id.home) { finish(); return true; - } - else if (item.getItemId() == R.id.nav_plugin_preferences) { - PasswordProtection.QueryPassword(this, R.string.settings_password, "settings_password", () -> { + } else if (item.getItemId() == R.id.nav_plugin_preferences) { + ProtectionCheck.INSTANCE.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(this, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); startActivity(i); - }, null); + }); return true; } return false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 059bec1444..58f8a33748 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.PasswordProtection +import info.nightscout.androidaps.utils.protection.ProtectionCheck import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.configbuilder_fragment.* @@ -33,16 +33,20 @@ class ConfigBuilderFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - if (PasswordProtection.isLocked("settings_password")) + if (ProtectionCheck.isLocked(ProtectionCheck.Protection.PREFERENCES)) configbuilder_main_layout.visibility = View.GONE else unlock.visibility = View.GONE unlock.setOnClickListener { - PasswordProtection.QueryPassword(context, R.string.settings_password, "settings_password", { - configbuilder_main_layout.visibility = View.VISIBLE - unlock.visibility = View.GONE - }, null) + activity?.let { activity -> + ProtectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable { + activity.runOnUiThread { + configbuilder_main_layout.visibility = View.VISIBLE + unlock.visibility = View.GONE + } + }) + } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt index 86e0f39437..549e71566e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.PasswordProtection +import info.nightscout.androidaps.utils.protection.ProtectionCheck class PluginViewHolder internal constructor(private val fragment: ConfigBuilderFragment, private val pluginType: PluginType, @@ -46,11 +46,13 @@ class PluginViewHolder internal constructor(private val fragment: ConfigBuilderF } pluginPreferences.setOnClickListener { - PasswordProtection.QueryPassword(fragment.context, R.string.settings_password, "settings_password", { - val i = Intent(fragment.context, PreferencesActivity::class.java) - i.putExtra("id", plugin.preferencesId) - fragment.startActivity(i) - }, null) + fragment.activity?.let { activity -> + ProtectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable { + val i = Intent(fragment.context, PreferencesActivity::class.java) + i.putExtra("id", plugin.preferencesId) + fragment.startActivity(i) + }) + } } update() } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java index 2c9e1ea51b..1369c19377 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java @@ -47,8 +47,8 @@ import info.nightscout.androidaps.setupwizard.elements.SWRadioButton; import info.nightscout.androidaps.setupwizard.events.EventSWUpdate; import info.nightscout.androidaps.utils.AndroidPermission; import info.nightscout.androidaps.utils.LocaleHelper; -import info.nightscout.androidaps.utils.PasswordProtection; import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.protection.ProtectionCheck; public class SWDefinition { private AppCompatActivity activity; @@ -216,11 +216,11 @@ public class SWDefinition { .action(() -> { final PluginBase plugin = (PluginBase) ConfigBuilderPlugin.getPlugin().getActiveInsulin(); if (plugin != null) { - PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(activity, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); activity.startActivity(i); - }, null); + }); } }) .visibility(() -> ConfigBuilderPlugin.getPlugin().getActiveInsulin() != null && ((PluginBase) ConfigBuilderPlugin.getPlugin().getActiveInsulin()).getPreferencesId() > 0)) @@ -237,11 +237,11 @@ public class SWDefinition { .action(() -> { final PluginBase plugin = (PluginBase) ConfigBuilderPlugin.getPlugin().getActiveBgSource(); if (plugin != null) { - PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(activity, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); activity.startActivity(i); - }, null); + }); } }) .visibility(() -> ConfigBuilderPlugin.getPlugin().getActiveBgSource() != null && ((PluginBase) ConfigBuilderPlugin.getPlugin().getActiveBgSource()).getPreferencesId() > 0)) @@ -307,11 +307,11 @@ public class SWDefinition { .action(() -> { final PluginBase plugin = (PluginBase) ConfigBuilderPlugin.getPlugin().getActivePump(); if (plugin != null) { - PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(activity, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); activity.startActivity(i); - }, null); + }); } }) .visibility(() -> (ConfigBuilderPlugin.getPlugin().getActivePump() != null && ((PluginBase) ConfigBuilderPlugin.getPlugin().getActivePump()).getPreferencesId() > 0))) @@ -338,11 +338,11 @@ public class SWDefinition { .action(() -> { final PluginBase plugin = (PluginBase) ConfigBuilderPlugin.getPlugin().getActiveAPS(); if (plugin != null) { - PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(activity, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); activity.startActivity(i); - }, null); + }); } }) .visibility(() -> ConfigBuilderPlugin.getPlugin().getActiveAPS() != null && ((PluginBase) ConfigBuilderPlugin.getPlugin().getActiveAPS()).getPreferencesId() > 0)) @@ -392,11 +392,11 @@ public class SWDefinition { .action(() -> { final PluginBase plugin = (PluginBase) ConfigBuilderPlugin.getPlugin().getActiveSensitivity(); if (plugin != null) { - PasswordProtection.QueryPassword(activity, R.string.settings_password, "settings_password", () -> { + ProtectionCheck.INSTANCE.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, () -> { Intent i = new Intent(activity, PreferencesActivity.class); i.putExtra("id", plugin.getPreferencesId()); activity.startActivity(i); - }, null); + }); } }) .visibility(() -> ConfigBuilderPlugin.getPlugin().getActiveSensitivity() != null && ((PluginBase) ConfigBuilderPlugin.getPlugin().getActiveSensitivity()).getPreferencesId() > 0)) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/PasswordProtection.java b/app/src/main/java/info/nightscout/androidaps/utils/PasswordProtection.java deleted file mode 100644 index 230be97e22..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/PasswordProtection.java +++ /dev/null @@ -1,68 +0,0 @@ -package info.nightscout.androidaps.utils; - -import android.app.AlertDialog; -import android.content.Context; -import android.content.DialogInterface; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.EditText; -import android.widget.TextView; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; - -/** - * Created by mike on 14.02.2017. - */ - -public class PasswordProtection { - static public boolean isLocked(String preference) { - final String password = SP.getString(preference, ""); - if (password.equals("")) { - return false; - } - return true; - } - - static public void QueryPassword(final Context context, int stringID, String preference, final Runnable ok, final Runnable fail) { - final String password = SP.getString(preference, ""); - if (password.equals("")) { - if (ok != null) ok.run(); - return; - } - LayoutInflater li = LayoutInflater.from(context); - View promptsView = li.inflate(R.layout.passwordprompt, null); - - AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); - alertDialogBuilder.setView(promptsView); - - final TextView label = (TextView) promptsView.findViewById(R.id.passwordprompt_text); - label.setText(MainApp.gs(stringID)); - final EditText userInput = (EditText) promptsView.findViewById(R.id.passwordprompt_pass); - - // set dialog message - alertDialogBuilder - .setCancelable(false) - .setPositiveButton("OK", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog,int id) { - String enteredPassword = userInput.getText().toString(); - if (password.equals(enteredPassword)) { - if (ok != null) ok.run(); - } else { - ToastUtils.showToastInUiThread(context, MainApp.gs(R.string.wrongpassword)); - if (fail != null) fail.run(); - } - } - }) - .setNegativeButton("Cancel", - new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog,int id) { - dialog.cancel(); - } - }); - - AlertDialog alertDialog = alertDialogBuilder.create(); - alertDialog.show(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt b/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt new file mode 100644 index 0000000000..decbf92056 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt @@ -0,0 +1,50 @@ +package info.nightscout.androidaps.utils.protection + +import androidx.biometric.BiometricPrompt +import androidx.fragment.app.FragmentActivity +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.ToastUtils +import java.util.concurrent.Executors + +object BiometricCheck { + fun biometricPrompt(activity: FragmentActivity, ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null) { + val executor = Executors.newSingleThreadExecutor() + + val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() { + + override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { + super.onAuthenticationError(errorCode, errString) + if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) cancel?.run() + else { + // Called when an unrecoverable error has been encountered and the operation is complete. + ToastUtils.showToastInUiThread(activity.baseContext, errString.toString()) + // call ok, because it's not possible to bypass it when biometrics fail + ok?.run() + } + } + + override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { + super.onAuthenticationSucceeded(result) + // Called when a biometric is recognized. + ok?.run() + } + + override fun onAuthenticationFailed() { + super.onAuthenticationFailed() + // Called when a biometric is valid but not recognized. + fail?.run() + } + }) + + val promptInfo = BiometricPrompt.PromptInfo.Builder() + .setTitle(MainApp.gs(R.string.biometric_title)) + .setSubtitle("Set the subtitle to display.") + .setDescription(MainApp.gs(R.string.biometric_title)) + .setNegativeButtonText(MainApp.gs(R.string.cancel)) + .build() + + biometricPrompt.authenticate(promptInfo) + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/protection/PasswordCheck.kt b/app/src/main/java/info/nightscout/androidaps/utils/protection/PasswordCheck.kt new file mode 100644 index 0000000000..beeeef3add --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/protection/PasswordCheck.kt @@ -0,0 +1,49 @@ +package info.nightscout.androidaps.utils.protection + +import android.app.AlertDialog +import android.view.LayoutInflater +import android.view.View +import android.widget.EditText +import android.widget.TextView +import androidx.annotation.StringRes +import androidx.fragment.app.FragmentActivity +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.SP +import info.nightscout.androidaps.utils.ToastUtils + +object PasswordCheck { + fun queryPassword(activity: FragmentActivity, @StringRes labelId: Int, @StringRes preference: Int, ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null) { + val password = SP.getString(preference, "") + if (password == "") { + ok?.run() + return + } + val promptsView = LayoutInflater.from(activity).inflate(R.layout.passwordprompt, null) + + val alertDialogBuilder = AlertDialog.Builder(activity) + alertDialogBuilder.setView(promptsView) + + val label = promptsView.findViewById(R.id.passwordprompt_text) as TextView + label.text = MainApp.gs(labelId) + val userInput = promptsView.findViewById(R.id.passwordprompt_pass) as EditText + + alertDialogBuilder + .setCancelable(false) + .setPositiveButton(MainApp.gs(R.string.ok)) { _, _ -> + val enteredPassword = userInput.text.toString() + if (password == enteredPassword) ok?.run() + else { + ToastUtils.showToastInUiThread(activity, MainApp.gs(R.string.wrongpassword)) + fail?.run() + } + } + .setNegativeButton(MainApp.gs(R.string.cancel) + ) { dialog, _ -> + cancel?.run() + dialog.cancel() + } + + alertDialogBuilder.create().show() + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt b/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt new file mode 100644 index 0000000000..86e29a7ed7 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt @@ -0,0 +1,56 @@ +package info.nightscout.androidaps.utils.protection + +import androidx.fragment.app.FragmentActivity +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.SP + +object ProtectionCheck { + enum class Protection { + PREFERENCES, + APPLICATION, + BOLUS + } + + enum class ProtectionType { + NONE, + BIOMETRIC, + PASSWORD + } + + private val passwordsResourceIDs = listOf( + R.string.key_settings_password, + R.string.key_application_password, + R.string.key_bolus_password) + + private val protectionTypeResourceIDs = listOf( + R.string.key_settings_protection, + R.string.key_application_protection, + R.string.key_bolus_protection) + + private val titleResourceIDs = listOf( + R.string.settings_password, + R.string.application_password, + R.string.bolus_password) + + fun isLocked(protection: Protection): Boolean { + when (ProtectionType.values()[SP.getInt(protectionTypeResourceIDs[protection.ordinal], ProtectionType.NONE.ordinal)]) { + ProtectionType.NONE -> return false + ProtectionType.BIOMETRIC -> return true + ProtectionType.PASSWORD -> return SP.getString(passwordsResourceIDs[protection.ordinal], "") != "" + } + } + + @JvmOverloads + fun queryProtection(activity: FragmentActivity, protection: Protection, + ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null) { + when (ProtectionType.values()[SP.getInt(protectionTypeResourceIDs[protection.ordinal], ProtectionType.NONE.ordinal)]) { + ProtectionType.NONE -> + ok?.run() + ProtectionType.BIOMETRIC -> + BiometricCheck.biometricPrompt(activity, ok, cancel, fail) + ProtectionType.PASSWORD -> + PasswordCheck.queryPassword(activity, titleResourceIDs[protection.ordinal], passwordsResourceIDs[protection.ordinal], ok, cancel, fail) + } + } + +} \ No newline at end of file diff --git a/app/src/main/res/values/protection.xml b/app/src/main/res/values/protection.xml new file mode 100644 index 0000000000..6bf675ab44 --- /dev/null +++ b/app/src/main/res/values/protection.xml @@ -0,0 +1,36 @@ + + + Authentication required + Place your finger on the fingerprint reader to verify your identity + Settings protection + Application protection + Bolus protection + Settings password + Application password + Bolus password + Unlock settings + Biometric + Password + No protection + Protection + + settings_password + application_password + translatable="false"bolus_password + settings_protection + application_protection + bolus_protection + + + @string/noprotection + @string/biometric + @string/password + + + + 0 + 1 + 2 + + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 70e05db6c4..e2dc6b5e07 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -515,8 +515,6 @@ Virtual pump settings Upload status to NS Wrong password - Password for settings - Unlock settings Approaching insulin daily limit NSClient NSCI diff --git a/app/src/main/res/xml/pref_password.xml b/app/src/main/res/xml/pref_password.xml index f050d0486c..fc71b2a644 100644 --- a/app/src/main/res/xml/pref_password.xml +++ b/app/src/main/res/xml/pref_password.xml @@ -1,14 +1,48 @@ - - - + + + + + + + + + + + + + + + + + + \ No newline at end of file From 466084db71dd66748dda438e5b5d87b6e9d355bc Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 26 Oct 2019 23:21:51 +0200 Subject: [PATCH 014/316] more tweaking --- .../utils/protection/BiometricCheck.kt | 33 +++++++++++++------ .../utils/protection/ProtectionCheck.kt | 2 +- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt b/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt index decbf92056..5aba1cf12f 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/protection/BiometricCheck.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.utils.protection +import androidx.biometric.BiometricConstants import androidx.biometric.BiometricPrompt import androidx.fragment.app.FragmentActivity import info.nightscout.androidaps.MainApp @@ -8,19 +9,32 @@ import info.nightscout.androidaps.utils.ToastUtils import java.util.concurrent.Executors object BiometricCheck { - fun biometricPrompt(activity: FragmentActivity, ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null) { + fun biometricPrompt(activity: FragmentActivity, title: Int, ok: Runnable?, cancel: Runnable? = null, fail: Runnable? = null) { val executor = Executors.newSingleThreadExecutor() val biometricPrompt = BiometricPrompt(activity, executor, object : BiometricPrompt.AuthenticationCallback() { - override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) - if (errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON) cancel?.run() - else { - // Called when an unrecoverable error has been encountered and the operation is complete. - ToastUtils.showToastInUiThread(activity.baseContext, errString.toString()) - // call ok, because it's not possible to bypass it when biometrics fail - ok?.run() + when (errorCode) { + BiometricConstants.ERROR_UNABLE_TO_PROCESS, + BiometricConstants.ERROR_TIMEOUT, + BiometricConstants.ERROR_CANCELED, + BiometricConstants.ERROR_LOCKOUT, + BiometricConstants.ERROR_VENDOR, + BiometricConstants.ERROR_LOCKOUT_PERMANENT, + BiometricConstants.ERROR_USER_CANCELED -> { + ToastUtils.showToastInUiThread(activity.baseContext, errString.toString()) + fail?.run() + } + BiometricConstants.ERROR_NEGATIVE_BUTTON -> + cancel?.run() + BiometricConstants.ERROR_NO_SPACE, + BiometricConstants.ERROR_HW_UNAVAILABLE, + BiometricConstants.ERROR_HW_NOT_PRESENT, + BiometricConstants.ERROR_NO_DEVICE_CREDENTIAL, + BiometricConstants.ERROR_NO_BIOMETRICS -> + // call ok, because it's not possible to bypass it when biometrics fail + ok?.run() } } @@ -38,8 +52,7 @@ object BiometricCheck { }) val promptInfo = BiometricPrompt.PromptInfo.Builder() - .setTitle(MainApp.gs(R.string.biometric_title)) - .setSubtitle("Set the subtitle to display.") + .setTitle(MainApp.gs(title)) .setDescription(MainApp.gs(R.string.biometric_title)) .setNegativeButtonText(MainApp.gs(R.string.cancel)) .build() diff --git a/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt b/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt index 86e29a7ed7..c7880aee08 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/protection/ProtectionCheck.kt @@ -47,7 +47,7 @@ object ProtectionCheck { ProtectionType.NONE -> ok?.run() ProtectionType.BIOMETRIC -> - BiometricCheck.biometricPrompt(activity, ok, cancel, fail) + BiometricCheck.biometricPrompt(activity, titleResourceIDs[protection.ordinal], ok, cancel, fail) ProtectionType.PASSWORD -> PasswordCheck.queryPassword(activity, titleResourceIDs[protection.ordinal], passwordsResourceIDs[protection.ordinal], ok, cancel, fail) } From 724c1edfd59a5d54a6022ceb17972e103b1df69b Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 29 Nov 2019 20:23:30 +1300 Subject: [PATCH 015/316] Add Noise to be used later when needed --- .../plugins/iob/iobCobCalculator/GlucoseStatus.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java index 159c5865af..512c22d2e4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java @@ -21,6 +21,7 @@ import info.nightscout.androidaps.utils.Round; public class GlucoseStatus { private static Logger log = LoggerFactory.getLogger(GlucoseStatus.class); public double glucose = 0d; + public double noise = 0d; public double delta = 0d; public double avgdelta = 0d; public double short_avgdelta = 0d; @@ -30,6 +31,7 @@ public class GlucoseStatus { public String log() { return "Glucose: " + DecimalFormatter.to0Decimal(glucose) + " mg/dl " + + "Noise: " + DecimalFormatter.to0Decimal(noise) + " " + "Delta: " + DecimalFormatter.to0Decimal(delta) + " mg/dl" + "Short avg. delta: " + " " + DecimalFormatter.to2Decimal(short_avgdelta) + " mg/dl " + "Long avg. delta: " + DecimalFormatter.to2Decimal(long_avgdelta) + " mg/dl"; @@ -40,6 +42,7 @@ public class GlucoseStatus { public GlucoseStatus round() { this.glucose = Round.roundTo(this.glucose, 0.1); + this.noise = Round.roundTo(this.noise, 0.1); this.delta = Round.roundTo(this.delta, 0.01); this.avgdelta = Round.roundTo(this.avgdelta, 0.01); this.short_avgdelta = Round.roundTo(this.short_avgdelta, 0.01); @@ -89,6 +92,7 @@ public class GlucoseStatus { if (sizeRecords == 1) { GlucoseStatus status = new GlucoseStatus(); status.glucose = now.value; + status.noise = 0d; status.short_avgdelta = 0d; status.delta = 0d; status.long_avgdelta = 0d; @@ -148,6 +152,7 @@ public class GlucoseStatus { GlucoseStatus status = new GlucoseStatus(); status.glucose = now.value; status.date = now_date; + status.noise = 0d; //for now set to nothing as not all CGMs report noise status.short_avgdelta = average(short_deltas); From 39835d3481294b7c974da46ca16dd734bc0dc534 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 29 Nov 2019 21:08:17 +1300 Subject: [PATCH 016/316] bring determine_basal up to date with 0.7.0 --- .../main/assets/OpenAPSSMB/determine-basal.js | 183 +++++++++--------- 1 file changed, 95 insertions(+), 88 deletions(-) diff --git a/app/src/main/assets/OpenAPSSMB/determine-basal.js b/app/src/main/assets/OpenAPSSMB/determine-basal.js index 4d9ed4122c..0ddbd9d601 100644 --- a/app/src/main/assets/OpenAPSSMB/determine-basal.js +++ b/app/src/main/assets/OpenAPSSMB/determine-basal.js @@ -47,6 +47,69 @@ function convert_bg(value, profile) } } +function enable_smb( + profile, + microBolusAllowed, + meal_data, + target_bg +) { + // disable SMB when a high temptarget is set + if (! microBolusAllowed) { + console.error("SMB disabled (!microBolusAllowed)"); + return false; + } else if (! profile.allowSMB_with_high_temptarget && profile.temptargetSet && target_bg > 100) { + console.error("SMB disabled due to high temptarget of",target_bg); + return false; + } else if (meal_data.bwFound === true && profile.A52_risk_enable === false) { + console.error("SMB disabled due to Bolus Wizard activity in the last 6 hours."); + return false; + } + + // enable SMB/UAM if always-on (unless previously disabled for high temptarget) + if (profile.enableSMB_always === true) { + if (meal_data.bwFound) { + console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard"); + } else { + console.error("SMB enabled due to enableSMB_always"); + } + return true; + } + + // enable SMB/UAM (if enabled in preferences) while we have COB + if (profile.enableSMB_with_COB === true && meal_data.mealCOB) { + if (meal_data.bwCarbs) { + console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard"); + } else { + console.error("SMB enabled for COB of",meal_data.mealCOB); + } + return true; + } + + // enable SMB/UAM (if enabled in preferences) for a full 6 hours after any carb entry + // (6 hours is defined in carbWindow in lib/meal/total.js) + if (profile.enableSMB_after_carbs === true && meal_data.carbs ) { + if (meal_data.bwCarbs) { + console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard"); + } else { + console.error("SMB enabled for 6h after carb entry"); + } + return true; + } + + // enable SMB/UAM (if enabled in preferences) if a low temptarget is set + if (profile.enableSMB_with_temptarget === true && (profile.temptargetSet && target_bg < 100)) { + if (meal_data.bwFound) { + console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard"); + } else { + console.error("SMB enabled for temptarget of",convert_bg(target_bg, profile)); + } + return true; + } + + console.error("SMB disabled (no enableSMB preferences active or no condition satisfied)"); + return false; +} + var determine_basal = function determine_basal(glucose_status, currenttemp, iob_data, profile, autosens_data, meal_data, tempBasalFunctions, microBolusAllowed, reservoir_data, currentTime) { var rT = {}; //short for requestedTemp @@ -86,7 +149,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ rT.reason = "Error: CGM data is unchanged for the past ~45m"; } } - if (bg <= 10 || bg === 38 || noise >= 3 || minAgo > 12 || minAgo < -5 || ( bg > 60 && glucose_status == 0 && glucose_status.short_avgdelta > -1 && glucose_status.short_avgdelta < 1 && glucose_status.long_avgdelta > -1 && glucose_status.long_avgdelta < 1 ) ) { + if (bg <= 10 || bg === 38 || noise >= 3 || minAgo > 12 || minAgo < -5 || ( bg > 60 && glucose_status == 0 && glucose_status.short_avgdelta > -1 && glucose_status.short_avgdelta < 1 && glucose_status.long_avgdelta > -1 && glucose_status.long_avgdelta < 1 ) ) { if (currenttemp.rate > basal) { // high temp is running rT.reason += ". Replacing high temp basal of "+currenttemp.rate+" with neutral temp of "+basal; rT.deliverAt = deliverAt; @@ -130,7 +193,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var sensitivityRatio; var high_temptarget_raises_sensitivity = profile.exercise_mode || profile.high_temptarget_raises_sensitivity; - var normalTarget = 100; // evaluate high/low temptarget against 100, not scheduled basal (which might change) + var normalTarget = 100; // evaluate high/low temptarget against 100, not scheduled target (which might change) if ( profile.half_basal_exercise_target ) { var halfBasalTarget = profile.half_basal_exercise_target; } else { @@ -147,24 +210,24 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // limit sensitivityRatio to profile.autosens_max (1.2x by default) sensitivityRatio = Math.min(sensitivityRatio, profile.autosens_max); sensitivityRatio = round(sensitivityRatio,2); - process.stderr.write("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+target_bg+"; "); + console.log("Sensitivity ratio set to "+sensitivityRatio+" based on temp target of "+target_bg+"; "); } else if (typeof autosens_data !== 'undefined' && autosens_data) { sensitivityRatio = autosens_data.ratio; - process.stderr.write("Autosens ratio: "+sensitivityRatio+"; "); + console.log("Autosens ratio: "+sensitivityRatio+"; "); } if (sensitivityRatio) { basal = profile.current_basal * sensitivityRatio; basal = round_basal(basal, profile); if (basal !== profile_current_basal) { - process.stderr.write("Adjusting basal from "+profile_current_basal+" to "+basal+"; "); + console.log("Adjusting basal from "+profile_current_basal+" to "+basal+"; "); } else { - process.stderr.write("Basal unchanged: "+basal+"; "); + console.log("Basal unchanged: "+basal+"; "); } } // adjust min, max, and target BG for sensitivity, such that 50% increase in ISF raises target from 100 to 120 if (profile.temptargetSet) { - //process.stderr.write("Temp Target set, not adjusting with autosens; "); + //console.log("Temp Target set, not adjusting with autosens; "); } else if (typeof autosens_data !== 'undefined' && autosens_data) { if ( profile.sensitivity_raises_target && autosens_data.ratio < 1 || profile.resistance_lowers_target && autosens_data.ratio > 1 ) { // with a target of 100, default 0.7-1.2 autosens min/max range would allow a 93-117 target range @@ -174,9 +237,9 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // don't allow target_bg below 80 new_target_bg = Math.max(80, new_target_bg); if (target_bg === new_target_bg) { - process.stderr.write("target_bg unchanged: "+new_target_bg+"; "); + console.log("target_bg unchanged: "+new_target_bg+"; "); } else { - process.stderr.write("target_bg from "+target_bg+" to "+new_target_bg+"; "); + console.log("target_bg from "+target_bg+" to "+new_target_bg+"; "); } target_bg = new_target_bg; } @@ -216,11 +279,11 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ sens = profile.sens / sensitivityRatio; sens = round(sens, 1); if (sens !== profile_sens) { - process.stderr.write("ISF from "+profile_sens+" to "+sens); + console.log("ISF from "+profile_sens+" to "+sens); } else { - process.stderr.write("ISF unchanged: "+sens); + console.log("ISF unchanged: "+sens); } - //process.stderr.write(" (autosens ratio "+sensitivityRatio+")"); + //console.log(" (autosens ratio "+sensitivityRatio+")"); } console.error("; CR:",profile.carb_ratio); @@ -292,7 +355,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var adjustedMinBG = round(Math.min(200, min_bg * noisyCGMTargetMultiplier )); var adjustedTargetBG = round(Math.min(200, target_bg * noisyCGMTargetMultiplier )); var adjustedMaxBG = round(Math.min(200, max_bg * noisyCGMTargetMultiplier )); - process.stderr.write("Raising target_bg for noisy / raw CGM data, from "+target_bg+" to "+adjustedTargetBG+"; "); + console.log("Raising target_bg for noisy / raw CGM data, from "+target_bg+" to "+adjustedTargetBG+"; "); min_bg = adjustedMinBG; target_bg = adjustedTargetBG; max_bg = adjustedMaxBG; @@ -305,17 +368,17 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // if eventualBG, naive_eventualBG, and target_bg aren't all above adjustedMinBG, don’t use it //console.error("naive_eventualBG:",naive_eventualBG+", eventualBG:",eventualBG); if (eventualBG > adjustedMinBG && naive_eventualBG > adjustedMinBG && min_bg > adjustedMinBG) { - process.stderr.write("Adjusting targets for high BG: min_bg from "+min_bg+" to "+adjustedMinBG+"; "); + console.log("Adjusting targets for high BG: min_bg from "+min_bg+" to "+adjustedMinBG+"; "); min_bg = adjustedMinBG; } else { - process.stderr.write("min_bg unchanged: "+min_bg+"; "); + console.log("min_bg unchanged: "+min_bg+"; "); } // if eventualBG, naive_eventualBG, and target_bg aren't all above adjustedTargetBG, don’t use it if (eventualBG > adjustedTargetBG && naive_eventualBG > adjustedTargetBG && target_bg > adjustedTargetBG) { - process.stderr.write("target_bg from "+target_bg+" to "+adjustedTargetBG+"; "); + console.log("target_bg from "+target_bg+" to "+adjustedTargetBG+"; "); target_bg = adjustedTargetBG; } else { - process.stderr.write("target_bg unchanged: "+target_bg+"; "); + console.log("target_bg unchanged: "+target_bg+"; "); } // if eventualBG, naive_eventualBG, and max_bg aren't all above adjustedMaxBG, don’t use it if (eventualBG > adjustedMaxBG && naive_eventualBG > adjustedMaxBG && max_bg > adjustedMaxBG) { @@ -361,71 +424,13 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ ZTpredBGs.push(bg); UAMpredBGs.push(bg); - // enable SMB whenever we have COB or UAM is enabled - // SMB is disabled by default, unless explicitly enabled in preferences.json - var enableSMB=false; - // disable SMB when a high temptarget is set - if (! microBolusAllowed) { - console.error("SMB disabled (!microBolusAllowed)") - } else if (! profile.allowSMB_with_high_temptarget && profile.temptargetSet && target_bg > 100) { - console.error("SMB disabled due to high temptarget of",target_bg); - enableSMB=false; - // enable SMB/UAM (if enabled in preferences) while we have COB - } else if (profile.enableSMB_with_COB === true && meal_data.mealCOB) { - if (meal_data.bwCarbs) { - if (profile.A52_risk_enable === true) { - console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard") - enableSMB=true; - } else { - console.error("SMB not enabled for Bolus Wizard COB"); - } - } else { - console.error("SMB enabled for COB of",meal_data.mealCOB); - enableSMB=true; - } - // enable SMB/UAM (if enabled in preferences) for a full 6 hours after any carb entry - // (6 hours is defined in carbWindow in lib/meal/total.js) - } else if ((profile.enableSMB_after_carbs === true || profile.enableSMB_with_carbs === true) && meal_data.carbs ) { - if (meal_data.bwCarbs) { - if (profile.A52_risk_enable === true) { - console.error("Warning: SMB enabled with Bolus Wizard carbs: be sure to easy bolus 30s before using Bolus Wizard") - enableSMB=true; - } else { - console.error("SMB not enabled for Bolus Wizard carbs"); - } - } else { - console.error("SMB enabled for 6h after carb entry"); - enableSMB=true; - } - // enable SMB/UAM (if enabled in preferences) if a low temptarget is set - } else if (profile.enableSMB_with_temptarget === true && (profile.temptargetSet && target_bg < 100)) { - if (meal_data.bwFound) { - if (profile.A52_risk_enable === true) { - console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard") - enableSMB=true; - } else { - console.error("enableSMB_with_temptarget not supported within 6h of using Bolus Wizard"); - } - } else { - console.error("SMB enabled for temptarget of",convert_bg(target_bg, profile)); - enableSMB=true; - } - // enable SMB/UAM if always-on (unless previously disabled for high temptarget) - } else if (profile.enableSMB_always === true) { - if (meal_data.bwFound) { - if (profile.A52_risk_enable === true) { - console.error("Warning: SMB enabled within 6h of using Bolus Wizard: be sure to easy bolus 30s before using Bolus Wizard") - enableSMB=true; - } else { - console.error("enableSMB_always not supported within 6h of using Bolus Wizard"); - } - } else { - console.error("SMB enabled due to enableSMB_always"); - enableSMB=true; - } - } else { - console.error("SMB disabled for this run (no selected enableSMB criteria met)"); - } + var enableSMB = enable_smb( + profile, + microBolusAllowed, + meal_data, + target_bg + ); + // enable UAM (if enabled in preferences) var enableUAM=(profile.enableUAM); @@ -573,7 +578,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ remainingCItotal += predCI+remainingCI; remainingCIs.push(round(remainingCI,0)); predCIs.push(round(predCI,0)); - //process.stderr.write(round(predCI,1)+"+"+round(remainingCI,1)+" "); + //console.log(round(predCI,1)+"+"+round(remainingCI,1)+" "); COBpredBG = COBpredBGs[COBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predCI + remainingCI; var aCOBpredBG = aCOBpredBGs[aCOBpredBGs.length-1] + predBGI + Math.min(0,predDev) + predACI; // for UAMpredBGs, predicted carb impact drops at slopeFromDeviations @@ -606,7 +611,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // set minPredBGs starting when currently-dosed insulin activity will peak // look ahead 60m (regardless of insulin type) so as to be less aggressive on slower insulins var insulinPeakTime = 60; - // add 30m to allow for insluin delivery (SMBs or temps) + // add 30m to allow for insulin delivery (SMBs or temps) insulinPeakTime = 90; var insulinPeak5m = (insulinPeakTime/60)*12; //console.error(insulinPeakTime, insulinPeak5m, profile.insulinPeakTime, profile.curve); @@ -764,8 +769,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // if blendedMinPredBG > minCOBPredBG, use that instead minPredBG = round(Math.max(minIOBPredBG, minCOBPredBG, blendedMinPredBG)); // if carbs have been entered, but have expired, use minUAMPredBG - } else { + } else if ( enableUAM ) { minPredBG = minZTUAMPredBG; + } else { + minPredBG = minGuardBG; } // in pure UAM mode, use the higher of minIOBPredBG,minUAMPredBG } else if ( enableUAM ) { @@ -775,12 +782,12 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ // make sure minPredBG isn't higher than avgPredBG minPredBG = Math.min( minPredBG, avgPredBG ); - process.stderr.write("minPredBG: "+minPredBG+" minIOBPredBG: "+minIOBPredBG+" minZTGuardBG: "+minZTGuardBG); + console.log("minPredBG: "+minPredBG+" minIOBPredBG: "+minIOBPredBG+" minZTGuardBG: "+minZTGuardBG); if (minCOBPredBG < 999) { - process.stderr.write(" minCOBPredBG: "+minCOBPredBG); + console.log(" minCOBPredBG: "+minCOBPredBG); } if (minUAMPredBG < 999) { - process.stderr.write(" minUAMPredBG: "+minUAMPredBG); + console.log(" minUAMPredBG: "+minUAMPredBG); } console.error(" avgPredBG:",avgPredBG,"COB:",meal_data.mealCOB,"/",meal_data.carbs); // But if the COB line falls off a cliff, don't trust UAM too much: From 243b7a12a502e21935481d1bfb025cb2f91f4884 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 29 Nov 2019 21:22:26 +1300 Subject: [PATCH 017/316] Add new preferences in and the ability to ingest noise --- .../DetermineBasalAdapterSMBJS.java | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index abc89f25de..82e83ed78a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -28,14 +28,17 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; + public class DetermineBasalAdapterSMBJS { private static Logger log = LoggerFactory.getLogger(L.APS); @@ -92,7 +95,7 @@ public class DetermineBasalAdapterSMBJS { log.debug("Reservoir data: " + "undefined"); log.debug("MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed)); log.debug("SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed)); -// log.debug("Current Time: " + (storedCurrentTime = "" + mCurrentTime)); + log.debug("CurrentTime: " + (storedCurrentTime = "" + mCurrentTime)); } DetermineBasalResultSMB determineBasalResultSMB = null; @@ -136,7 +139,7 @@ public class DetermineBasalAdapterSMBJS { setTempBasalFunctionsObj, new Boolean(mMicrobolusAllowed), makeParam(null, rhino, scope), // reservoir data as undefined - mCurrentTime + new Long(mCurrentTime) }; @@ -170,7 +173,6 @@ public class DetermineBasalAdapterSMBJS { storedCurrentTemp = mCurrentTemp.toString(); storedProfile = mProfile.toString(); storedMeal_data = mMealData.toString(); - //storedCurrentTime = "" + mCurrentTime; return determineBasalResultSMB; @@ -180,10 +182,6 @@ public class DetermineBasalAdapterSMBJS { return storedGlucoseStatus; } - // String getCurrentTimeParam() { - // return storedCurrentTime; - // } - String getCurrentTempParam() { return storedCurrentTemp; } @@ -247,15 +245,13 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)); mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)); - // TODO AS-FIX - // mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)); - mProfile.put("high_temptarget_raises_sensitivity", false); - //mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity)); - mProfile.put("low_temptarget_lowers_sensitivity", false); + mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)); + mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity)); - mProfile.put("sensitivity_raises_target", SMBDefaults.sensitivity_raises_target); - mProfile.put("resistance_lowers_target", SMBDefaults.resistance_lowers_target); + + mProfile.put("sensitivity_raises_target", SP.getBoolean(R.string.key_sensitivity_raises_target, SMBDefaults.sensitivity_raises_target)); + mProfile.put("resistance_lowers_target", SP.getBoolean(R.string.key_resistance_lowers_target, SMBDefaults.resistance_lowers_target)); mProfile.put("adv_target_adjustments", SMBDefaults.adv_target_adjustments); mProfile.put("exercise_mode", SMBDefaults.exercise_mode); mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target); @@ -272,20 +268,20 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable); boolean smbEnabled = SP.getBoolean(MainApp.gs(R.string.key_use_smb), false); + mProfile.put("SMBInterval", SP.getInt("key_smbinterval", SMBDefaults.SMBInterval)); mProfile.put("enableSMB_with_COB", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_COB, false)); mProfile.put("enableSMB_with_temptarget", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_temptarget, false)); mProfile.put("allowSMB_with_high_temptarget", smbEnabled && SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false)); mProfile.put("enableSMB_always", smbEnabled && SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering); mProfile.put("enableSMB_after_carbs", smbEnabled && SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes)); - mProfile.put("maxUAMSMBBasalMinutes", SP.getInt("key_uamsmbmaxminutes", SMBDefaults.maxUAMSMBBasalMinutes)); - mProfile.put("SMBInterval", SP.getInt("key_smbinterval", SMBDefaults.SMBInterval)); + mProfile.put("maxUAMSMBBasalMinutes", SP.getInt(R.string.key_uamsmbmaxminutes, SMBDefaults.maxUAMSMBBasalMinutes)); if (bolusincrement < pumpbolusstep){ //the bolus incrument is less than what the pump can support (by pump settings or pump restriction), set to value supported by the pump bolusincrement = pumpbolusstep; } mProfile.put("bolus_increment", bolusincrement); - mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); + mProfile.put("carbsReqThreshold", SP.getInt(R.string.key_carbsReqThreshold, SMBDefaults.carbsReqThreshold)); mProfile.put("current_basal", basalrate); mProfile.put("temptargetSet", tempTargetSet); @@ -305,7 +301,7 @@ public class DetermineBasalAdapterSMBJS { mCurrentTemp.put("rate", tb != null ? tb.tempBasalConvertedToAbsolute(now, profile) : 0d); // as we have non default temps longer than 30 mintues - TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); + TemporaryBasal tempBasal = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); if (tempBasal != null) { mCurrentTemp.put("minutesrunning", tempBasal.getRealDuration()); } @@ -314,6 +310,7 @@ public class DetermineBasalAdapterSMBJS { mGlucoseStatus = new JSONObject(); mGlucoseStatus.put("glucose", glucoseStatus.glucose); + mGlucoseStatus.put("noise", glucoseStatus.noise); if (SP.getBoolean(R.string.key_always_use_shortavg, false)) { mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta); From 8eeb91a0a80efb1d79856c41bf6be8e14527bccd Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 29 Nov 2019 21:23:12 +1300 Subject: [PATCH 018/316] Add New preferences for oref 0.7.0 --- app/src/main/res/values/strings.xml | 10 ++++ app/src/main/res/xml/pref_openapssmb.xml | 70 ++++++++++++++++-------- 2 files changed, 58 insertions(+), 22 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ccc91c699b..e8a8888ec2 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -837,6 +837,9 @@ Max minutes of basal to limit SMB to UAM SMB max minutes Max minutes of basal to limit SMB to for UAM + carbsReqThreshold + Carb suggestion threshold + When Carbs are suggested, how many carbs will prompt a notification bolus_increment Minimum bolus that can be delivered as an SMB Unsupported pump firmware @@ -1152,6 +1155,12 @@ = 100]]> Low temptarget lowers sensitivity + resistance_lowers_target + Resistance lowers target + When resistance is detected, lower the target glucose + sensitivity_raises_target + Sensitivity raises target + When sensitivity is detected, raise the target glucose Invalid pump setup, check the docs and verify that the Quick Info menu is named QUICK INFO using the 360 configuration software. Custom Large Time Difference @@ -1354,6 +1363,7 @@ Upload BG tests smbmaxminutes + uamsmbmaxminutes Daylight Saving time Daylight Saving time change in 24h or less Daylight Saving time change less than 3 hours ago - Closed loop disabled diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index 45375df376..99e3332bb7 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -93,30 +93,30 @@ validate:testType="numericRange" /> + android:defaultValue="30" + android:dialogMessage="@string/uamsmbmaxminutes" + android:digits="0123456789" + android:inputType="number" + android:key="@string/key_uamsmbmaxminutes" + android:maxLines="20" + android:selectAllOnFocus="true" + android:singleLine="true" + android:title="@string/uamsmbmaxminutes_summary" + validate:maxNumber="120" + validate:minNumber="15" + validate:testType="numericRange" /> + android:defaultValue="0.1" + android:inputType="numberDecimal" + android:key="key_bolus_increment" + android:maxLines="20" + android:selectAllOnFocus="true" + android:singleLine="true" + android:title="@string/bolus_increment_summary" + validate:floatmaxNumber="1.0" + validate:floatminNumber="0.05" + validate:testType="floatNumericRange" /> + + + + From 0a5bd7f935f416257589defa57838a2ea5ec74fe Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 29 Nov 2019 21:24:05 +1300 Subject: [PATCH 019/316] Hack determine_basal so a date string could be converted to date object --- app/src/main/assets/OpenAPSSMB/determine-basal.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/assets/OpenAPSSMB/determine-basal.js b/app/src/main/assets/OpenAPSSMB/determine-basal.js index 0ddbd9d601..363e46da73 100644 --- a/app/src/main/assets/OpenAPSSMB/determine-basal.js +++ b/app/src/main/assets/OpenAPSSMB/determine-basal.js @@ -115,7 +115,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ var deliverAt = new Date(); if (currentTime) { - deliverAt = currentTime; + deliverAt = new Date(currentTime); } if (typeof profile === 'undefined' || typeof profile.current_basal === 'undefined') { From 280e075adab8a982c1ad67d7db65f69948bcce88 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 6 Dec 2019 18:16:09 +1300 Subject: [PATCH 020/316] Remove Bolus Increment setting --- app/src/main/res/values/strings.xml | 2 -- app/src/main/res/xml/pref_openapssmb.xml | 12 ------------ 2 files changed, 14 deletions(-) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e8a8888ec2..f03fbcef92 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -840,8 +840,6 @@ carbsReqThreshold Carb suggestion threshold When Carbs are suggested, how many carbs will prompt a notification - bolus_increment - Minimum bolus that can be delivered as an SMB Unsupported pump firmware Send BG data to xDrip+ dexcomg5_xdripupload diff --git a/app/src/main/res/xml/pref_openapssmb.xml b/app/src/main/res/xml/pref_openapssmb.xml index 99e3332bb7..befec72ec4 100644 --- a/app/src/main/res/xml/pref_openapssmb.xml +++ b/app/src/main/res/xml/pref_openapssmb.xml @@ -106,18 +106,6 @@ validate:minNumber="15" validate:testType="numericRange" /> - - Date: Fri, 6 Dec 2019 18:16:46 +1300 Subject: [PATCH 021/316] Set the Bolus Increment to the min amount supported by the pump --- .../aps/openAPSSMB/DetermineBasalAdapterSMBJS.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index 82e83ed78a..cd86aae46e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -228,7 +228,6 @@ public class DetermineBasalAdapterSMBJS { ) throws JSONException { String units = profile.getUnits(); - Double bolusincrement = SP.getDouble("key_bolus_increment", SMBDefaults.bolus_increment); Double pumpbolusstep = ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().bolusStep; mProfile = new JSONObject(); @@ -276,11 +275,8 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("enableSMB_after_carbs", smbEnabled && SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("maxSMBBasalMinutes", SP.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxUAMSMBBasalMinutes", SP.getInt(R.string.key_uamsmbmaxminutes, SMBDefaults.maxUAMSMBBasalMinutes)); - if (bolusincrement < pumpbolusstep){ - //the bolus incrument is less than what the pump can support (by pump settings or pump restriction), set to value supported by the pump - bolusincrement = pumpbolusstep; - } - mProfile.put("bolus_increment", bolusincrement); + //set the min SMB amount to be the amount set by the pump. + mProfile.put("bolus_increment", pumpbolusstep); mProfile.put("carbsReqThreshold", SP.getInt(R.string.key_carbsReqThreshold, SMBDefaults.carbsReqThreshold)); mProfile.put("current_basal", basalrate); From bf45338eb94a97db538c05ce206ef860ca22fbbc Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 6 Dec 2019 18:22:51 +1300 Subject: [PATCH 022/316] Disable high_temptarget_raises_sensitivity and low_temptarget_lowers_sensitivity --- .../plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index cd86aae46e..bd142bfecd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -244,9 +244,10 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3)); mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d)); - mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)); - mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity)); - + //mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)); + mProfile.put("high_temptarget_raises_sensitivity", false); + //mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity)); + mProfile.put("low_temptarget_lowers_sensitivity", false); mProfile.put("sensitivity_raises_target", SP.getBoolean(R.string.key_sensitivity_raises_target, SMBDefaults.sensitivity_raises_target)); From 457f43b1fe7298a649edc3c57f74840bf732b2b1 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 6 Dec 2019 18:25:09 +1300 Subject: [PATCH 023/316] Reuse Variable --- .../plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index bd142bfecd..5769196bb7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -338,7 +338,7 @@ public class DetermineBasalAdapterSMBJS { mMicrobolusAllowed = microBolusAllowed; mSMBAlwaysAllowed = advancedFiltering; - mCurrentTime = System.currentTimeMillis(); + mCurrentTime = now; } From f7b40854450c084648eb07c57e2b3cb6130bc597 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Fri, 6 Dec 2019 18:28:44 +1300 Subject: [PATCH 024/316] Round to 2DP --- .../androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java index 512c22d2e4..d404603f6e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/GlucoseStatus.java @@ -42,7 +42,7 @@ public class GlucoseStatus { public GlucoseStatus round() { this.glucose = Round.roundTo(this.glucose, 0.1); - this.noise = Round.roundTo(this.noise, 0.1); + this.noise = Round.roundTo(this.noise, 0.01); this.delta = Round.roundTo(this.delta, 0.01); this.avgdelta = Round.roundTo(this.avgdelta, 0.01); this.short_avgdelta = Round.roundTo(this.short_avgdelta, 0.01); From 3c7454884d8995c214772c3203ae3f90a4790c58 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 8 Dec 2019 17:04:39 +0100 Subject: [PATCH 025/316] protect MainActivity by biometrics --- .../main/java/info/nightscout/androidaps/MainActivity.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index eb3e7255ec..94f8ad429c 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -169,6 +169,12 @@ public class MainActivity extends NoSplashAppCompatActivity { disposable.clear(); } + @Override + protected void onResume() { + super.onResume(); + ProtectionCheck.INSTANCE.queryProtection(this, ProtectionCheck.Protection.APPLICATION, null, this::finish, this::finish); + } + private void setWakeLock() { boolean keepScreenOn = SP.getBoolean(R.string.key_keep_screen_on, false); if (keepScreenOn) From 66fd83ccb1e9a98f9cc1a6aec73e9d21098e3291 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 8 Dec 2019 18:01:52 +0100 Subject: [PATCH 026/316] biometrics bolus protection --- .../plugins/general/actions/ActionsFragment.kt | 7 ++++++- .../plugins/general/overview/OverviewFragment.java | 13 ++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index dfc06e6156..a0aa2fc066 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -26,6 +26,7 @@ import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatm import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.protection.ProtectionCheck import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.actions_fragment.* @@ -84,7 +85,11 @@ class ActionsFragment : Fragment() { }) } } - actions_fill.setOnClickListener { fragmentManager?.let { FillDialog().show(it, "FillDialog") } } + actions_fill.setOnClickListener { + activity?.let { activity -> + ProtectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { fragmentManager?.let { FillDialog().show(it, "FillDialog") } }) + } + } actions_historybrowser.setOnClickListener { startActivity(Intent(context, HistoryBrowseActivity::class.java)) } actions_tddstats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index f3b718743e..80cbcea992 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -118,6 +118,7 @@ import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SingleClickButton; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.ToastUtils; +import info.nightscout.androidaps.utils.protection.ProtectionCheck; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; @@ -825,11 +826,10 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, onClickAcceptTemp(); break; case R.id.overview_quickwizardbutton: - onClickQuickwizard(); + ProtectionCheck.INSTANCE.queryProtection(getActivity(), ProtectionCheck.Protection.BOLUS, this::onClickQuickwizard); break; case R.id.overview_wizardbutton: - WizardDialog wizardDialog = new WizardDialog(); - wizardDialog.show(manager, "WizardDialog"); + ProtectionCheck.INSTANCE.queryProtection(getActivity(), ProtectionCheck.Protection.BOLUS, () -> new WizardDialog().show(manager, "WizardDialog")); break; case R.id.overview_calibrationbutton: if (xdrip) { @@ -863,14 +863,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } break; case R.id.overview_treatmentbutton: - NewTreatmentDialog treatmentDialogFragment = new NewTreatmentDialog(); - treatmentDialogFragment.show(manager, "TreatmentDialog"); + ProtectionCheck.INSTANCE.queryProtection(getActivity(), ProtectionCheck.Protection.BOLUS, () -> new NewTreatmentDialog().show(manager, "TreatmentDialog")); break; case R.id.overview_insulinbutton: - new NewInsulinDialog().show(manager, "InsulinDialog"); + ProtectionCheck.INSTANCE.queryProtection(getActivity(), ProtectionCheck.Protection.BOLUS, () -> new NewInsulinDialog().show(manager, "InsulinDialog")); break; case R.id.overview_carbsbutton: - new NewCarbsDialog().show(manager, "CarbsDialog"); + ProtectionCheck.INSTANCE.queryProtection(getActivity(), ProtectionCheck.Protection.BOLUS, () -> new NewCarbsDialog().show(manager, "CarbsDialog")); break; case R.id.overview_pumpstatus: if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized()) From f2aa21ce82f05054a19f31970757c76f3c0975df Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 13 Dec 2019 02:12:19 +0100 Subject: [PATCH 027/316] some dagger code --- app/build.gradle | 18 +++ .../nightscout/androidaps/MainActivity.java | 2 + .../info/nightscout/androidaps/MainApp.java | 20 ++- .../dependencyInjection/ActivitiesModule.kt | 11 ++ .../dependencyInjection/AppComponent.kt | 18 +++ .../dependencyInjection/AppModule.kt | 31 +++++ .../androidaps/utils/sharedPreferences/SP.kt | 122 ++++++++++++++++++ 7 files changed, 219 insertions(+), 3 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt diff --git a/app/build.gradle b/app/build.gradle index 6d781a8962..3ed4ced0b1 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -13,6 +13,7 @@ buildscript { apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' +apply plugin: 'kotlin-kapt' apply plugin: 'com.google.gms.google-services' apply plugin: 'io.fabric' apply plugin: 'jacoco-android' @@ -208,6 +209,10 @@ android { } useLibrary "org.apache.http.legacy" + + configurations.all { + resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' + } } allprojects { @@ -312,6 +317,19 @@ dependencies { androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test:rules:1.3.0-alpha03' androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.2' + + /* Dagger2 - We are going to use dagger.android which includes + * support for Activity and fragment injection so we need to include + * the following dependencies */ + implementation 'com.google.dagger:dagger-android:2.25.2' + implementation 'com.google.dagger:dagger-android-support:2.25.2' + annotationProcessor 'com.google.dagger:dagger-compiler:2.25.2' + annotationProcessor 'com.google.dagger:dagger-android-processor:2.25.2' + kapt 'com.google.dagger:dagger-android-processor:2.25.2' + + /* Dagger2 - default dependency */ + kapt 'com.google.dagger:dagger-compiler:2.25.2' + } diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index ca6345b337..919e4abd10 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -37,6 +37,7 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import dagger.android.AndroidInjection; import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.PreferencesActivity; @@ -73,6 +74,7 @@ public class MainActivity extends NoSplashAppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { + AndroidInjection.inject(this); super.onCreate(savedInstanceState); Iconify.with(new FontAwesomeModule()); diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 4802655d3a..1a64511b9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -21,8 +21,11 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; +import dagger.android.AndroidInjector; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; @@ -51,8 +54,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.receivers.DBAccessRec import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin; import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; -import info.nightscout.androidaps.plugins.source.RandomBgPlugin; -import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; @@ -74,6 +75,7 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; +import info.nightscout.androidaps.plugins.source.RandomBgPlugin; import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin; import info.nightscout.androidaps.plugins.source.SourceEversensePlugin; import info.nightscout.androidaps.plugins.source.SourceGlimpPlugin; @@ -88,6 +90,7 @@ import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver; import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; import info.nightscout.androidaps.services.Intents; +import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.LocaleHelper; import io.fabric.sdk.android.Fabric; @@ -95,7 +98,7 @@ import io.fabric.sdk.android.Fabric; import static info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion; -public class MainApp extends Application { +public class MainApp extends Application implements HasAndroidInjector { private static Logger log = LoggerFactory.getLogger(L.CORE); private static KeepAliveReceiver keepAliveReceiver; @@ -120,9 +123,19 @@ public class MainApp extends Application { public static boolean devBranch; public static boolean engineeringMode; + AndroidInjector activityInjector; + + @Override + public AndroidInjector androidInjector() { + return activityInjector; + } + @Override public void onCreate() { super.onCreate(); + // Dagger injection + DaggerAppComponent.create().inject(this); + log.debug("onCreate"); sInstance = this; sResources = getResources(); @@ -442,4 +455,5 @@ public class MainApp extends Application { float scale = sResources.getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } + } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt new file mode 100644 index 0000000000..ee98184025 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.MainActivity + +@Module +abstract class ActivitiesModule { + @ContributesAndroidInjector + abstract fun contributeMainActivity(): MainActivity +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt new file mode 100644 index 0000000000..ca3b7a6026 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Component +import dagger.android.AndroidInjectionModule +import info.nightscout.androidaps.MainApp + + +@Component( + modules = [ + AndroidInjectionModule::class, + ActivitiesModule::class, + AppModule::class + ] +) + +interface AppComponent { + fun inject(mainApp: MainApp) +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt new file mode 100644 index 0000000000..facc1e1b5d --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.dependencyInjection + +import android.content.Context +import android.content.SharedPreferences +import android.preference.PreferenceManager +import dagger.Module +import dagger.Provides +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Singleton + + +@Module +class AppModule(private val application: MainApp) { + @Provides + @Singleton + fun provideApplication(): MainApp { + return application + } + + @Provides + fun provideContext(): Context { + return application.applicationContext + } + + @Provides + @Singleton + fun provideSharedPreferences(): SP { + return SP(PreferenceManager.getDefaultSharedPreferences(provideContext())) + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt new file mode 100644 index 0000000000..cc5cac8001 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt @@ -0,0 +1,122 @@ +package info.nightscout.androidaps.utils.sharedPreferences + +import android.content.SharedPreferences +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.utils.SafeParse +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by mike on 17.02.2017. + */ +@Singleton +class SP @Inject internal constructor(private val sharedPreferences: SharedPreferences) { + + fun getAll(): Map = sharedPreferences.all + + fun clear() = sharedPreferences.edit().clear().apply() + + fun contains(key: String): Boolean = sharedPreferences.contains(key) + + fun contains(resourceId: Int): Boolean = sharedPreferences.contains(MainApp.gs(resourceId)) + + fun remove(resourceID: Int) = + sharedPreferences.edit().remove(MainApp.gs(resourceID)).apply() + + fun remove(key: String) = + sharedPreferences.edit().remove(key).apply() + + fun getString(resourceID: Int, defaultValue: String): String = + sharedPreferences.getString(MainApp.gs(resourceID), defaultValue) + + fun getString(key: String, defaultValue: String): String = + sharedPreferences.getString(key, defaultValue) + + fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean { + return try { + sharedPreferences.getBoolean(MainApp.gs(resourceID), defaultValue) + } catch (e: Exception) { + defaultValue + } + } + + fun getBoolean(key: String, defaultValue: Boolean): Boolean { + return try { + sharedPreferences.getBoolean(key, defaultValue) + } catch (e: Exception) { + defaultValue + } + } + + fun getDouble(resourceID: Int, defaultValue: Double): Double = + SafeParse.stringToDouble(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + + fun getDouble(key: String, defaultValue: Double): Double = + SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())) + + fun getInt(resourceID: Int, defaultValue: Int): Int { + return try { + sharedPreferences.getInt(MainApp.gs(resourceID), defaultValue) + } catch (e: Exception) { + SafeParse.stringToInt(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + } + } + + fun getInt(key: String, defaultValue: Int): Int { + return try { + sharedPreferences.getInt(key, defaultValue) + } catch (e: Exception) { + SafeParse.stringToInt(sharedPreferences.getString(key, defaultValue.toString())) + } + } + + fun getLong(resourceID: Int, defaultValue: Long): Long { + return try { + sharedPreferences.getLong(MainApp.gs(resourceID), defaultValue) + } catch (e: Exception) { + SafeParse.stringToLong(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + } + } + + fun getLong(key: String, defaultValue: Long): Long { + return try { + sharedPreferences.getLong(key, defaultValue) + } catch (e: Exception) { + SafeParse.stringToLong(sharedPreferences.getString(key, defaultValue.toString())) + } + } + + fun putBoolean(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply() + + fun putBoolean(resourceID: Int, value: Boolean) = + sharedPreferences.edit().putBoolean(MainApp.gs(resourceID), value).apply() + + + fun putDouble(key: String, value: Double) = + sharedPreferences.edit().putString(key, java.lang.Double.toString(value)).apply() + + + fun putLong(key: String, value: Long) = + sharedPreferences.edit().putLong(key, value).apply() + + fun putLong(resourceID: Int, value: Long) = + sharedPreferences.edit().putLong(MainApp.gs(resourceID), value).apply() + + fun putInt(key: String, value: Int) = + sharedPreferences.edit().putInt(key, value).apply() + + fun putInt(resourceID: Int, value: Int) = + sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() + + fun incInt(resourceID: Int) { + val value = getInt(resourceID, 0) + 1 + sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() + } + + fun putString(resourceID: Int, value: String) = + sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply() + + fun putString(key: String, value: String) = + sharedPreferences.edit().putString(key, value).apply() + +} \ No newline at end of file From 3d1c1140b57023ffd240918aa4e4ddaeb894874a Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 21 Dec 2019 20:17:08 +0100 Subject: [PATCH 028/316] dagger2! --- .../info/nightscout/androidaps/MainApp.java | 47 +++++++++---------- .../dependencyInjection/AppComponent.kt | 27 +++++++---- .../dependencyInjection/AppModule.kt | 30 +++++------- .../androidaps/utils/sharedPreferences/SP.kt | 2 +- 4 files changed, 56 insertions(+), 50 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 1a64511b9b..b50ced81e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps; -import android.app.Application; import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.content.res.Resources; @@ -22,7 +21,7 @@ import java.io.File; import java.util.ArrayList; import dagger.android.AndroidInjector; -import dagger.android.HasAndroidInjector; +import dagger.android.DaggerApplication; import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; @@ -98,43 +97,34 @@ import io.fabric.sdk.android.Fabric; import static info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion; -public class MainApp extends Application implements HasAndroidInjector { - private static Logger log = LoggerFactory.getLogger(L.CORE); - private static KeepAliveReceiver keepAliveReceiver; +public class MainApp extends DaggerApplication { + static Logger log = LoggerFactory.getLogger(L.CORE); + static KeepAliveReceiver keepAliveReceiver; - private static MainApp sInstance; + static MainApp sInstance; public static Resources sResources; - private static FirebaseAnalytics mFirebaseAnalytics; + static FirebaseAnalytics mFirebaseAnalytics; - private static DatabaseHelper sDatabaseHelper = null; - private static ConstraintChecker sConstraintsChecker = null; + static DatabaseHelper sDatabaseHelper = null; + static ConstraintChecker sConstraintsChecker = null; - private static ArrayList pluginsList = null; + static ArrayList pluginsList = null; - private static DataReceiver dataReceiver = new DataReceiver(); - private static NSAlarmReceiver alarmReciever = new NSAlarmReceiver(); - private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver(); - private static DBAccessReceiver dbAccessReciever = new DBAccessReceiver(); - private LocalBroadcastManager lbm; + static DataReceiver dataReceiver = new DataReceiver(); + static NSAlarmReceiver alarmReciever = new NSAlarmReceiver(); + static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver(); + static DBAccessReceiver dbAccessReciever = new DBAccessReceiver(); + LocalBroadcastManager lbm; BroadcastReceiver btReceiver; TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver; public static boolean devBranch; public static boolean engineeringMode; - AndroidInjector activityInjector; - - @Override - public AndroidInjector androidInjector() { - return activityInjector; - } - @Override public void onCreate() { super.onCreate(); - // Dagger injection - DaggerAppComponent.create().inject(this); log.debug("onCreate"); sInstance = this; @@ -258,6 +248,15 @@ public class MainApp extends Application implements HasAndroidInjector { } } + @Override + protected AndroidInjector applicationInjector() { + + return DaggerAppComponent + .builder() + .application(this) + .build(); + } + private void registerLocalBroadcastReceiver() { lbm = LocalBroadcastManager.getInstance(this); lbm.registerReceiver(dataReceiver, new IntentFilter(Intents.ACTION_NEW_TREATMENT)); diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index ca3b7a6026..2168f9f8d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -1,18 +1,29 @@ package info.nightscout.androidaps.dependencyInjection +import android.app.Application +import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule +import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp +import javax.inject.Singleton - +@Singleton @Component( - modules = [ - AndroidInjectionModule::class, - ActivitiesModule::class, - AppModule::class - ] + modules = [ + AndroidInjectionModule::class, + ActivitiesModule::class, + AppModule::class + ] ) +interface AppComponent : AndroidInjector { -interface AppComponent { - fun inject(mainApp: MainApp) + @Component.Builder + interface Builder { + + @BindsInstance + fun application(application: Application): Builder + + fun build(): AppComponent + } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index facc1e1b5d..4f2ea5cd6b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -1,31 +1,27 @@ package info.nightscout.androidaps.dependencyInjection +import android.app.Application import android.content.Context -import android.content.SharedPreferences import android.preference.PreferenceManager +import dagger.Binds import dagger.Module import dagger.Provides -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Singleton - -@Module -class AppModule(private val application: MainApp) { - @Provides - @Singleton - fun provideApplication(): MainApp { - return application - } - - @Provides - fun provideContext(): Context { - return application.applicationContext - } +@Module(includes = [AppModule.AppBindings::class]) +class AppModule() { @Provides @Singleton - fun provideSharedPreferences(): SP { - return SP(PreferenceManager.getDefaultSharedPreferences(provideContext())) + fun provideSharedPreferences(context: Context): SP { + return SP(PreferenceManager.getDefaultSharedPreferences(context)) + } + + @Module + interface AppBindings { + + @Binds + fun bindContext(application: Application): Context } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt index cc5cac8001..a56f4736b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt @@ -10,7 +10,7 @@ import javax.inject.Singleton * Created by mike on 17.02.2017. */ @Singleton -class SP @Inject internal constructor(private val sharedPreferences: SharedPreferences) { +class SP @Inject constructor(private val sharedPreferences: SharedPreferences) { fun getAll(): Map = sharedPreferences.all From cd6dba8a3154cdabf537c08065c6ecbd47e74cca Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 23 Dec 2019 13:27:15 +0100 Subject: [PATCH 029/316] injecting insulin... plugin --- .../info/nightscout/androidaps/MainApp.java | 8 +- .../activities/MyPreferenceFragment.java | 157 ++++++++++++++++++ .../activities/PreferencesActivity.java | 142 ++-------------- .../dependencyInjection/ActivitiesModule.kt | 5 + .../dependencyInjection/AppComponent.kt | 1 + .../dependencyInjection/AppModule.kt | 5 +- .../dependencyInjection/FragmentsModule.kt | 11 ++ .../dependency-injection-todo.txt | 16 ++ .../insulin/InsulinOrefFreePeakPlugin.java | 49 ------ .../insulin/InsulinOrefFreePeakPlugin.kt | 45 +++++ .../androidaps/utils/ResourceHelper.kt | 22 +++ .../androidaps/utils/sharedPreferences/SP.kt | 144 ++++------------ .../utils/sharedPreferences/SPImpl.kt | 122 ++++++++++++++ 13 files changed, 433 insertions(+), 294 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index b50ced81e0..c4bfe32cbe 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -20,6 +20,8 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; +import javax.inject.Inject; + import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; import info.nightscout.androidaps.data.ConstraintChecker; @@ -92,6 +94,7 @@ import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.LocaleHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SPImpl; import io.fabric.sdk.android.Fabric; import static info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion; @@ -122,6 +125,9 @@ public class MainApp extends DaggerApplication { public static boolean devBranch; public static boolean engineeringMode; + @Inject + InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + @Override public void onCreate() { super.onCreate(); @@ -181,7 +187,7 @@ public class MainApp extends DaggerApplication { if (!Config.NSCLIENT) pluginsList.add(ActionsPlugin.INSTANCE); pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin()); - pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin()); + pluginsList.add(insulinOrefFreePeakPlugin); pluginsList.add(SensitivityOref0Plugin.getPlugin()); pluginsList.add(SensitivityAAPSPlugin.getPlugin()); pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin()); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java new file mode 100644 index 0000000000..533eaa0416 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java @@ -0,0 +1,157 @@ +package info.nightscout.androidaps.activities; + +import android.os.Bundle; +import android.preference.PreferenceFragment; + +import javax.inject.Inject; + +import dagger.android.AndroidInjection; +import dagger.android.AndroidInjector; +import dagger.android.DispatchingAndroidInjector; +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; +import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; +import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; +import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; +import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin; +import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin; +import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; +import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin; +import info.nightscout.androidaps.plugins.general.wear.WearPlugin; +import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; +import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; +import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin; +import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; +import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; +import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; +import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin; +import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin; +import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; +import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; +import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; +import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin; + +/** + * Created by adrian on 2019-12-23. + */ +public class MyPreferenceFragment extends PreferenceFragment implements HasAndroidInjector { + private Integer id; + + @Inject + DispatchingAndroidInjector androidInjector; + + @Inject + InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + + @Override + public void setArguments(Bundle args) { + super.setArguments(args); + id = args.getInt("id"); + } + + void addPreferencesFromResourceIfEnabled(PluginBase p, PluginType type) { + if (p.isEnabled(type) && p.getPreferencesId() != -1) + addPreferencesFromResource(p.getPreferencesId()); + } + + @Override + public AndroidInjector androidInjector() { + return androidInjector; + } + + @Override + public void onCreate(final Bundle savedInstanceState) { + AndroidInjection.inject(this); + super.onCreate(savedInstanceState); + + if (savedInstanceState != null && savedInstanceState.containsKey("id")) { + id = savedInstanceState.getInt("id"); + } + + AndroidInjection.inject(this); + + if (id != -1) { + addPreferencesFromResource(id); + } else { + + if (!Config.NSCLIENT) { + addPreferencesFromResource(R.xml.pref_password); + } + addPreferencesFromResource(R.xml.pref_general); + addPreferencesFromResource(R.xml.pref_age); + + addPreferencesFromResource(R.xml.pref_overview); + + addPreferencesFromResourceIfEnabled(SourceDexcomPlugin.INSTANCE, PluginType.BGSOURCE); + addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginType.CONSTRAINTS); + if (Config.APS) { + addPreferencesFromResourceIfEnabled(LoopPlugin.getPlugin(), PluginType.LOOP); + addPreferencesFromResourceIfEnabled(OpenAPSMAPlugin.getPlugin(), PluginType.APS); + addPreferencesFromResourceIfEnabled(OpenAPSAMAPlugin.getPlugin(), PluginType.APS); + addPreferencesFromResourceIfEnabled(OpenAPSSMBPlugin.getPlugin(), PluginType.APS); + } + + addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginType.SENSITIVITY); + addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), PluginType.SENSITIVITY); + addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY); + addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY); + + if (Config.PUMPDRIVERS) { + addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginType.PUMP); + addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP); + addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP); + addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP); + addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), PluginType.PUMP); + addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP); + addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP); + + if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE) + || DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE) + || DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE) + || DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) { + addPreferencesFromResource(R.xml.pref_danarprofile); + } + } + + if (!Config.NSCLIENT) { + addPreferencesFromResourceIfEnabled(VirtualPumpPlugin.getPlugin(), PluginType.PUMP); + } + + addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, PluginType.INSULIN); + + addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(TidepoolPlugin.INSTANCE, PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.INSTANCE, PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(AutomationPlugin.INSTANCE, PluginType.GENERAL); + + addPreferencesFromResource(R.xml.pref_others); + addPreferencesFromResource(R.xml.pref_datachoices); + + addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL); + } + + PreferencesActivity.initSummary(getPreferenceScreen()); + + for (PluginBase plugin : MainApp.getPluginsList()) { + plugin.preprocessPreferences(this); + } + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + outState.putInt("id", id); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java index c0dbf43527..4d859279d2 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -7,57 +7,39 @@ import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; -import android.preference.PreferenceFragment; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import java.util.Arrays; -import info.nightscout.androidaps.Config; +import javax.inject.Inject; + +import dagger.android.AndroidInjection; +import dagger.android.AndroidInjector; +import dagger.android.DispatchingAndroidInjector; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRebuildTabs; import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; -import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; -import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; -import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; -import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin; -import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin; -import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; -import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; -import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin; -import info.nightscout.androidaps.plugins.general.wear.WearPlugin; -import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; -import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin; -import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; -import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; -import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; -import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; -import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; -import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin; import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; -public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { +public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener, HasAndroidInjector { MyPreferenceFragment myPreferenceFragment; + @Inject + DispatchingAndroidInjector androidInjector; + @Override protected void onCreate(Bundle savedInstanceState) { + AndroidInjection.inject(this); setTheme(R.style.AppTheme_NoActionBar); super.onCreate(savedInstanceState); myPreferenceFragment = new MyPreferenceFragment(); @@ -68,6 +50,11 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this); } + @Override + public AndroidInjector androidInjector() { + return androidInjector; + } + @Override public void attachBaseContext(Context newBase) { super.attachBaseContext(LocaleHelper.INSTANCE.wrap(newBase)); @@ -144,101 +131,4 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre } } - public static class MyPreferenceFragment extends PreferenceFragment { - private Integer id; - - @Override - public void setArguments(Bundle args) { - super.setArguments(args); - id = args.getInt("id"); - } - - void addPreferencesFromResourceIfEnabled(PluginBase p, PluginType type) { - if (p.isEnabled(type) && p.getPreferencesId() != -1) - addPreferencesFromResource(p.getPreferencesId()); - } - - @Override - public void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - if (savedInstanceState != null && savedInstanceState.containsKey("id")) { - id = savedInstanceState.getInt("id"); - } - - if (id != -1) { - addPreferencesFromResource(id); - } else { - - if (!Config.NSCLIENT) { - addPreferencesFromResource(R.xml.pref_password); - } - addPreferencesFromResource(R.xml.pref_general); - addPreferencesFromResource(R.xml.pref_age); - - addPreferencesFromResource(R.xml.pref_overview); - - addPreferencesFromResourceIfEnabled(SourceDexcomPlugin.INSTANCE, PluginType.BGSOURCE); - addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginType.CONSTRAINTS); - if (Config.APS) { - addPreferencesFromResourceIfEnabled(LoopPlugin.getPlugin(), PluginType.LOOP); - addPreferencesFromResourceIfEnabled(OpenAPSMAPlugin.getPlugin(), PluginType.APS); - addPreferencesFromResourceIfEnabled(OpenAPSAMAPlugin.getPlugin(), PluginType.APS); - addPreferencesFromResourceIfEnabled(OpenAPSSMBPlugin.getPlugin(), PluginType.APS); - } - - addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginType.SENSITIVITY); - addPreferencesFromResourceIfEnabled(SensitivityWeightedAveragePlugin.getPlugin(), PluginType.SENSITIVITY); - addPreferencesFromResourceIfEnabled(SensitivityOref0Plugin.getPlugin(), PluginType.SENSITIVITY); - addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY); - - if (Config.PUMPDRIVERS) { - addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginType.PUMP); - addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP); - addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP); - addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP); - addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), PluginType.PUMP); - addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP); - addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP); - - if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE) - || DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE) - || DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE) - || DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) { - addPreferencesFromResource(R.xml.pref_danarprofile); - } - } - - if (!Config.NSCLIENT) { - addPreferencesFromResourceIfEnabled(VirtualPumpPlugin.getPlugin(), PluginType.PUMP); - } - - addPreferencesFromResourceIfEnabled(InsulinOrefFreePeakPlugin.getPlugin(), PluginType.INSULIN); - - addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(TidepoolPlugin.INSTANCE, PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.INSTANCE, PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(AutomationPlugin.INSTANCE, PluginType.GENERAL); - - addPreferencesFromResource(R.xml.pref_others); - addPreferencesFromResource(R.xml.pref_datachoices); - - addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL); - } - - initSummary(getPreferenceScreen()); - - for (PluginBase plugin : MainApp.getPluginsList()) { - plugin.preprocessPreferences(this); - } - } - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - outState.putInt("id", id); - } - } } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt index ee98184025..cb3d910e5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -3,9 +3,14 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.MainActivity +import info.nightscout.androidaps.activities.PreferencesActivity @Module abstract class ActivitiesModule { + @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity + + @ContributesAndroidInjector + abstract fun contributesPreferencesActivity(): PreferencesActivity } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 2168f9f8d0..cb6fc27cb9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -13,6 +13,7 @@ import javax.inject.Singleton modules = [ AndroidInjectionModule::class, ActivitiesModule::class, + FragmentsModule::class, AppModule::class ] ) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 4f2ea5cd6b..48ab314606 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -7,15 +7,16 @@ import dagger.Binds import dagger.Module import dagger.Provides import info.nightscout.androidaps.utils.sharedPreferences.SP +import info.nightscout.androidaps.utils.sharedPreferences.SPImpl import javax.inject.Singleton @Module(includes = [AppModule.AppBindings::class]) -class AppModule() { +class AppModule { @Provides @Singleton fun provideSharedPreferences(context: Context): SP { - return SP(PreferenceManager.getDefaultSharedPreferences(context)) + return SPImpl(PreferenceManager.getDefaultSharedPreferences(context)) } @Module diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt new file mode 100644 index 0000000000..db9a555388 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.activities.MyPreferenceFragment + +@Module +abstract class FragmentsModule { + @ContributesAndroidInjector + abstract fun contributesPreferencesFragment(): MyPreferenceFragment +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt new file mode 100644 index 0000000000..6ee0c902dc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt @@ -0,0 +1,16 @@ +PreferenceActivity is an Example how to make an Activity injectable. +We might undo that as we don't actually have us inject things. + +MyPreferencesFragment is an injectable Fragment. Here we actually have Dagger2 provide us an InsulinOrefFreePeakPlugin instance. + +If we use multiple Fragments, we should generate a base-class. Then we only have to add a "provides***Fragment" to the FragmentsModule and derive from that class. + +InsulinOrefFreePeakPlugin is an example how to get things injected via the constructor. +You could call "new InsulinOrefFreePeakPlugin(new SPImpl(SPImpl(PreferenceManager.getDefaultSharedPreferences(context))), new ResourceHelper())"... but Dagger will resolve that for you in MainApp. :) + +SPImpl is an example how to bind an implementation to an Interface via Dagger. + +ResourceHelper is an example how to generate simple classes that Dagger can auto-resolve how to inject them. No need for a provider here. +ResourceHelper might have a weak reference at some point and not a static dependency on MainApp... but at least we reduced the static dependencies within a plugin. + +In order to Test: Any dependency of InsulinOrefFreePeakPlugin is passed via the constructor. Instead of static mocking MainApp you now can Mock ResourceHelper with a very small interface. \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.java deleted file mode 100644 index 3d32d2317b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.java +++ /dev/null @@ -1,49 +0,0 @@ -package info.nightscout.androidaps.plugins.insulin; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by adrian on 14/08/17. - */ - -public class InsulinOrefFreePeakPlugin extends InsulinOrefBasePlugin { - - private static InsulinOrefFreePeakPlugin plugin = null; - - public static InsulinOrefFreePeakPlugin getPlugin() { - if (plugin == null) - plugin = new InsulinOrefFreePeakPlugin(); - return plugin; - } - - private static final int DEFAULT_PEAK = 75; - - private InsulinOrefFreePeakPlugin() { - super(); - pluginDescription - .pluginName(R.string.free_peak_oref) - .preferencesId(R.xml.pref_insulinoreffreepeak) - .description(R.string.description_insulin_free_peak); - } - - @Override - public int getId() { - return OREF_FREE_PEAK; - } - - public String getFriendlyName() { - return MainApp.gs(R.string.free_peak_oref); - } - - @Override - public String commentStandardText() { - return MainApp.gs(R.string.insulin_peak_time) + ": " + getPeak(); - } - - @Override - int getPeak() { - return SP.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt new file mode 100644 index 0000000000..6707fd7873 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.plugins.insulin + +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.InsulinInterface +import info.nightscout.androidaps.utils.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by adrian on 14/08/17. + */ +@Singleton +class InsulinOrefFreePeakPlugin @Inject constructor( + private val sp: SP, + private val resourceHelper: ResourceHelper +) : InsulinOrefBasePlugin() { + + override fun getId(): Int { + return InsulinInterface.OREF_FREE_PEAK + } + + override fun getFriendlyName(): String { + return resourceHelper.gs(R.string.free_peak_oref) + } + + public override fun commentStandardText(): String { + return resourceHelper.gs(R.string.insulin_peak_time) + ": " + peak + } + + public override fun getPeak(): Int { + return sp.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK) + } + + companion object { + private const val DEFAULT_PEAK = 75 + } + + init { + pluginDescription + .pluginName(R.string.free_peak_oref) + .preferencesId(R.xml.pref_insulinoreffreepeak) + .description(R.string.description_insulin_free_peak) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt new file mode 100644 index 0000000000..655c319170 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.utils + +import androidx.annotation.ColorRes +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes +import info.nightscout.androidaps.MainApp +import javax.inject.Inject + +/** + * Created by adrian on 2019-12-23. + */ +class ResourceHelper @Inject constructor() { + + fun gs(@StringRes id: Int): String = MainApp.sResources.getString(id) + + fun gs(@StringRes id: Int, vararg args: Any?) = MainApp.sResources.getString(id, *args) + + fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String = + MainApp.sResources.getQuantityString(id, quantity, *args) + + fun gc(@ColorRes id: Int): Int = MainApp.sResources.getColor(id) +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt index a56f4736b1..e1bb9e9373 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt @@ -1,122 +1,34 @@ package info.nightscout.androidaps.utils.sharedPreferences -import android.content.SharedPreferences -import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.utils.SafeParse -import javax.inject.Inject -import javax.inject.Singleton - /** - * Created by mike on 17.02.2017. + * Created by adrian on 2019-12-23. */ -@Singleton -class SP @Inject constructor(private val sharedPreferences: SharedPreferences) { - - fun getAll(): Map = sharedPreferences.all - - fun clear() = sharedPreferences.edit().clear().apply() - - fun contains(key: String): Boolean = sharedPreferences.contains(key) - - fun contains(resourceId: Int): Boolean = sharedPreferences.contains(MainApp.gs(resourceId)) - - fun remove(resourceID: Int) = - sharedPreferences.edit().remove(MainApp.gs(resourceID)).apply() - - fun remove(key: String) = - sharedPreferences.edit().remove(key).apply() - - fun getString(resourceID: Int, defaultValue: String): String = - sharedPreferences.getString(MainApp.gs(resourceID), defaultValue) - - fun getString(key: String, defaultValue: String): String = - sharedPreferences.getString(key, defaultValue) - - fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean { - return try { - sharedPreferences.getBoolean(MainApp.gs(resourceID), defaultValue) - } catch (e: Exception) { - defaultValue - } - } - - fun getBoolean(key: String, defaultValue: Boolean): Boolean { - return try { - sharedPreferences.getBoolean(key, defaultValue) - } catch (e: Exception) { - defaultValue - } - } - - fun getDouble(resourceID: Int, defaultValue: Double): Double = - SafeParse.stringToDouble(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) - - fun getDouble(key: String, defaultValue: Double): Double = - SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())) - - fun getInt(resourceID: Int, defaultValue: Int): Int { - return try { - sharedPreferences.getInt(MainApp.gs(resourceID), defaultValue) - } catch (e: Exception) { - SafeParse.stringToInt(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) - } - } - - fun getInt(key: String, defaultValue: Int): Int { - return try { - sharedPreferences.getInt(key, defaultValue) - } catch (e: Exception) { - SafeParse.stringToInt(sharedPreferences.getString(key, defaultValue.toString())) - } - } - - fun getLong(resourceID: Int, defaultValue: Long): Long { - return try { - sharedPreferences.getLong(MainApp.gs(resourceID), defaultValue) - } catch (e: Exception) { - SafeParse.stringToLong(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) - } - } - - fun getLong(key: String, defaultValue: Long): Long { - return try { - sharedPreferences.getLong(key, defaultValue) - } catch (e: Exception) { - SafeParse.stringToLong(sharedPreferences.getString(key, defaultValue.toString())) - } - } - - fun putBoolean(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply() - - fun putBoolean(resourceID: Int, value: Boolean) = - sharedPreferences.edit().putBoolean(MainApp.gs(resourceID), value).apply() - - - fun putDouble(key: String, value: Double) = - sharedPreferences.edit().putString(key, java.lang.Double.toString(value)).apply() - - - fun putLong(key: String, value: Long) = - sharedPreferences.edit().putLong(key, value).apply() - - fun putLong(resourceID: Int, value: Long) = - sharedPreferences.edit().putLong(MainApp.gs(resourceID), value).apply() - - fun putInt(key: String, value: Int) = - sharedPreferences.edit().putInt(key, value).apply() - - fun putInt(resourceID: Int, value: Int) = - sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() - - fun incInt(resourceID: Int) { - val value = getInt(resourceID, 0) + 1 - sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() - } - - fun putString(resourceID: Int, value: String) = - sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply() - - fun putString(key: String, value: String) = - sharedPreferences.edit().putString(key, value).apply() +interface SP { + fun getAll(): Map + fun clear() + fun contains(key: String): Boolean + fun contains(resourceId: Int): Boolean + fun remove(resourceID: Int) + fun remove(key: String) + fun getString(resourceID: Int, defaultValue: String): String + fun getString(key: String, defaultValue: String): String + fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean + fun getBoolean(key: String, defaultValue: Boolean): Boolean + fun getDouble(resourceID: Int, defaultValue: Double): Double + fun getDouble(key: String, defaultValue: Double): Double + fun getInt(resourceID: Int, defaultValue: Int): Int + fun getInt(key: String, defaultValue: Int): Int + fun getLong(resourceID: Int, defaultValue: Long): Long + fun getLong(key: String, defaultValue: Long): Long + fun putBoolean(key: String, value: Boolean) + fun putBoolean(resourceID: Int, value: Boolean) + fun putDouble(key: String, value: Double) + fun putLong(key: String, value: Long) + fun putLong(resourceID: Int, value: Long) + fun putInt(key: String, value: Int) + fun putInt(resourceID: Int, value: Int) + fun incInt(resourceID: Int) + fun putString(resourceID: Int, value: String) + fun putString(key: String, value: String) } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt new file mode 100644 index 0000000000..5c73a56967 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt @@ -0,0 +1,122 @@ +package info.nightscout.androidaps.utils.sharedPreferences + +import android.content.SharedPreferences +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.utils.SafeParse +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by mike on 17.02.2017. + */ +@Singleton +class SPImpl @Inject constructor(private val sharedPreferences: SharedPreferences) : SP { + + override fun getAll(): Map = sharedPreferences.all + + override fun clear() = sharedPreferences.edit().clear().apply() + + override fun contains(key: String): Boolean = sharedPreferences.contains(key) + + override fun contains(resourceId: Int): Boolean = sharedPreferences.contains(MainApp.gs(resourceId)) + + override fun remove(resourceID: Int) = + sharedPreferences.edit().remove(MainApp.gs(resourceID)).apply() + + override fun remove(key: String) = + sharedPreferences.edit().remove(key).apply() + + override fun getString(resourceID: Int, defaultValue: String): String = + sharedPreferences.getString(MainApp.gs(resourceID), defaultValue) + + override fun getString(key: String, defaultValue: String): String = + sharedPreferences.getString(key, defaultValue) + + override fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean { + return try { + sharedPreferences.getBoolean(MainApp.gs(resourceID), defaultValue) + } catch (e: Exception) { + defaultValue + } + } + + override fun getBoolean(key: String, defaultValue: Boolean): Boolean { + return try { + sharedPreferences.getBoolean(key, defaultValue) + } catch (e: Exception) { + defaultValue + } + } + + override fun getDouble(resourceID: Int, defaultValue: Double): Double = + SafeParse.stringToDouble(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + + override fun getDouble(key: String, defaultValue: Double): Double = + SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())) + + override fun getInt(resourceID: Int, defaultValue: Int): Int { + return try { + sharedPreferences.getInt(MainApp.gs(resourceID), defaultValue) + } catch (e: Exception) { + SafeParse.stringToInt(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + } + } + + override fun getInt(key: String, defaultValue: Int): Int { + return try { + sharedPreferences.getInt(key, defaultValue) + } catch (e: Exception) { + SafeParse.stringToInt(sharedPreferences.getString(key, defaultValue.toString())) + } + } + + override fun getLong(resourceID: Int, defaultValue: Long): Long { + return try { + sharedPreferences.getLong(MainApp.gs(resourceID), defaultValue) + } catch (e: Exception) { + SafeParse.stringToLong(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + } + } + + override fun getLong(key: String, defaultValue: Long): Long { + return try { + sharedPreferences.getLong(key, defaultValue) + } catch (e: Exception) { + SafeParse.stringToLong(sharedPreferences.getString(key, defaultValue.toString())) + } + } + + override fun putBoolean(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply() + + override fun putBoolean(resourceID: Int, value: Boolean) = + sharedPreferences.edit().putBoolean(MainApp.gs(resourceID), value).apply() + + + override fun putDouble(key: String, value: Double) = + sharedPreferences.edit().putString(key, java.lang.Double.toString(value)).apply() + + + override fun putLong(key: String, value: Long) = + sharedPreferences.edit().putLong(key, value).apply() + + override fun putLong(resourceID: Int, value: Long) = + sharedPreferences.edit().putLong(MainApp.gs(resourceID), value).apply() + + override fun putInt(key: String, value: Int) = + sharedPreferences.edit().putInt(key, value).apply() + + override fun putInt(resourceID: Int, value: Int) = + sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() + + override fun incInt(resourceID: Int) { + val value = getInt(resourceID, 0) + 1 + sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() + } + + override fun putString(resourceID: Int, value: String) = + sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply() + + override fun putString(key: String, value: String) = + sharedPreferences.edit().putString(key, value).apply() + +} \ No newline at end of file From 143a9f87494bc6c608a20ae23a7109b168f021a5 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Wed, 25 Dec 2019 12:19:26 +0100 Subject: [PATCH 030/316] dagger testing --- .../androidaps/utils/ResourceHelper.kt | 2 +- .../insulin/InsulinOrefFreePeakPluginTest.kt | 60 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt index 655c319170..a718a0803e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt @@ -9,7 +9,7 @@ import javax.inject.Inject /** * Created by adrian on 2019-12-23. */ -class ResourceHelper @Inject constructor() { +open class ResourceHelper @Inject constructor() { fun gs(@StringRes id: Int): String = MainApp.sResources.getString(id) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt new file mode 100644 index 0000000000..806c8e0379 --- /dev/null +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt @@ -0,0 +1,60 @@ +package info.nightscout.androidaps.plugins.insulin + +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import junit.framework.Assert.assertEquals +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.mockito.ArgumentMatchers.anyInt +import org.mockito.ArgumentMatchers.eq +import org.mockito.Mock +import org.mockito.Mockito +import org.mockito.Mockito.`when` +import org.mockito.junit.MockitoJUnit +import org.mockito.junit.MockitoRule + +/** + * Created by adrian on 2019-12-25. + */ + +class InsulinOrefFreePeakPluginTest { + + + // TODO: move to a base class + // Add a JUnit rule that will setup the @Mock annotated vars and log. + // Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method. + @get:Rule + val mockitoRule: MockitoRule = MockitoJUnit.rule() + + lateinit var sut: InsulinOrefFreePeakPlugin + + @Mock + lateinit var sp: SP + + @Mock + lateinit var resourceHelper: ResourceHelper + + @Before + fun setup() { + sut = InsulinOrefFreePeakPlugin(sp, resourceHelper) + } + + @Test + fun `simple peak test`() { + `when`(sp.getInt(eq(R.string.key_insulin_oref_peak), anyInt())).thenReturn(90) + assertEquals(90, sut.peak) + } + + // Workaround for Kotlin nullability. TODO: move to a base class + // https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791 + // https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin + private fun anyObject(): T { + Mockito.any() + return uninitialized() + } + + private fun uninitialized(): T = null as T + +} \ No newline at end of file From 48e8888b82756ceb8131c2e57ef26f60f5689afb Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Wed, 25 Dec 2019 10:11:14 +0100 Subject: [PATCH 031/316] Firebase follow privacy setting --- app/src/main/java/info/nightscout/androidaps/MainApp.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 7d743cbf7d..370ce47b22 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -162,7 +162,7 @@ public class MainApp extends DaggerApplication { registerActivityLifecycleCallbacks(ActivityMonitor.INSTANCE); mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); - mFirebaseAnalytics.setAnalyticsCollectionEnabled(!Boolean.getBoolean("disableFirebase")); + mFirebaseAnalytics.setAnalyticsCollectionEnabled(!Boolean.getBoolean("disableFirebase") && FabricPrivacy.fabricEnabled()); JodaTimeAndroid.init(this); From 895b32d8f36a0059f56824d358407f9a56d3a0bb Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 26 Dec 2019 15:12:12 +0100 Subject: [PATCH 032/316] SPImplementation cleanup --- .../dependencyInjection/AppModule.kt | 4 +-- .../androidaps/utils/sharedPreferences/SP.kt | 25 ++++++++------- .../{SPImpl.kt => SPImplementation.kt} | 32 +++++++++---------- 3 files changed, 31 insertions(+), 30 deletions(-) rename app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/{SPImpl.kt => SPImplementation.kt} (74%) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 48ab314606..f55ee48ae9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -7,7 +7,7 @@ import dagger.Binds import dagger.Module import dagger.Provides import info.nightscout.androidaps.utils.sharedPreferences.SP -import info.nightscout.androidaps.utils.sharedPreferences.SPImpl +import info.nightscout.androidaps.utils.sharedPreferences.SPImplementation import javax.inject.Singleton @Module(includes = [AppModule.AppBindings::class]) @@ -16,7 +16,7 @@ class AppModule { @Provides @Singleton fun provideSharedPreferences(context: Context): SP { - return SPImpl(PreferenceManager.getDefaultSharedPreferences(context)) + return SPImplementation(PreferenceManager.getDefaultSharedPreferences(context)) } @Module diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt index e1bb9e9373..ce1c12f8a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SP.kt @@ -1,34 +1,37 @@ package info.nightscout.androidaps.utils.sharedPreferences +import androidx.annotation.StringRes + /** * Created by adrian on 2019-12-23. */ interface SP { + fun getAll(): Map fun clear() fun contains(key: String): Boolean fun contains(resourceId: Int): Boolean - fun remove(resourceID: Int) + fun remove(@StringRes resourceID: Int) fun remove(key: String) - fun getString(resourceID: Int, defaultValue: String): String + fun getString(@StringRes resourceID: Int, defaultValue: String): String fun getString(key: String, defaultValue: String): String - fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean + fun getBoolean(@StringRes resourceID: Int, defaultValue: Boolean): Boolean fun getBoolean(key: String, defaultValue: Boolean): Boolean - fun getDouble(resourceID: Int, defaultValue: Double): Double + fun getDouble(@StringRes resourceID: Int, defaultValue: Double): Double fun getDouble(key: String, defaultValue: Double): Double - fun getInt(resourceID: Int, defaultValue: Int): Int + fun getInt(@StringRes resourceID: Int, defaultValue: Int): Int fun getInt(key: String, defaultValue: Int): Int - fun getLong(resourceID: Int, defaultValue: Long): Long + fun getLong(@StringRes resourceID: Int, defaultValue: Long): Long fun getLong(key: String, defaultValue: Long): Long fun putBoolean(key: String, value: Boolean) - fun putBoolean(resourceID: Int, value: Boolean) + fun putBoolean(@StringRes resourceID: Int, value: Boolean) fun putDouble(key: String, value: Double) fun putLong(key: String, value: Long) - fun putLong(resourceID: Int, value: Long) + fun putLong(@StringRes resourceID: Int, value: Long) fun putInt(key: String, value: Int) - fun putInt(resourceID: Int, value: Int) - fun incInt(resourceID: Int) - fun putString(resourceID: Int, value: String) + fun putInt(@StringRes resourceID: Int, value: Int) + fun incInt(@StringRes resourceID: Int) + fun putString(@StringRes resourceID: Int, value: String) fun putString(key: String, value: String) } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt similarity index 74% rename from app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt rename to app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt index 5c73a56967..3aca8915ec 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImpl.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/sharedPreferences/SPImplementation.kt @@ -10,7 +10,7 @@ import javax.inject.Singleton * Created by mike on 17.02.2017. */ @Singleton -class SPImpl @Inject constructor(private val sharedPreferences: SharedPreferences) : SP { +class SPImplementation @Inject constructor(private val sharedPreferences: SharedPreferences) : SP { override fun getAll(): Map = sharedPreferences.all @@ -21,16 +21,16 @@ class SPImpl @Inject constructor(private val sharedPreferences: SharedPreference override fun contains(resourceId: Int): Boolean = sharedPreferences.contains(MainApp.gs(resourceId)) override fun remove(resourceID: Int) = - sharedPreferences.edit().remove(MainApp.gs(resourceID)).apply() + sharedPreferences.edit().remove(MainApp.gs(resourceID)).apply() override fun remove(key: String) = - sharedPreferences.edit().remove(key).apply() + sharedPreferences.edit().remove(key).apply() override fun getString(resourceID: Int, defaultValue: String): String = - sharedPreferences.getString(MainApp.gs(resourceID), defaultValue) + sharedPreferences.getString(MainApp.gs(resourceID), defaultValue) ?: defaultValue override fun getString(key: String, defaultValue: String): String = - sharedPreferences.getString(key, defaultValue) + sharedPreferences.getString(key, defaultValue) ?: defaultValue override fun getBoolean(resourceID: Int, defaultValue: Boolean): Boolean { return try { @@ -49,10 +49,10 @@ class SPImpl @Inject constructor(private val sharedPreferences: SharedPreference } override fun getDouble(resourceID: Int, defaultValue: Double): Double = - SafeParse.stringToDouble(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) + SafeParse.stringToDouble(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())) override fun getDouble(key: String, defaultValue: Double): Double = - SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())) + SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())) override fun getInt(resourceID: Int, defaultValue: Int): Int { return try { @@ -89,24 +89,22 @@ class SPImpl @Inject constructor(private val sharedPreferences: SharedPreference override fun putBoolean(key: String, value: Boolean) = sharedPreferences.edit().putBoolean(key, value).apply() override fun putBoolean(resourceID: Int, value: Boolean) = - sharedPreferences.edit().putBoolean(MainApp.gs(resourceID), value).apply() - + sharedPreferences.edit().putBoolean(MainApp.gs(resourceID), value).apply() override fun putDouble(key: String, value: Double) = - sharedPreferences.edit().putString(key, java.lang.Double.toString(value)).apply() - + sharedPreferences.edit().putString(key, java.lang.Double.toString(value)).apply() override fun putLong(key: String, value: Long) = - sharedPreferences.edit().putLong(key, value).apply() + sharedPreferences.edit().putLong(key, value).apply() override fun putLong(resourceID: Int, value: Long) = - sharedPreferences.edit().putLong(MainApp.gs(resourceID), value).apply() + sharedPreferences.edit().putLong(MainApp.gs(resourceID), value).apply() override fun putInt(key: String, value: Int) = - sharedPreferences.edit().putInt(key, value).apply() + sharedPreferences.edit().putInt(key, value).apply() override fun putInt(resourceID: Int, value: Int) = - sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() + sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply() override fun incInt(resourceID: Int) { val value = getInt(resourceID, 0) + 1 @@ -114,9 +112,9 @@ class SPImpl @Inject constructor(private val sharedPreferences: SharedPreference } override fun putString(resourceID: Int, value: String) = - sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply() + sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply() override fun putString(key: String, value: String) = - sharedPreferences.edit().putString(key, value).apply() + sharedPreferences.edit().putString(key, value).apply() } \ No newline at end of file From 3654b0b66f454c46fc5e9669d485f09522bc3eac Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 26 Dec 2019 17:50:16 +0100 Subject: [PATCH 033/316] ResourceHelper --- .../dependencyInjection/AppComponent.kt | 3 +-- .../dependencyInjection/AppModule.kt | 12 ++++++++-- .../insulin/InsulinOrefFreePeakPlugin.kt | 4 ++-- .../androidaps/utils/ResourceHelper.kt | 22 ------------------ .../utils/resources/ResourceHelper.kt | 12 ++++++++++ .../resources/ResourceHelperImplementation.kt | 23 +++++++++++++++++++ .../insulin/InsulinOrefFreePeakPluginTest.kt | 4 ++-- 7 files changed, 50 insertions(+), 30 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index cb6fc27cb9..edf202b5ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.dependencyInjection -import android.app.Application import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule @@ -23,7 +22,7 @@ interface AppComponent : AndroidInjector { interface Builder { @BindsInstance - fun application(application: Application): Builder + fun application(mainApp: MainApp): Builder fun build(): AppComponent } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index f55ee48ae9..367f228ed3 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -1,11 +1,13 @@ package info.nightscout.androidaps.dependencyInjection -import android.app.Application import android.content.Context import android.preference.PreferenceManager import dagger.Binds import dagger.Module import dagger.Provides +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SPImplementation import javax.inject.Singleton @@ -19,10 +21,16 @@ class AppModule { return SPImplementation(PreferenceManager.getDefaultSharedPreferences(context)) } + @Provides + @Singleton + fun provideResources(mainApp: MainApp): ResourceHelper { + return ResourceHelperImplementation(mainApp) + } + @Module interface AppBindings { @Binds - fun bindContext(application: Application): Context + fun bindContext(mainApp: MainApp): Context } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index 6707fd7873..ba6773d324 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.insulin import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface -import info.nightscout.androidaps.utils.ResourceHelper +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton @@ -21,7 +21,7 @@ class InsulinOrefFreePeakPlugin @Inject constructor( } override fun getFriendlyName(): String { - return resourceHelper.gs(R.string.free_peak_oref) + return resourceHelper.gs(R.string.free_peak_oref) ?: "" } public override fun commentStandardText(): String { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt deleted file mode 100644 index a718a0803e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/ResourceHelper.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.utils - -import androidx.annotation.ColorRes -import androidx.annotation.PluralsRes -import androidx.annotation.StringRes -import info.nightscout.androidaps.MainApp -import javax.inject.Inject - -/** - * Created by adrian on 2019-12-23. - */ -open class ResourceHelper @Inject constructor() { - - fun gs(@StringRes id: Int): String = MainApp.sResources.getString(id) - - fun gs(@StringRes id: Int, vararg args: Any?) = MainApp.sResources.getString(id, *args) - - fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String = - MainApp.sResources.getQuantityString(id, quantity, *args) - - fun gc(@ColorRes id: Int): Int = MainApp.sResources.getColor(id) -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt new file mode 100644 index 0000000000..2eb62f6ee6 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.utils.resources + +import androidx.annotation.ColorRes +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes + +interface ResourceHelper { + fun gs(@StringRes id: Int): String? + fun gs(@StringRes id: Int, vararg args: Any?): String? + fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String? + fun gc(@ColorRes id: Int): Int? +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt new file mode 100644 index 0000000000..08660d3745 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.utils.resources + +import androidx.annotation.ColorRes +import androidx.annotation.PluralsRes +import androidx.annotation.StringRes +import androidx.core.content.ContextCompat +import info.nightscout.androidaps.MainApp +import javax.inject.Inject + +/** + * Created by adrian on 2019-12-23. + */ +class ResourceHelperImplementation @Inject constructor(private val mainApp: MainApp) : ResourceHelper { + + override fun gs(@StringRes id: Int): String? = mainApp.getString(id) + + override fun gs(@StringRes id: Int, vararg args: Any?): String? = mainApp.getString(id, *args) + + override fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String? = + mainApp.resources.getQuantityString(id, quantity, *args) + + override fun gc(@ColorRes id: Int): Int = ContextCompat.getColor(mainApp, id) +} \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt index 806c8e0379..a0e5b7954c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.insulin import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.ResourceHelper +import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP import junit.framework.Assert.assertEquals import org.junit.Before @@ -34,7 +34,7 @@ class InsulinOrefFreePeakPluginTest { lateinit var sp: SP @Mock - lateinit var resourceHelper: ResourceHelper + lateinit var resourceHelper: ResourceHelperImplementation @Before fun setup() { From 12253007f1ce744379056682e434b4c6e33195c7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 26 Dec 2019 23:26:00 +0100 Subject: [PATCH 034/316] ProfileFunction WIP --- .../activities/PreferencesActivity.java | 1 - .../dependencyInjection/AppModule.kt | 8 ++ .../androidaps/dialogs/ProfileSwitchDialog.kt | 2 +- .../androidaps/dialogs/TempBasalDialog.kt | 4 +- .../androidaps/dialogs/WizardDialog.kt | 6 +- .../configBuilder/ConfigBuilderPlugin.java | 12 ++- .../plugins/configBuilder/ProfileFunction.kt | 19 +++++ .../ProfileFunctionImplementation.kt | 80 +++++++++++++++++++ .../configBuilder/ProfileFunctions.java | 34 +++++--- .../general/actions/ActionsFragment.kt | 2 +- .../actions/ActionProfileSwitch.java | 2 +- .../actions/ActionProfileSwitchPercent.java | 2 +- .../automation/dialogs/EditActionDialog.kt | 8 +- .../Dialogs/NewNSTreatmentDialog.java | 2 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 16 ++-- .../general/wear/ActionStringHandler.java | 2 +- .../plugins/profile/ns/NSProfileFragment.kt | 4 +- .../androidaps/receivers/KeepAliveReceiver.kt | 2 +- .../androidaps/utils/BolusWizard.kt | 2 +- .../nightscout/androidaps/utils/OKDialog.kt | 2 - 20 files changed, 170 insertions(+), 40 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java index 3884954f3b..359c14cd6f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -25,7 +25,6 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRebuildTabs; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.SP; diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 367f228ed3..2b266afc22 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -6,6 +6,8 @@ import dagger.Binds import dagger.Module import dagger.Provides import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -21,6 +23,12 @@ class AppModule { return SPImplementation(PreferenceManager.getDefaultSharedPreferences(context)) } + @Provides + @Singleton + fun provideProfileFunction(sp : SP): ProfileFunction { + return ProfileFunctionImplementation(sp) + } + @Provides @Singleton fun provideResources(mainApp: MainApp): ResourceHelper { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 5df248593c..172cd24195 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -97,7 +97,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { - ProfileFunctions.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) + ProfileFunctions.getInstance().doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt index dc31349650..77c7df319f 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -43,7 +43,7 @@ class TempBasalDialog : DialogFragmentWithDate() { super.onViewCreated(view, savedInstanceState) val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return - val profile = ProfileFunctions.getInstance().profile ?: return + val profile = ProfileFunctions.getInstance().getProfile() ?: return val maxTempPercent = pumpDescription.maxTempPercent.toDouble() val tempPercentStep = pumpDescription.tempPercentStep.toDouble() @@ -73,7 +73,7 @@ class TempBasalDialog : DialogFragmentWithDate() { var percent = 0 var absolute = 0.0 val durationInMinutes = SafeParse.stringToInt(actions_tempbasal_duration.text) - val profile = ProfileFunctions.getInstance().profile ?: return false + val profile = ProfileFunctions.getInstance().getProfile() ?: return false val actions: LinkedList = LinkedList() if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index c84bd4a0b6..d48c28337b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -194,7 +194,7 @@ class WizardDialog : DialogFragment() { } private fun initDialog() { - val profile = ProfileFunctions.getInstance().profile + val profile = ProfileFunctions.getInstance().getProfile() val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile if (profile == null || profileStore == null) { @@ -249,8 +249,8 @@ class WizardDialog : DialogFragment() { var profileName = treatments_wizard_profile.selectedItem.toString() val specificProfile: Profile? if (profileName == MainApp.gs(R.string.active)) { - specificProfile = ProfileFunctions.getInstance().profile - profileName = ProfileFunctions.getInstance().profileName + specificProfile = ProfileFunctions.getInstance().getProfile() + profileName = ProfileFunctions.getInstance().getProfileName() ?: return } else specificProfile = profileStore.getSpecificProfile(profileName) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index f43513fbf5..14615060d9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -2,11 +2,14 @@ package info.nightscout.androidaps.plugins.configBuilder; import androidx.annotation.Nullable; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; +import javax.inject.Inject; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventAppInitialized; @@ -22,6 +25,7 @@ import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; +import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; @@ -53,6 +57,9 @@ public class ConfigBuilderPlugin extends PluginBase { private CommandQueue commandQueue = new CommandQueue(); + @Inject + LocalProfilePlugin localProfilePlugin; + public ConfigBuilderPlugin() { super(new PluginDescription() .mainType(PluginType.GENERAL) @@ -237,9 +244,10 @@ public class ConfigBuilderPlugin extends PluginBase { return activeBgSource; } - @Nullable + @NotNull public ProfileInterface getActiveProfileInterface() { - return activeProfile; + if (activeProfile != null) return activeProfile; + else return localProfilePlugin; } @Nullable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt new file mode 100644 index 0000000000..6faee1c38a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.plugins.configBuilder + +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.db.ProfileSwitch + +interface ProfileFunction { + fun getProfileName(): String? + fun getProfileName(customized: Boolean): String + fun getProfileNameWithDuration(): String + fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String + fun isProfileValid(from: String): Boolean + fun getProfile(): Profile? + fun getUnits(): String + fun getProfile(time: Long): Profile? + fun prepareProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long): ProfileSwitch + fun doProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long) + fun doProfileSwitch(duration: Int, percentage: Int, timeShift: Int) +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt new file mode 100644 index 0000000000..de43cf5519 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -0,0 +1,80 @@ +package info.nightscout.androidaps.plugins.configBuilder + +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.db.Source +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.utils.sharedPreferences.SP +import java.security.spec.InvalidParameterSpecException +import javax.inject.Inject +import javax.inject.Singleton + +class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFunction { + + override fun getProfileName(): String = + getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = false) + + override fun getProfileName(customized: Boolean): String = + getProfileName(System.currentTimeMillis(), customized, showRemainingTime = false) + + override fun getProfileName(time: Long, customized: Boolean, showRemainingTime: Boolean): String = + ProfileFunctions.getInstance().getProfileName(time, customized, showRemainingTime) + + override fun getProfileNameWithDuration(): String = + getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = true) + + override fun isProfileValid(from: String): Boolean = + getProfile()?.isValid(from) ?: false + + override fun getProfile(): Profile? { + return ProfileFunctions.getInstance().getProfile() + } + + override fun getProfile(time: Long): Profile? = + getProfile(System.currentTimeMillis()) + + override fun getUnits(): String = + sp.getString(R.string.key_units, Constants.MGDL) + + override fun prepareProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long): ProfileSwitch { + val profile = profileStore.getSpecificProfile(profileName) + ?: throw InvalidParameterSpecException(profileName) + val profileSwitch = ProfileSwitch() + profileSwitch.date = date + profileSwitch.source = Source.USER + profileSwitch.profileName = profileName + profileSwitch.profileJson = profile.data.toString() + profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().activeProfileInterface::class.java.name + profileSwitch.durationInMinutes = duration + profileSwitch.isCPP = percentage != 100 || timeShift != 0 + profileSwitch.timeshift = timeShift + profileSwitch.percentage = percentage + return profileSwitch + } + + override fun doProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long) { + val profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date) + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch) + if (percentage == 90 && duration == 10) + sp.putBoolean(R.string.key_objectiveuseprofileswitch, true) + } + + override fun doProfileSwitch(duration: Int, percentage: Int, timeShift: Int) { + getProfile()?.let { + val profileSwitch = ProfileSwitch() + profileSwitch.date = System.currentTimeMillis() + profileSwitch.source = Source.USER + profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), customized = false, showRemainingTime = false) + profileSwitch.profileJson = it.data.toString() + profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().activeProfileInterface::class.java.name + profileSwitch.durationInMinutes = duration + profileSwitch.isCPP = percentage != 100 || timeShift != 0 + profileSwitch.timeshift = timeShift + profileSwitch.percentage = percentage + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java index bdde6606bb..126fc6c44d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -7,6 +7,7 @@ import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; +import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -14,6 +15,7 @@ import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.ProfileSwitch; @@ -24,7 +26,6 @@ import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; @@ -33,7 +34,7 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; -public class ProfileFunctions { +public class ProfileFunctions implements ProfileFunction { private static Logger log = LoggerFactory.getLogger(L.PROFILE); private CompositeDisposable disposable = new CompositeDisposable(); @@ -75,18 +76,22 @@ public class ProfileFunctions { ); } + @NotNull public String getProfileName() { return getProfileName(System.currentTimeMillis(), true, false); } + @NotNull public String getProfileName(boolean customized) { return getProfileName(System.currentTimeMillis(), customized, false); } + @NotNull public String getProfileNameWithDuration() { return getProfileName(System.currentTimeMillis(), true, true); } + @NotNull public String getProfileName(long time, boolean customized, boolean showRemainingTime) { String profileName = MainApp.gs(R.string.noprofileselected); @@ -114,7 +119,7 @@ public class ProfileFunctions { return profileName; } - public boolean isProfileValid(String from) { + public boolean isProfileValid(@NotNull String from) { Profile profile = getProfile(); return profile != null && profile.isValid(from); } @@ -124,6 +129,12 @@ public class ProfileFunctions { return getProfile(System.currentTimeMillis()); } + @NotNull + public String getUnits() { + return getSystemUnits(); + } + + @NotNull public static String getSystemUnits() { return SP.getString(R.string.key_units, Constants.MGDL); } @@ -156,7 +167,8 @@ public class ProfileFunctions { return null; } - public static ProfileSwitch prepareProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, long date) { + @NotNull + public ProfileSwitch prepareProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, long date) { ProfileSwitch profileSwitch = new ProfileSwitch(); profileSwitch.date = date; profileSwitch.source = Source.USER; @@ -164,20 +176,20 @@ public class ProfileFunctions { profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeshift != 0; - profileSwitch.timeshift = timeshift; + profileSwitch.isCPP = percentage != 100 || timeShift != 0; + profileSwitch.timeshift = timeShift; profileSwitch.percentage = percentage; return profileSwitch; } - public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, final long date) { - ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeshift, date); + public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { + ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date); TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); if (percentage == 90 && duration == 10) SP.putBoolean(R.string.key_objectiveuseprofileswitch, true); } - public static void doProfileSwitch(final int duration, final int percentage, final int timeshift) { + public void doProfileSwitch(final int duration, final int percentage, final int timeShift) { ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); if (profileSwitch != null) { profileSwitch = new ProfileSwitch(); @@ -187,8 +199,8 @@ public class ProfileFunctions { profileSwitch.profileJson = getInstance().getProfile().getData().toString(); profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeshift != 0; - profileSwitch.timeshift = timeshift; + profileSwitch.isCPP = percentage != 100 || timeShift != 0; + profileSwitch.timeshift = timeShift; profileSwitch.percentage = percentage; TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index 5143cdebc5..a6d29c70d2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -157,7 +157,7 @@ class ActionsFragment : Fragment() { if (ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile != null) View.VISIBLE else View.GONE - if (ProfileFunctions.getInstance().profile == null) { + if (ProfileFunctions.getInstance().getProfile() == null) { actions_temptarget?.visibility = View.GONE actions_extendedbolus?.visibility = View.GONE actions_extendedbolus_cancel?.visibility = View.GONE diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java index 63c923fdcf..b3741b7271 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java @@ -98,7 +98,7 @@ public class ActionProfileSwitch extends Action { return; } - ProfileFunctions.doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); + ProfileFunctions.getInstance().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); if (callback != null) callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java index 23b54640a5..71cbed7173 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java @@ -47,7 +47,7 @@ public class ActionProfileSwitchPercent extends Action { @Override public void doAction(Callback callback) { - ProfileFunctions.doProfileSwitch((int) duration.getValue(), (int) pct.getValue(), 0); + ProfileFunctions.getInstance().doProfileSwitch((int) duration.getValue(), (int) pct.getValue(), 0); if (callback != null) callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt index e738b7f94c..63a053f29f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditActionDialog.kt @@ -44,11 +44,11 @@ class EditActionDialog : DialogFragmentWithDate() { return true } - override fun onSaveInstanceState(bundle: Bundle) { - super.onSaveInstanceState(bundle) + override fun onSaveInstanceState(savedInstanceState: Bundle) { + super.onSaveInstanceState(savedInstanceState) action?.let { - bundle.putInt("actionPosition", actionPosition) - bundle.putString("action", it.toJSON()) + savedInstanceState.putInt("actionPosition", actionPosition) + savedInstanceState.putString("action", it.toJSON()) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java index 38ad5bb879..c4f70f40bf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java @@ -704,7 +704,7 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie void createNSTreatment(JSONObject data) { if (JsonHelper.safeGetString(data, "eventType", "").equals(CareportalEvent.PROFILESWITCH)) { - ProfileSwitch profileSwitch = ProfileFunctions.prepareProfileSwitch( + ProfileSwitch profileSwitch = ProfileFunctions.getInstance().prepareProfileSwitch( profileStore, JsonHelper.safeGetString(data, "profile"), JsonHelper.safeGetInt(data, "duration"), diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 87f7d832da..7dba406479 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -428,9 +428,15 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true return } + val profileName = ProfileFunctions.getInstance().getProfileName() + if (profileName == null) { + sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured)) + receivedSms.processed = true + return + } val list = store.getProfileList() if (splitted[1].toUpperCase(Locale.getDefault()) == "STATUS") { - sendSMS(Sms(receivedSms.phoneNumber, ProfileFunctions.getInstance().profileName)) + sendSMS(Sms(receivedSms.phoneNumber, profileName)) } else if (splitted[1].toUpperCase(Locale.getDefault()) == "LIST") { if (list.isEmpty()) sendSMS(Sms(receivedSms.phoneNumber, R.string.invalidprofile)) else { @@ -459,7 +465,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() val finalPercentage = percentage messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) { override fun run() { - ProfileFunctions.doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) + ProfileFunctions.getInstance().doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) sendSMS(Sms(receivedSms.phoneNumber, R.string.profileswitchcreated)) } }) @@ -495,7 +501,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() var tempBasalPct = SafeParse.stringToInt(StringUtils.removeEnd(splitted[1], "%")) var duration = 30 if (splitted.size > 2) duration = SafeParse.stringToInt(splitted[2]) - val profile = ProfileFunctions.getInstance().profile + val profile = ProfileFunctions.getInstance().getProfile() if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, R.string.noprofile)) else if (tempBasalPct == 0 && splitted[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) @@ -527,7 +533,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() var tempBasal = SafeParse.stringToDouble(splitted[1]) var duration = 30 if (splitted.size > 2) duration = SafeParse.stringToInt(splitted[2]) - val profile = ProfileFunctions.getInstance().profile + val profile = ProfileFunctions.getInstance().getProfile() if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, R.string.noprofile)) else if (tempBasal == 0.0 && splitted[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) @@ -644,7 +650,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) lastRemoteBolusTime = DateUtil.now() if (isMeal) { - ProfileFunctions.getInstance().profile?.let { currentProfile -> + ProfileFunctions.getInstance().getProfile()?.let { currentProfile -> var eatingSoonTTDuration = SP.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration) eatingSoonTTDuration = if (eatingSoonTTDuration > 0) eatingSoonTTDuration diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java index cae9817a55..d25d42bbe2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java @@ -679,7 +679,7 @@ public class ActionStringHandler { //send profile to pumpe new NewNSTreatmentDialog(); //init - ProfileFunctions.doProfileSwitch(0, percentage, timeshift); + ProfileFunctions.getInstance().doProfileSwitch(0, percentage, timeshift); } private static void generateTempTarget(int duration, double low, double high) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt index 6c111faf3f..5183007a64 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt @@ -42,7 +42,7 @@ class NSProfileFragment : Fragment() { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.nsprofile), MainApp.gs(R.string.activate_profile) + ": " + name + " ?", Runnable { - ProfileFunctions.doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) + ProfileFunctions.getInstance().doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) }) } } @@ -121,7 +121,7 @@ class NSProfileFragment : Fragment() { nsprofile_spinner.adapter = adapter // set selected to actual profile for (p in profileList.indices) { - if (profileList[p] == ProfileFunctions.getInstance().profileName) + if (profileList[p] == ProfileFunctions.getInstance().getProfileName()) nsprofile_spinner.setSelection(p) } profileview_noprofile.visibility = View.GONE diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt index 7ca4f962ae..e338b02f2b 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -90,7 +90,7 @@ class KeepAliveReceiver : BroadcastReceiver() { private fun checkPump() { val pump = ConfigBuilderPlugin.getPlugin().activePump - val profile = ProfileFunctions.getInstance().profile + val profile = ProfileFunctions.getInstance().getProfile() if (pump != null && profile != null) { val lastConnection = pump.lastDataTime() val isStatusOutdated = lastConnection + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis() diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt index 6d71a80ba1..df1a0586de 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt @@ -262,7 +262,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile, } fun confirmAndExecute(context: Context) { - val profile = ProfileFunctions.getInstance().profile ?: return + val profile = ProfileFunctions.getInstance().getProfile() ?: return val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return if (calculatedTotalInsulin > 0.0 || carbs > 0.0) { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt b/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt index 1d22c380ca..830053bef0 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/OKDialog.kt @@ -62,13 +62,11 @@ object OKDialog { } @JvmStatic - @JvmOverloads fun showConfirmation(activity: Activity, message: String, ok: Runnable?) { showConfirmation(activity, MainApp.gs(R.string.confirmation), message, ok, null) } @JvmStatic - @JvmOverloads fun showConfirmation(activity: Activity, message: Spanned, ok: Runnable?) { showConfirmation(activity, MainApp.gs(R.string.confirmation), message, ok, null) } From ac05390292f80ceb606ecae2e09ed07d70c97f42 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Fri, 27 Dec 2019 04:17:49 +0100 Subject: [PATCH 035/316] Insulin plugins injectable and Prep for SMS plugin and ConfigBuilder --- .../nightscout/androidaps/MainActivity.java | 26 +- .../info/nightscout/androidaps/MainApp.java | 25 +- .../activities/MyPreferenceFragment.java | 5 +- .../dependencyInjection/AppComponent.kt | 9 + .../dependencyInjection/AppModule.kt | 15 +- .../dependencyInjection/FragmentsModule.kt | 4 + .../configBuilder/ConfigBuilderPlugin.java | 34 ++- .../automation/actions/ActionSendSMS.java | 13 +- .../SmsCommunicatorFragment.kt | 15 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 224 +++++++++--------- .../insulin/InsulinOrefBasePlugin.java | 109 --------- .../plugins/insulin/InsulinOrefBasePlugin.kt | 93 ++++++++ .../insulin/InsulinOrefFreePeakPlugin.kt | 7 +- .../insulin/InsulinOrefRapidActingPlugin.java | 48 ---- .../insulin/InsulinOrefRapidActingPlugin.kt | 33 +++ .../InsulinOrefUltraRapidActingPlugin.java | 53 ----- .../InsulinOrefUltraRapidActingPlugin.kt | 37 +++ .../profile/local/LocalProfileFragment.kt | 2 +- .../queue/commands/CommandSetProfile.java | 7 +- .../androidaps/services/DataService.java | 14 +- .../androidaps/utils/AndroidPermission.java | 4 +- .../ConfigBuilderPluginTest.java | 4 + .../SmsCommunicatorPluginTest.java | 6 +- .../insulin/InsulinOrefBasePluginTest.java | 6 +- .../insulin/InsulinOrefFreePeakPluginTest.kt | 3 +- 25 files changed, 437 insertions(+), 359 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 1d326fc5de..d6cf1bcd28 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -37,7 +37,12 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; + import dagger.android.AndroidInjection; +import dagger.android.AndroidInjector; +import dagger.android.DispatchingAndroidInjector; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.PreferencesActivity; @@ -53,6 +58,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt; import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus; +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.setupwizard.SetupWizardActivity; import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.androidaps.utils.AndroidPermission; @@ -64,14 +70,21 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class MainActivity extends NoSplashAppCompatActivity { +public class MainActivity extends NoSplashAppCompatActivity implements HasAndroidInjector { private static Logger log = LoggerFactory.getLogger(L.CORE); + + @Inject + DispatchingAndroidInjector androidInjector; + private CompositeDisposable disposable = new CompositeDisposable(); private ActionBarDrawerToggle actionBarDrawerToggle; private MenuItem pluginPreferencesMenuItem; + @Inject + SmsCommunicatorPlugin smsCommunicatorPlugin; + @Override public void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); @@ -148,7 +161,7 @@ public class MainActivity extends NoSplashAppCompatActivity { AndroidPermission.notifyForBatteryOptimizationPermission(this); if (Config.PUMPDRIVERS) { AndroidPermission.notifyForLocationPermissions(this); - AndroidPermission.notifyForSMSPermissions(this); + AndroidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin); } } @@ -340,4 +353,13 @@ public class MainActivity extends NoSplashAppCompatActivity { } return actionBarDrawerToggle.onOptionsItemSelected(item); } + + + /** + * Returns an {@link AndroidInjector}. + */ + @Override + public AndroidInjector androidInjector() { + return androidInjector; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 122484342d..9e5ccb7879 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -123,8 +123,12 @@ public class MainApp extends DaggerApplication { public static boolean devBranch; public static boolean engineeringMode; - @Inject - InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + @Inject ConfigBuilderPlugin configBuilderPlugin; + + @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + @Inject InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin; + @Inject InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin; + @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; @Override public void onCreate() { @@ -182,8 +186,8 @@ public class MainApp extends DaggerApplication { pluginsList.add(OverviewPlugin.INSTANCE); pluginsList.add(IobCobCalculatorPlugin.getPlugin()); if (!Config.NSCLIENT) pluginsList.add(ActionsPlugin.INSTANCE); - pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin()); - pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin()); + pluginsList.add(insulinOrefRapidActingPlugin); + pluginsList.add(insulinOrefUltraRapidActingPlugin); pluginsList.add(insulinOrefFreePeakPlugin); pluginsList.add(SensitivityOref0Plugin.getPlugin()); pluginsList.add(SensitivityAAPSPlugin.getPlugin()); @@ -220,7 +224,7 @@ public class MainApp extends DaggerApplication { pluginsList.add(SourceTomatoPlugin.getPlugin()); pluginsList.add(SourceEversensePlugin.getPlugin()); pluginsList.add(RandomBgPlugin.INSTANCE); - if (!Config.NSCLIENT) pluginsList.add(SmsCommunicatorPlugin.INSTANCE); + if (!Config.NSCLIENT) pluginsList.add(smsCommunicatorPlugin); pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(WearPlugin.initPlugin(this)); @@ -231,21 +235,21 @@ public class MainApp extends DaggerApplication { pluginsList.add(MaintenancePlugin.initPlugin(this)); pluginsList.add(AutomationPlugin.INSTANCE); - pluginsList.add(ConfigBuilderPlugin.getPlugin()); + pluginsList.add(configBuilderPlugin); pluginsList.add(DstHelperPlugin.getPlugin()); - ConfigBuilderPlugin.getPlugin().initialize(); + configBuilderPlugin.initialize(); } NSUpload.uploadAppStart(); - final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); + final PumpInterface pump = configBuilderPlugin.getActivePump(); if (pump != null) { new Thread(() -> { SystemClock.sleep(5000); - ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Initialization", null); + configBuilderPlugin.getCommandQueue().readStatus("Initialization", null); }).start(); } @@ -253,6 +257,8 @@ public class MainApp extends DaggerApplication { doMigrations(); } + + private void doMigrations() { // guarantee that the unreachable threshold is at least 30 and of type String @@ -279,7 +285,6 @@ public class MainApp extends DaggerApplication { @Override protected AndroidInjector applicationInjector() { - return DaggerAppComponent .builder() .application(this) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java index 533eaa0416..67c309c82d 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java @@ -53,6 +53,9 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + @Inject + SmsCommunicatorPlugin smsCommunicatorPlugin; + @Override public void setArguments(Bundle args) { super.setArguments(args); @@ -132,7 +135,7 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(TidepoolPlugin.INSTANCE, PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.INSTANCE, PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(smsCommunicatorPlugin, PluginType.GENERAL); addPreferencesFromResourceIfEnabled(AutomationPlugin.INSTANCE, PluginType.GENERAL); addPreferencesFromResource(R.xml.pref_others); diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index edf202b5ce..d7ed6d04a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,6 +5,9 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS +import info.nightscout.androidaps.queue.commands.CommandSetProfile +import info.nightscout.androidaps.services.DataService import javax.inject.Singleton @Singleton @@ -18,6 +21,12 @@ import javax.inject.Singleton ) interface AppComponent : AndroidInjector { + fun injectDataService(service: DataService) + + fun injectCommandSetProfile(commandSetProfile: CommandSetProfile) + + fun injectActionSendSMS(actionSendSMS: ActionSendSMS) + @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 2b266afc22..d031bf7267 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -5,9 +5,13 @@ import android.preference.PreferenceManager import dagger.Binds import dagger.Module import dagger.Provides +import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation +import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS +import info.nightscout.androidaps.queue.commands.CommandSetProfile +import info.nightscout.androidaps.services.DataService import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -25,7 +29,7 @@ class AppModule { @Provides @Singleton - fun provideProfileFunction(sp : SP): ProfileFunction { + fun provideProfileFunction(sp: SP): ProfileFunction { return ProfileFunctionImplementation(sp) } @@ -38,6 +42,15 @@ class AppModule { @Module interface AppBindings { + @ContributesAndroidInjector + fun bindDataService(): DataService + + @ContributesAndroidInjector + fun bindCommandSetProfile(): CommandSetProfile + + @ContributesAndroidInjector + fun bindActionSendSMS(): ActionSendSMS + @Binds fun bindContext(mainApp: MainApp): Context } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index db9a555388..162f156fe3 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -3,9 +3,13 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.activities.MyPreferenceFragment +import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment @Module abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment + + @ContributesAndroidInjector + abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index 14615060d9..02508769dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -9,7 +9,9 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import javax.inject.Inject; +import javax.inject.Singleton; +import dagger.Lazy; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventAppInitialized; @@ -35,14 +37,20 @@ import info.nightscout.androidaps.utils.SP; /** * Created by mike on 05.08.2016. */ +@Singleton public class ConfigBuilderPlugin extends PluginBase { private Logger log = LoggerFactory.getLogger(L.CONFIGBUILDER); private static ConfigBuilderPlugin configBuilderPlugin; + + /** + * @deprecated Use dagger to get an instance + */ + @Deprecated static public ConfigBuilderPlugin getPlugin() { if (configBuilderPlugin == null) - configBuilderPlugin = new ConfigBuilderPlugin(); + throw new IllegalStateException("Accessing ConfigBuilder before first instantiation"); return configBuilderPlugin; } @@ -57,10 +65,20 @@ public class ConfigBuilderPlugin extends PluginBase { private CommandQueue commandQueue = new CommandQueue(); - @Inject - LocalProfilePlugin localProfilePlugin; + private Lazy insulinOrefRapidActingPlugin; - public ConfigBuilderPlugin() { + //TODO: inject + LocalProfilePlugin localProfilePlugin = LocalProfilePlugin.INSTANCE; + + /* + * Written by Adrian: + * The ConfigBuilderPlugin.getPlugin() method is used at 333 places throughout the app. + * In order to make the transition to DI, while legacy code is still calling `getPlugin()`, + * I'd instantiate this plugin very very early on (first injected dependency in MainApp) and use + * Lazy dependencies in this constructor. + * */ + @Inject + public ConfigBuilderPlugin(Lazy insulinOrefRapidActingPlugin) { super(new PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ConfigBuilderFragment.class.getName()) @@ -71,6 +89,8 @@ public class ConfigBuilderPlugin extends PluginBase { .shortName(R.string.configbuilder_shortname) .description(R.string.description_config_builder) ); + this.insulinOrefRapidActingPlugin = insulinOrefRapidActingPlugin; + configBuilderPlugin = this; // TODO: only while transitioning to Dagger } @Override @@ -298,8 +318,8 @@ public class ConfigBuilderPlugin extends PluginBase { pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.INSULIN); activeInsulin = (InsulinInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN); if (activeInsulin == null) { - activeInsulin = InsulinOrefRapidActingPlugin.getPlugin(); - InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(PluginType.INSULIN, true); + activeInsulin = insulinOrefRapidActingPlugin.get(); + insulinOrefRapidActingPlugin.get().setPluginEnabled(PluginType.INSULIN, true); if (L.isEnabled(L.CONFIGBUILDER)) log.debug("Defaulting InsulinOrefRapidActingPlugin"); } @@ -457,7 +477,7 @@ public class ConfigBuilderPlugin extends PluginBase { if (type == PluginType.PUMP) VirtualPumpPlugin.getPlugin().setPluginEnabled(type, true); else if (type == PluginType.INSULIN) - InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(type, true); + insulinOrefRapidActingPlugin.get().setPluginEnabled(type, true); else if (type == PluginType.SENSITIVITY) SensitivityOref0Plugin.getPlugin().setPluginEnabled(type, true); else if (type == PluginType.PROFILE) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java index fa9140e5f9..7d97eff3a8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java @@ -9,10 +9,11 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.general.automation.elements.InputString; import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement; import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder; @@ -25,6 +26,14 @@ public class ActionSendSMS extends Action { public InputString text = new InputString(); + @Inject + SmsCommunicatorPlugin smsCommunicatorPlugin; + + public ActionSendSMS() { + super(); + MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger + } + @Override public int friendlyName() { return R.string.sendsmsactiondescription; @@ -37,7 +46,7 @@ public class ActionSendSMS extends Action { @Override public void doAction(Callback callback) { - boolean result = SmsCommunicatorPlugin.INSTANCE.sendNotificationToAllNumbers(text.getValue()); + boolean result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.getValue()); if (callback != null) callback.result(new PumpEnactResult().success(result).comment(result ? R.string.ok : R.string.danar_error)).run(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt index 90ec078931..3423d6d7df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt @@ -5,6 +5,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment +import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.bus.RxBus.toObservable import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui @@ -15,11 +16,15 @@ import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.smscommunicator_fragment.* import java.util.* +import javax.inject.Inject import kotlin.math.max -class SmsCommunicatorFragment : Fragment() { +class SmsCommunicatorFragment : DaggerFragment() { private val disposable = CompositeDisposable() + @Inject + lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.smscommunicator_fragment, container, false) @@ -47,12 +52,12 @@ class SmsCommunicatorFragment : Fragment() { return (object1.date - object2.date).toInt() } } - Collections.sort(SmsCommunicatorPlugin.messages, CustomComparator()) + Collections.sort(smsCommunicatorPlugin.messages, CustomComparator()) val messagesToShow = 40 - val start = max(0, SmsCommunicatorPlugin.messages.size - messagesToShow) + val start = max(0, smsCommunicatorPlugin.messages.size - messagesToShow) var logText = "" - for (x in start until SmsCommunicatorPlugin.messages.size) { - val sms = SmsCommunicatorPlugin.messages[x] + for (x in start until smsCommunicatorPlugin.messages.size) { + val sms = smsCommunicatorPlugin.messages[x] when { sms.ignored -> { logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + "
" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 7dba406479..2103856af1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -45,15 +45,19 @@ import org.apache.commons.lang3.StringUtils import org.slf4j.LoggerFactory import java.text.Normalizer import java.util.* +import javax.inject.Inject +import javax.inject.Singleton -object SmsCommunicatorPlugin : PluginBase(PluginDescription() - .mainType(PluginType.GENERAL) - .fragmentClass(SmsCommunicatorFragment::class.java.name) - .pluginName(R.string.smscommunicator) - .shortName(R.string.smscommunicator_shortname) - .preferencesId(R.xml.pref_smscommunicator) - .description(R.string.description_sms_communicator) +@Singleton +class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigBuilderPlugin) : PluginBase(PluginDescription() + .mainType(PluginType.GENERAL) + .fragmentClass(SmsCommunicatorFragment::class.java.name) + .pluginName(R.string.smscommunicator) + .shortName(R.string.smscommunicator_shortname) + .preferencesId(R.xml.pref_smscommunicator) + .description(R.string.description_sms_communicator) ) { + private val log = LoggerFactory.getLogger(L.SMS) private val disposable = CompositeDisposable() var allowedNumbers: MutableList = ArrayList() @@ -62,31 +66,32 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() var messages = ArrayList() val commands = mapOf( - "BG" to "BG", - "LOOP" to "LOOP STOP/DISABLE/START/ENABLE/RESUME/STATUS\nLOOP SUSPEND 20", - "TREATMENTS" to "TREATMENTS REFRESH", - "NSCLIENT" to "NSCLIENT RESTART", - "PUMP" to "PUMP", - "BASAL" to "BASAL STOP/CANCEL\nBASAL 0.3\nBASAL 0.3 20\nBASAL 30%\nBASAL 30% 20\n", - "BOLUS" to "BOLUS 1.2\nBOLUS 1.2 MEAL", - "EXTENDED" to "EXTENDED STOP/CANCEL\nEXTENDED 2 120", - "CAL" to "CAL 5.6", - "PROFILE" to "PROFILE STATUS/LIST\nPROFILE 1\nPROFILE 2 30", - "TARGET" to "TARGET MEAL/ACTIVITY/HYPO/STOP", - "SMS" to "SMS DISABLE/STOP", - "CARBS" to "CARBS 12\nCARBS 12 23:05\nCARBS 12 11:05PM", - "HELP" to "HELP\nHELP command" + "BG" to "BG", + "LOOP" to "LOOP STOP/DISABLE/START/ENABLE/RESUME/STATUS\nLOOP SUSPEND 20", + "TREATMENTS" to "TREATMENTS REFRESH", + "NSCLIENT" to "NSCLIENT RESTART", + "PUMP" to "PUMP", + "BASAL" to "BASAL STOP/CANCEL\nBASAL 0.3\nBASAL 0.3 20\nBASAL 30%\nBASAL 30% 20\n", + "BOLUS" to "BOLUS 1.2\nBOLUS 1.2 MEAL", + "EXTENDED" to "EXTENDED STOP/CANCEL\nEXTENDED 2 120", + "CAL" to "CAL 5.6", + "PROFILE" to "PROFILE STATUS/LIST\nPROFILE 1\nPROFILE 2 30", + "TARGET" to "TARGET MEAL/ACTIVITY/HYPO/STOP", + "SMS" to "SMS DISABLE/STOP", + "CARBS" to "CARBS 12\nCARBS 12 23:05\nCARBS 12 11:05PM", + "HELP" to "HELP\nHELP command" ) - init { + /*init { processSettings(null) - } + }*/ override fun onStart() { + processSettings(null) // TODO moved from init block to avoid cyclic calling MainApp via SP while we are still in MainApp.onCreate() super.onStart() disposable.add(toObservable(EventPreferenceChange::class.java) - .observeOn(Schedulers.io()) - .subscribe({ event: EventPreferenceChange? -> processSettings(event) }) { throwable: Throwable? -> FabricPrivacy.logException(throwable) } + .observeOn(Schedulers.io()) + .subscribe({ event: EventPreferenceChange? -> processSettings(event) }) { throwable: Throwable? -> FabricPrivacy.logException(throwable) } ) } @@ -98,13 +103,13 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() override fun preprocessPreferences(preferenceFragment: PreferenceFragment) { super.preprocessPreferences(preferenceFragment) val distance = preferenceFragment.findPreference(MainApp.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference? - ?: return + ?: return val allowedNumbers = preferenceFragment.findPreference(MainApp.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference? - ?: return + ?: return if (!areMoreNumbers(allowedNumbers.text)) { distance.title = (MainApp.gs(R.string.smscommunicator_remotebolusmindistance) - + ".\n" - + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + + ".\n" + + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) distance.isEnabled = false } else { distance.title = MainApp.gs(R.string.smscommunicator_remotebolusmindistance) @@ -114,8 +119,8 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() if (!areMoreNumbers(newValue as String)) { distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString() distance.title = (MainApp.gs(R.string.smscommunicator_remotebolusmindistance) - + ".\n" - + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + + ".\n" + + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) distance.isEnabled = false } else { distance.title = MainApp.gs(R.string.smscommunicator_remotebolusmindistance) @@ -185,67 +190,67 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() send(EventSmsCommunicatorUpdateGui()) return } - val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return + val pump = configBuilderPlugin.activePump ?: return messages.add(receivedSms) log.debug(receivedSms.toString()) val splitted = receivedSms.text.split(Regex("\\s+")).toTypedArray() val remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false) if (splitted.isNotEmpty() && isCommand(splitted[0].toUpperCase(Locale.getDefault()), receivedSms.phoneNumber)) { when (splitted[0].toUpperCase(Locale.getDefault())) { - "BG" -> + "BG" -> if (splitted.size == 1) processBG(receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "LOOP" -> + "LOOP" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2 || splitted.size == 3) processLOOP(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) "TREATMENTS" -> if (splitted.size == 2) processTREATMENTS(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "NSCLIENT" -> + "NSCLIENT" -> if (splitted.size == 2) processNSCLIENT(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "PUMP" -> + "PUMP" -> if (splitted.size == 1) processPUMP(receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "PROFILE" -> + "PROFILE" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2 || splitted.size == 3) processPROFILE(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "BASAL" -> + "BASAL" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2 || splitted.size == 3) processBASAL(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "EXTENDED" -> + "EXTENDED" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2 || splitted.size == 3) processEXTENDED(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "BOLUS" -> + "BOLUS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2 && DateUtil.now() - lastRemoteBolusTime < Constants.remoteBolusMinDistance) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotebolusnotallowed)) else if (splitted.size == 2 && pump.isSuspended) sendSMS(Sms(receivedSms.phoneNumber, R.string.pumpsuspended)) else if (splitted.size == 2 || splitted.size == 3) processBOLUS(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "CARBS" -> + "CARBS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2 || splitted.size == 3) processCARBS(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "CAL" -> + "CAL" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2) processCAL(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "TARGET" -> + "TARGET" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2) processTARGET(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "SMS" -> + "SMS" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed)) else if (splitted.size == 2) processSMS(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - "HELP" -> + "HELP" -> if (splitted.size == 1 || splitted.size == 2) processHELP(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) - else -> + else -> if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) { messageToConfirm?.action(splitted[0]) messageToConfirm = null @@ -275,9 +280,9 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() val basalIob = TreatmentsPlugin.getPlugin().lastCalculationTempBasals.round() val cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB") reply += (MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" - + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " - + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " - + MainApp.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) + + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " + + MainApp.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } @@ -288,11 +293,11 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() val loopPlugin = LoopPlugin.getPlugin() if (loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.setPluginEnabled(PluginType.LOOP, false) - ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() { + configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { send(EventRefreshOverview("SMS_LOOP_STOP")) val replyText = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " + - MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } }) @@ -300,6 +305,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisdisabled)) receivedSms.processed = true } + "ENABLE", "START" -> { val loopPlugin = LoopPlugin.getPlugin() if (!loopPlugin.isEnabled(PluginType.LOOP)) { @@ -310,7 +316,8 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisenabled)) receivedSms.processed = true } - "STATUS" -> { + + "STATUS" -> { val loopPlugin = LoopPlugin.getPlugin() val reply = if (loopPlugin.isEnabled(PluginType.LOOP)) { if (loopPlugin.isSuspended()) String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) @@ -320,13 +327,15 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } - "RESUME" -> { + + "RESUME" -> { LoopPlugin.getPlugin().suspendTo(0) send(EventRefreshOverview("SMS_LOOP_RESUME")) NSUpload.uploadOpenAPSOffline(0.0) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopresumed)) } - "SUSPEND" -> { + + "SUSPEND" -> { var duration = 0 if (splitted.size == 3) duration = SafeParse.stringToInt(splitted[2]) duration = Math.max(0, duration) @@ -341,18 +350,18 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(duration) { override fun run() { - ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() { + configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + anInteger() * 60L * 1000) NSUpload.uploadOpenAPSOffline(anInteger() * 60.toDouble()) send(EventRefreshOverview("SMS_LOOP_SUSPENDED")) val replyText = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " + - MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -361,7 +370,8 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() }) } } - else -> sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) + + else -> sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) } } @@ -398,9 +408,9 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() } private fun processPUMP(receivedSms: Sms) { - ConfigBuilderPlugin.getPlugin().commandQueue.readStatus("SMS", object : Callback() { + configBuilderPlugin.commandQueue.readStatus("SMS", object : Callback() { override fun run() { - val pump = ConfigBuilderPlugin.getPlugin().activePump + val pump = configBuilderPlugin.activePump if (result.success) { if (pump != null) { val reply = pump.shortStatus(true) @@ -416,7 +426,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() } private fun processPROFILE(splitted: Array, receivedSms: Sms) { // load profiles - val anInterface = ConfigBuilderPlugin.getPlugin().activeProfileInterface + val anInterface = configBuilderPlugin.activeProfileInterface if (anInterface == null) { sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured)) receivedSms.processed = true @@ -482,15 +492,15 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { - ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() { + configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcanceled) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -512,16 +522,16 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(tempBasalPct, duration) { override fun run() { - ConfigBuilderPlugin.getPlugin().commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, object : Callback() { + configBuilderPlugin.commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, object : Callback() { override fun run() { if (result.success) { var replyText: String replyText = if (result.isPercent) String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_tempbasalfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -544,16 +554,16 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(tempBasal, duration) { override fun run() { - ConfigBuilderPlugin.getPlugin().commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, object : Callback() { + configBuilderPlugin.commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, object : Callback() { override fun run() { if (result.success) { var replyText = if (result.isPercent) String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_tempbasalfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -571,15 +581,15 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { - ConfigBuilderPlugin.getPlugin().commandQueue.cancelExtended(object : Callback() { + configBuilderPlugin.commandQueue.cancelExtended(object : Callback() { override fun run() { if (result.success) { var replyText = MainApp.gs(R.string.smscommunicator_extendedcanceled) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_extendedcancelfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -599,15 +609,15 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(extended, duration) { override fun run() { - ConfigBuilderPlugin.getPlugin().commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { + configBuilderPlugin.commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { override fun run() { if (result.success) { var replyText = String.format(MainApp.gs(R.string.smscommunicator_extendedset), aDouble, duration) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_extendedfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -636,37 +646,37 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.insulin = aDouble() detailedBolusInfo.source = Source.USER - ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { + configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { val resultSuccess = result.success val resultBolusDelivered = result.bolusDelivered - ConfigBuilderPlugin.getPlugin().commandQueue.readStatus("SMS", object : Callback() { + configBuilderPlugin.commandQueue.readStatus("SMS", object : Callback() { override fun run() { if (resultSuccess) { var replyText = if (isMeal) String.format(MainApp.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) else String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) lastRemoteBolusTime = DateUtil.now() if (isMeal) { ProfileFunctions.getInstance().getProfile()?.let { currentProfile -> var eatingSoonTTDuration = SP.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration) eatingSoonTTDuration = - if (eatingSoonTTDuration > 0) eatingSoonTTDuration - else Constants.defaultEatingSoonTTDuration + if (eatingSoonTTDuration > 0) eatingSoonTTDuration + else Constants.defaultEatingSoonTTDuration var eatingSoonTT = SP.getDouble(R.string.key_eatingsoon_target, if (currentProfile.units == Constants.MMOL) Constants.defaultEatingSoonTTmmol else Constants.defaultEatingSoonTTmgdl) eatingSoonTT = - if (eatingSoonTT > 0) eatingSoonTT - else if (currentProfile.units == Constants.MMOL) Constants.defaultEatingSoonTTmmol - else Constants.defaultEatingSoonTTmgdl + if (eatingSoonTT > 0) eatingSoonTT + else if (currentProfile.units == Constants.MMOL) Constants.defaultEatingSoonTTmmol + else Constants.defaultEatingSoonTTmgdl val tempTarget = TempTarget() - .date(System.currentTimeMillis()) - .duration(eatingSoonTTDuration) - .reason(MainApp.gs(R.string.eatingsoon)) - .source(Source.USER) - .low(Profile.toMgdl(eatingSoonTT, currentProfile.units)) - .high(Profile.toMgdl(eatingSoonTT, currentProfile.units)) + .date(System.currentTimeMillis()) + .duration(eatingSoonTTDuration) + .reason(MainApp.gs(R.string.eatingsoon)) + .source(Source.USER) + .low(Profile.toMgdl(eatingSoonTT, currentProfile.units)) + .high(Profile.toMgdl(eatingSoonTT, currentProfile.units)) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) val tt = if (currentProfile.units == Constants.MMOL) { DecimalFormatter.to1Decimal(eatingSoonTT) @@ -677,7 +687,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_bolusfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -712,15 +722,15 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.carbs = anInteger().toDouble() detailedBolusInfo.date = secondLong() - ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { + configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (result.success) { var replyText = String.format(MainApp.gs(R.string.smscommunicator_carbsset), anInteger) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { var replyText = MainApp.gs(R.string.smscommunicator_carbsfailed) - replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true) + replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } } @@ -772,12 +782,12 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() tt = Profile.toCurrentUnits(tt) tt = if (tt > 0) tt else if (units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL val tempTarget = TempTarget() - .date(System.currentTimeMillis()) - .duration(ttDuration) - .reason(MainApp.gs(R.string.eatingsoon)) - .source(Source.USER) - .low(Profile.toMgdl(tt, units)) - .high(Profile.toMgdl(tt, units)) + .date(System.currentTimeMillis()) + .duration(ttDuration) + .reason(MainApp.gs(R.string.eatingsoon)) + .source(Source.USER) + .low(Profile.toMgdl(tt, units)) + .high(Profile.toMgdl(tt, units)) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) val ttString = if (units == Constants.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt) val replyText = String.format(MainApp.gs(R.string.smscommunicator_tt_set), ttString, ttDuration) @@ -791,11 +801,11 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { val tempTarget = TempTarget() - .source(Source.USER) - .date(DateUtil.now()) - .duration(0) - .low(0.0) - .high(0.0) + .source(Source.USER) + .date(DateUtil.now()) + .duration(0) + .low(0.0) + .high(0.0) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) val replyText = String.format(MainApp.gs(R.string.smscommunicator_tt_canceled)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) @@ -807,7 +817,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() private fun processSMS(splitted: Array, receivedSms: Sms) { val isStop = (splitted[1].equals("STOP", ignoreCase = true) - || splitted[1].equals("DISABLE", ignoreCase = true)) + || splitted[1].equals("DISABLE", ignoreCase = true)) if (isStop) { val passCode = generatePasscode() val reply = String.format(MainApp.gs(R.string.smscommunicator_stopsmswithcode), passCode) @@ -862,7 +872,7 @@ object SmsCommunicatorPlugin : PluginBase(PluginDescription() else { val parts = smsManager.divideMessage(sms.text) smsManager.sendMultipartTextMessage(sms.phoneNumber, null, parts, - null, null) + null, null) } messages.add(sms) } catch (e: IllegalArgumentException) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.java deleted file mode 100644 index 8ad187d41a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.java +++ /dev/null @@ -1,109 +0,0 @@ -package info.nightscout.androidaps.plugins.insulin; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Iob; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.interfaces.InsulinInterface; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.treatments.Treatment; - -/** - * Created by adrian on 13.08.2017. - */ - -public abstract class InsulinOrefBasePlugin extends PluginBase implements InsulinInterface { - - public static double MIN_DIA = 5; - - long lastWarned = 0; - - public InsulinOrefBasePlugin() { - super(new PluginDescription() - .mainType(PluginType.INSULIN) - .fragmentClass(InsulinFragment.class.getName()) - .pluginName(R.string.fastactinginsulin) - .shortName(R.string.insulin_shortname) - .visibleByDefault(false) - ); - } - - @Override - public double getDia() { - double dia = getUserDefinedDia(); - if (dia >= MIN_DIA) { - return dia; - } else { - sendShortDiaNotification(dia); - return MIN_DIA; - } - } - - void sendShortDiaNotification(double dia) { - if ((System.currentTimeMillis() - lastWarned) > 60 * 1000) { - lastWarned = System.currentTimeMillis(); - Notification notification = new Notification(Notification.SHORT_DIA, String.format(this.getNotificationPattern(), dia, MIN_DIA), Notification.URGENT); - RxBus.INSTANCE.send(new EventNewNotification(notification)); - } - } - - public String getNotificationPattern() { - return MainApp.gs(R.string.dia_too_short); - } - - public double getUserDefinedDia() { - Profile profile = ProfileFunctions.getInstance().getProfile(); - return profile != null ? profile.getDia() : MIN_DIA; - } - - public Iob iobCalcForTreatment(Treatment treatment, long time) { - return this.iobCalcForTreatment(treatment, time, 0d); - } - - @Override - public Iob iobCalcForTreatment(Treatment treatment, long time, double dia) { - Iob result = new Iob(); - - int peak = getPeak(); - - if (treatment.insulin != 0d) { - - long bolusTime = treatment.date; - double t = (time - bolusTime) / 1000d / 60d; - - double td = getDia() * 60; //getDIA() always >= MIN_DIA - double tp = peak; - - // force the IOB to 0 if over DIA hours have passed - if (t < td) { - double tau = tp * (1 - tp / td) / (1 - 2 * tp / td); - double a = 2 * tau / td; - double S = 1 / (1 - a + (1 + a) * Math.exp(-td / tau)); - result.activityContrib = treatment.insulin * (S / Math.pow(tau, 2)) * t * (1 - t / td) * Math.exp(-t / tau); - result.iobContrib = treatment.insulin * (1 - S * (1 - a) * ((Math.pow(t, 2) / (tau * td * (1 - a)) - t / tau - 1) * Math.exp(-t / tau) + 1)); - } - } - return result; - } - - @Override - public String getComment() { - String comment = commentStandardText(); - double userDia = getUserDefinedDia(); - if (userDia < MIN_DIA) { - comment += "\n" + String.format(MainApp.gs(R.string.dia_too_short), userDia, MIN_DIA); - } - return comment; - } - - abstract int getPeak(); - - abstract String commentStandardText(); - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt new file mode 100644 index 0000000000..d802abd28f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt @@ -0,0 +1,93 @@ +package info.nightscout.androidaps.plugins.insulin + +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Iob +import info.nightscout.androidaps.interfaces.InsulinInterface +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.plugins.bus.RxBus.send +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification +import info.nightscout.androidaps.plugins.treatments.Treatment + +/** + * Created by adrian on 13.08.2017. + */ +abstract class InsulinOrefBasePlugin() : PluginBase(PluginDescription() + .mainType(PluginType.INSULIN) + .fragmentClass(InsulinFragment::class.java.name) + .shortName(R.string.insulin_shortname) + .visibleByDefault(false) +), InsulinInterface { + + var lastWarned: Long = 0 + override fun getDia(): Double { + val dia = userDefinedDia + return if (dia >= MIN_DIA) { + dia + } else { + sendShortDiaNotification(dia) + MIN_DIA + } + } + + open fun sendShortDiaNotification(dia: Double) { + if (System.currentTimeMillis() - lastWarned > 60 * 1000) { + lastWarned = System.currentTimeMillis() + val notification = Notification(Notification.SHORT_DIA, String.format(notificationPattern, dia, MIN_DIA), Notification.URGENT) + send(EventNewNotification(notification)) + } + } + + val notificationPattern: String + get() = MainApp.gs(R.string.dia_too_short) + + open val userDefinedDia: Double + get() { + val profile = ProfileFunctions.getInstance().getProfile() + return profile?.dia ?: MIN_DIA + } + + fun iobCalcForTreatment(treatment: Treatment, time: Long): Iob { + return this.iobCalcForTreatment(treatment, time, 0.0) + } + + override fun iobCalcForTreatment(treatment: Treatment, time: Long, dia: Double): Iob { + val result = Iob() + val peak = peak + if (treatment.insulin != 0.0) { + val bolusTime = treatment.date + val t = (time - bolusTime) / 1000.0 / 60.0 + val td = getDia() * 60 //getDIA() always >= MIN_DIA + val tp = peak.toDouble() + // force the IOB to 0 if over DIA hours have passed + if (t < td) { + val tau = tp * (1 - tp / td) / (1 - 2 * tp / td) + val a = 2 * tau / td + val S = 1 / (1 - a + (1 + a) * Math.exp(-td / tau)) + result.activityContrib = treatment.insulin * (S / Math.pow(tau, 2.0)) * t * (1 - t / td) * Math.exp(-t / tau) + result.iobContrib = treatment.insulin * (1 - S * (1 - a) * ((Math.pow(t, 2.0) / (tau * td * (1 - a)) - t / tau - 1) * Math.exp(-t / tau) + 1)) + } + } + return result + } + + override fun getComment(): String { + var comment = commentStandardText() + val userDia = userDefinedDia + if (userDia < MIN_DIA) { + comment += "\n" + String.format(MainApp.gs(R.string.dia_too_short), userDia, MIN_DIA) + } + return comment + } + + abstract val peak: Int + abstract fun commentStandardText(): String + + companion object { + const val MIN_DIA = 5.0 + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index ba6773d324..b3da1d9ff0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -24,13 +24,12 @@ class InsulinOrefFreePeakPlugin @Inject constructor( return resourceHelper.gs(R.string.free_peak_oref) ?: "" } - public override fun commentStandardText(): String { + override fun commentStandardText(): String { return resourceHelper.gs(R.string.insulin_peak_time) + ": " + peak } - public override fun getPeak(): Int { - return sp.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK) - } + override val peak: Int + get() = sp.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK) companion object { private const val DEFAULT_PEAK = 75 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.java deleted file mode 100644 index 5aceaaacaf..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.java +++ /dev/null @@ -1,48 +0,0 @@ -package info.nightscout.androidaps.plugins.insulin; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; - -/** - * Created by adrian on 14/08/17. - */ - -public class InsulinOrefRapidActingPlugin extends InsulinOrefBasePlugin { - - private static InsulinOrefRapidActingPlugin plugin = null; - - public static InsulinOrefRapidActingPlugin getPlugin() { - if (plugin == null) - plugin = new InsulinOrefRapidActingPlugin(); - return plugin; - } - - private static final int PEAK = 75; - - private InsulinOrefRapidActingPlugin() { - super(); - pluginDescription - .pluginName(R.string.rapid_acting_oref) - .description(R.string.description_insulin_rapid); - } - - @Override - public int getId() { - return OREF_RAPID_ACTING; - } - - @Override - public String getFriendlyName() { - return MainApp.gs(R.string.rapid_acting_oref); - } - - @Override - public String commentStandardText() { - return MainApp.gs(R.string.fastactinginsulincomment); - } - - @Override - int getPeak() { - return PEAK; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt new file mode 100644 index 0000000000..4cdb152a4d --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.plugins.insulin + +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.InsulinInterface +import javax.inject.Inject + +/** + * Created by adrian on 14/08/17. + */ +class InsulinOrefRapidActingPlugin @Inject constructor(): InsulinOrefBasePlugin() { + + override fun getId(): Int { + return InsulinInterface.OREF_RAPID_ACTING + } + + override fun getFriendlyName(): String { + return MainApp.gs(R.string.rapid_acting_oref) + } + + override fun commentStandardText(): String { + return MainApp.gs(R.string.fastactinginsulincomment) + } + + override val peak = 75 + + + init { + pluginDescription + .pluginName(R.string.rapid_acting_oref) + .description(R.string.description_insulin_rapid) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.java deleted file mode 100644 index 7e800cacc1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.java +++ /dev/null @@ -1,53 +0,0 @@ -package info.nightscout.androidaps.plugins.insulin; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; - -/** - * Created by adrian on 14/08/17. - */ - -public class InsulinOrefUltraRapidActingPlugin extends InsulinOrefBasePlugin { - - private static InsulinOrefUltraRapidActingPlugin plugin = null; - - public static InsulinOrefUltraRapidActingPlugin getPlugin() { - if (plugin == null) - plugin = new InsulinOrefUltraRapidActingPlugin(); - return plugin; - } - - private static final int PEAK = 55; - - private InsulinOrefUltraRapidActingPlugin() { - super(); - pluginDescription - .pluginName(R.string.ultrarapid_oref) - .description(R.string.description_insulin_ultra_rapid); - } - - @Override - public int getId() { - return OREF_ULTRA_RAPID_ACTING; - } - - @Override - public String getName() { - return MainApp.gs(R.string.ultrarapid_oref); - } - - @Override - public String getFriendlyName() { - return MainApp.gs(R.string.ultrarapid_oref); - } - - @Override - public String commentStandardText() { - return MainApp.gs(R.string.ultrafastactinginsulincomment); - } - - @Override - int getPeak() { - return PEAK; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt new file mode 100644 index 0000000000..6d854bbdee --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.plugins.insulin + +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.InsulinInterface +import javax.inject.Inject + +/** + * Created by adrian on 14/08/17. + */ +class InsulinOrefUltraRapidActingPlugin @Inject constructor(): InsulinOrefBasePlugin() { + + override fun getId(): Int { + return InsulinInterface.OREF_ULTRA_RAPID_ACTING + } + + override fun getName(): String { + return MainApp.gs(R.string.ultrarapid_oref) + } + + override fun getFriendlyName(): String { + return MainApp.gs(R.string.ultrarapid_oref) + } + + override fun commentStandardText(): String { + return MainApp.gs(R.string.ultrafastactinginsulincomment) + } + + override val peak = 55 + + + init { + pluginDescription + .pluginName(R.string.ultrarapid_oref) + .description(R.string.description_insulin_ultra_rapid) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index 4478c025d4..fd25e0e43f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.MIN_DIA +import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.Companion.MIN_DIA import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.utils.* import io.reactivex.android.schedulers.AndroidSchedulers diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java index b69f3f4dc7..49acf3e2a9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java @@ -3,6 +3,8 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -25,10 +27,14 @@ public class CommandSetProfile extends Command { private Profile profile; + @Inject + SmsCommunicatorPlugin smsCommunicatorPlugin; + public CommandSetProfile(Profile profile, Callback callback) { commandType = CommandType.BASALPROFILE; this.profile = profile; this.callback = callback; + MainApp.instance().androidInjector().inject(this); // TODO: Inject via constructor } @Override @@ -50,7 +56,6 @@ public class CommandSetProfile extends Command { // Send SMS notification if ProfileSwitch is comming from NS ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); if (profileSwitch != null && r.enacted && profileSwitch.source == Source.NIGHTSCOUT) { - SmsCommunicatorPlugin smsCommunicatorPlugin = SmsCommunicatorPlugin.INSTANCE; if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) { smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.gs(R.string.profile_set_ok)); } 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 5907ac8392..07193d14f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -11,6 +11,8 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; @@ -47,6 +49,16 @@ public class DataService extends IntentService { super("DataService"); } + @Inject + SmsCommunicatorPlugin smsCommunicatorPlugin; + + @Override + public void onCreate() { + super.onCreate(); + ((MainApp) getApplication()).androidInjector().inject(this); + + } + @Override protected void onHandleIntent(final Intent intent) { if (L.isEnabled(L.DATASERVICE)) { @@ -99,7 +111,7 @@ public class DataService extends IntentService { ) { handleNewDataFromNSClient(intent); } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { - SmsCommunicatorPlugin.INSTANCE.handleNewData(intent); + smsCommunicatorPlugin.handleNewData(intent); } if (L.isEnabled(L.DATASERVICE)) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java index fdee5417a3..488ef314f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.java @@ -80,8 +80,8 @@ public class AndroidPermission { return !selfCheck; } - public static synchronized void notifyForSMSPermissions(Activity activity) { - if (SmsCommunicatorPlugin.INSTANCE.isEnabled(PluginType.GENERAL)) { + public static synchronized void notifyForSMSPermissions(Activity activity, SmsCommunicatorPlugin smsCommunicatorPlugin) { + if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) { if (permissionNotGranted(activity, Manifest.permission.RECEIVE_SMS)) { NotificationWithAction notification = new NotificationWithAction(Notification.PERMISSION_SMS, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.URGENT); notification.action(R.string.request, () -> AndroidPermission.askForPermission(activity, new String[]{Manifest.permission.RECEIVE_SMS, diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java index 39c5f3279e..38911796b0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.configBuilder; import junit.framework.Assert; import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; @@ -18,18 +19,21 @@ import info.nightscout.androidaps.utils.SP; public class ConfigBuilderPluginTest { @Test + @Ignore public void getPluginTest() { ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin(); Assert.assertNotNull(configBuilderPlugin); } @Test + @Ignore public void onStartTest() { ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin(); configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, true); } @Test + @Ignore public void onStopTest() { ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin(); configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, true); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java index 84b7f4c3fa..a00c029ce9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java @@ -15,6 +15,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import java.util.ArrayList; import java.util.List; +import dagger.Lazy; import info.AAPSMocker; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; @@ -30,6 +31,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; +import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin; @@ -902,7 +904,9 @@ public class SmsCommunicatorPluginTest { when(SmsManager.getDefault()).thenReturn(smsManager); when(SP.getString(R.string.key_smscommunicator_allowednumbers, "")).thenReturn("1234;5678"); - smsCommunicatorPlugin = SmsCommunicatorPlugin.INSTANCE; + Lazy insulinOrefRapidActingPlugin = InsulinOrefRapidActingPlugin::new; + ConfigBuilderPlugin configBuilderPlugin = new ConfigBuilderPlugin(insulinOrefRapidActingPlugin); + smsCommunicatorPlugin = new SmsCommunicatorPlugin(configBuilderPlugin); smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true); mockStatic(LoopPlugin.class); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.java index 0e859b93e2..28d5656b41 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.java @@ -82,7 +82,7 @@ public class InsulinOrefBasePluginTest extends InsulinOrefBasePlugin { * @return */ @Override - int getPeak() { + public int getPeak() { return this.peak; } @@ -95,7 +95,7 @@ public class InsulinOrefBasePluginTest extends InsulinOrefBasePlugin { return this.dia; } - void sendShortDiaNotification(double dia) { + public void sendShortDiaNotification(double dia) { this.shortDiaNotificationSend = true; } @@ -110,7 +110,7 @@ public class InsulinOrefBasePluginTest extends InsulinOrefBasePlugin { } @Override - String commentStandardText() { + public String commentStandardText() { return null; } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt index a0e5b7954c..298e610ba3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.insulin import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP import junit.framework.Assert.assertEquals @@ -34,7 +35,7 @@ class InsulinOrefFreePeakPluginTest { lateinit var sp: SP @Mock - lateinit var resourceHelper: ResourceHelperImplementation + lateinit var resourceHelper: ResourceHelper @Before fun setup() { From dc037cc248f77c0a5f2576b81ddcd1ccf48426a6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 10:52:24 +0100 Subject: [PATCH 036/316] resources to SMSCommunicatorPlugin --- .../smsCommunicator/SmsCommunicatorPlugin.kt | 150 ++++++++---------- .../insulin/InsulinOrefFreePeakPlugin.kt | 2 +- .../utils/resources/ResourceHelper.kt | 6 +- .../resources/ResourceHelperImplementation.kt | 6 +- 4 files changed, 77 insertions(+), 87 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 2103856af1..158864bb74 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -39,6 +39,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.apache.commons.lang3.StringUtils @@ -49,7 +50,10 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigBuilderPlugin) : PluginBase(PluginDescription() +class SmsCommunicatorPlugin @Inject constructor( + val configBuilderPlugin: ConfigBuilderPlugin, + val resourceHelper: ResourceHelper +) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(SmsCommunicatorFragment::class.java.name) .pluginName(R.string.smscommunicator) @@ -82,12 +86,8 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB "HELP" to "HELP\nHELP command" ) - /*init { - processSettings(null) - }*/ - override fun onStart() { - processSettings(null) // TODO moved from init block to avoid cyclic calling MainApp via SP while we are still in MainApp.onCreate() + processSettings(null) super.onStart() disposable.add(toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) @@ -102,28 +102,28 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB override fun preprocessPreferences(preferenceFragment: PreferenceFragment) { super.preprocessPreferences(preferenceFragment) - val distance = preferenceFragment.findPreference(MainApp.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference? + val distance = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference? ?: return - val allowedNumbers = preferenceFragment.findPreference(MainApp.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference? + val allowedNumbers = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference? ?: return if (!areMoreNumbers(allowedNumbers.text)) { - distance.title = (MainApp.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = (resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) + ".\n" - + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + + resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) distance.isEnabled = false } else { - distance.title = MainApp.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) distance.isEnabled = true } allowedNumbers.onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, newValue: Any -> if (!areMoreNumbers(newValue as String)) { distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString() - distance.title = (MainApp.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = (resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) + ".\n" - + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) + + resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance_caveat)) distance.isEnabled = false } else { - distance.title = MainApp.gs(R.string.smscommunicator_remotebolusmindistance) + distance.title = resourceHelper.gs(R.string.smscommunicator_remotebolusmindistance) distance.isEnabled = true } true @@ -135,7 +135,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB if (pref is EditTextPreference) { val editTextPref = pref if (pref.getKey().contains("smscommunicator_allowednumbers") && (editTextPref.text == null || TextUtils.isEmpty(editTextPref.text.trim { it <= ' ' }))) { - pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary)) + pref.setSummary(resourceHelper.gs(R.string.smscommunicator_allowednumbers_summary)) } } } @@ -266,23 +266,23 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB var reply = "" val units = ProfileFunctions.getSystemUnits() if (actualBG != null) { - reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", " + reply = resourceHelper.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", " } else if (lastBG != null) { val agoMsec = System.currentTimeMillis() - lastBG.date val agoMin = (agoMsec / 60.0 / 1000.0).toInt() - reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", " + reply = resourceHelper.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(resourceHelper.gs(R.string.sms_minago), agoMin) + ", " } val glucoseStatus = GlucoseStatus.getGlucoseStatusData() - if (glucoseStatus != null) reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " + if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " TreatmentsPlugin.getPlugin().updateTotalIOBTreatments() val bolusIob = TreatmentsPlugin.getPlugin().lastCalculationTreatments.round() TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals() val basalIob = TreatmentsPlugin.getPlugin().lastCalculationTempBasals.round() val cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB") - reply += (MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" - + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " - + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " - + MainApp.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) + reply += (resourceHelper.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" + + resourceHelper.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + + resourceHelper.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), " + + resourceHelper.gs(R.string.cob) + ": " + cobInfo.generateCOBString()) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } @@ -296,8 +296,8 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { send(EventRefreshOverview("SMS_LOOP_STOP")) - val replyText = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " + - MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + val replyText = resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled) + " " + + resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } }) @@ -320,10 +320,10 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB "STATUS" -> { val loopPlugin = LoopPlugin.getPlugin() val reply = if (loopPlugin.isEnabled(PluginType.LOOP)) { - if (loopPlugin.isSuspended()) String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) - else MainApp.gs(R.string.smscommunicator_loopisenabled) + if (loopPlugin.isSuspended()) String.format(resourceHelper.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) + else resourceHelper.gs(R.string.smscommunicator_loopisenabled) } else - MainApp.gs(R.string.smscommunicator_loopisdisabled) + resourceHelper.gs(R.string.smscommunicator_loopisdisabled) sendSMS(Sms(receivedSms.phoneNumber, reply)) receivedSms.processed = true } @@ -346,7 +346,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB return } else { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(duration) { override fun run() { @@ -356,11 +356,11 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + anInteger() * 60L * 1000) NSUpload.uploadOpenAPSOffline(anInteger() * 60.toDouble()) send(EventRefreshOverview("SMS_LOOP_SUSPENDED")) - val replyText = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " + - MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + val replyText = resourceHelper.gs(R.string.smscommunicator_loopsuspended) + " " + + resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -417,7 +417,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB sendSMS(Sms(receivedSms.phoneNumber, reply)) } } else { - val reply = MainApp.gs(R.string.readstatusfailed) + val reply = resourceHelper.gs(R.string.readstatusfailed) sendSMS(Sms(receivedSms.phoneNumber, reply)) } } @@ -427,11 +427,6 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB private fun processPROFILE(splitted: Array, receivedSms: Sms) { // load profiles val anInterface = configBuilderPlugin.activeProfileInterface - if (anInterface == null) { - sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured)) - receivedSms.processed = true - return - } val store = anInterface.profile if (store == null) { sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured)) @@ -439,11 +434,6 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB return } val profileName = ProfileFunctions.getInstance().getProfileName() - if (profileName == null) { - sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured)) - receivedSms.processed = true - return - } val list = store.getProfileList() if (splitted[1].toUpperCase(Locale.getDefault()) == "STATUS") { sendSMS(Sms(receivedSms.phoneNumber, profileName)) @@ -470,7 +460,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, R.string.noprofile)) else { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_profilereplywithcode), list[pindex - 1], percentage, passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_profilereplywithcode), list[pindex - 1], percentage, passCode) receivedSms.processed = true val finalPercentage = percentage messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) { @@ -488,18 +478,18 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB private fun processBASAL(splitted: Array, receivedSms: Sms) { if (splitted[1].toUpperCase(Locale.getDefault()) == "CANCEL" || splitted[1].toUpperCase(Locale.getDefault()) == "STOP") { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalstopreplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() { override fun run() { if (result.success) { - var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcanceled) + var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcanceled) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalcancelfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -518,7 +508,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB else { tempBasalPct = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(tempBasalPct, duration) { override fun run() { @@ -526,11 +516,11 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB override fun run() { if (result.success) { var replyText: String - replyText = if (result.isPercent) String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) + replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_tempbasalfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -550,19 +540,19 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB else { tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(tempBasal), profile).value() val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(tempBasal, duration) { override fun run() { configBuilderPlugin.commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, object : Callback() { override fun run() { if (result.success) { - var replyText = if (result.isPercent) String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) - else String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) + var replyText = if (result.isPercent) String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) + else String.format(resourceHelper.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_tempbasalfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_tempbasalfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -577,18 +567,18 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB private fun processEXTENDED(splitted: Array, receivedSms: Sms) { if (splitted[1].toUpperCase(Locale.getDefault()) == "CANCEL" || splitted[1].toUpperCase(Locale.getDefault()) == "STOP") { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { configBuilderPlugin.commandQueue.cancelExtended(object : Callback() { override fun run() { if (result.success) { - var replyText = MainApp.gs(R.string.smscommunicator_extendedcanceled) + var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcanceled) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_extendedcancelfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_extendedcancelfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -605,18 +595,18 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(extended, duration) { override fun run() { configBuilderPlugin.commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() { override fun run() { if (result.success) { - var replyText = String.format(MainApp.gs(R.string.smscommunicator_extendedset), aDouble, duration) + var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_extendedfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_extendedfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -637,9 +627,9 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB } else if (bolus > 0.0) { val passCode = generatePasscode() val reply = if (isMeal) - String.format(MainApp.gs(R.string.smscommunicator_mealbolusreplywithcode), bolus, passCode) + String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusreplywithcode), bolus, passCode) else - String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode) + String.format(resourceHelper.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(bolus) { override fun run() { @@ -654,9 +644,9 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB override fun run() { if (resultSuccess) { var replyText = if (isMeal) - String.format(MainApp.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) + String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered) else - String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) + String.format(resourceHelper.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) lastRemoteBolusTime = DateUtil.now() if (isMeal) { @@ -673,7 +663,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(eatingSoonTTDuration) - .reason(MainApp.gs(R.string.eatingsoon)) + .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) .low(Profile.toMgdl(eatingSoonTT, currentProfile.units)) .high(Profile.toMgdl(eatingSoonTT, currentProfile.units)) @@ -681,12 +671,12 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB val tt = if (currentProfile.units == Constants.MMOL) { DecimalFormatter.to1Decimal(eatingSoonTT) } else DecimalFormatter.to0Decimal(eatingSoonTT) - replyText += "\n" + String.format(MainApp.gs(R.string.smscommunicator_mealbolusdelivered_tt), tt, eatingSoonTTDuration) + replyText += "\n" + String.format(resourceHelper.gs(R.string.smscommunicator_mealbolusdelivered_tt), tt, eatingSoonTTDuration) } } sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_bolusfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_bolusfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -715,7 +705,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_carbsreplywithcode), grams, DateUtil.timeString(time), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode), grams, DateUtil.timeString(time), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(grams, time) { override fun run() { @@ -725,11 +715,11 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (result.success) { - var replyText = String.format(MainApp.gs(R.string.smscommunicator_carbsset), anInteger) + var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_carbsset), anInteger) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { - var replyText = MainApp.gs(R.string.smscommunicator_carbsfailed) + var replyText = resourceHelper.gs(R.string.smscommunicator_carbsfailed) replyText += "\n" + configBuilderPlugin.activePump?.shortStatus(true) sendSMS(Sms(receivedSms.phoneNumber, replyText)) } @@ -747,7 +737,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB val isStop = splitted[1].equals("STOP", ignoreCase = true) || splitted[1].equals("CANCEL", ignoreCase = true) if (isMeal || isActivity || isHypo) { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_temptargetwithcode), splitted[1].toUpperCase(Locale.getDefault()), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetwithcode), splitted[1].toUpperCase(Locale.getDefault()), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { @@ -784,19 +774,19 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(ttDuration) - .reason(MainApp.gs(R.string.eatingsoon)) + .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) .low(Profile.toMgdl(tt, units)) .high(Profile.toMgdl(tt, units)) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) val ttString = if (units == Constants.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt) - val replyText = String.format(MainApp.gs(R.string.smscommunicator_tt_set), ttString, ttDuration) + val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_tt_set), ttString, ttDuration) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } }) } else if (isStop) { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_temptargetcancel), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_temptargetcancel), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { @@ -807,7 +797,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB .low(0.0) .high(0.0) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) - val replyText = String.format(MainApp.gs(R.string.smscommunicator_tt_canceled)) + val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_tt_canceled)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } }) @@ -820,12 +810,12 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB || splitted[1].equals("DISABLE", ignoreCase = true)) if (isStop) { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_stopsmswithcode), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_stopsmswithcode), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() { override fun run() { SP.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false) - val replyText = String.format(MainApp.gs(R.string.smscommunicator_stoppedsms)) + val replyText = String.format(resourceHelper.gs(R.string.smscommunicator_stoppedsms)) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } }) @@ -836,7 +826,7 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB val cal = SafeParse.stringToDouble(splitted[1]) if (cal > 0.0) { val passCode = generatePasscode() - val reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode) receivedSms.processed = true messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(cal) { override fun run() { @@ -877,16 +867,16 @@ class SmsCommunicatorPlugin @Inject constructor(val configBuilderPlugin: ConfigB messages.add(sms) } catch (e: IllegalArgumentException) { return if (e.message == "Invalid message body") { - val notification = Notification(Notification.INVALID_MESSAGE_BODY, MainApp.gs(R.string.smscommunicator_messagebody), Notification.NORMAL) + val notification = Notification(Notification.INVALID_MESSAGE_BODY, resourceHelper.gs(R.string.smscommunicator_messagebody), Notification.NORMAL) send(EventNewNotification(notification)) false } else { - val notification = Notification(Notification.INVALID_PHONE_NUMBER, MainApp.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL) + val notification = Notification(Notification.INVALID_PHONE_NUMBER, resourceHelper.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL) send(EventNewNotification(notification)) false } } catch (e: SecurityException) { - val notification = Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL) + val notification = Notification(Notification.MISSING_SMS_PERMISSION, resourceHelper.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL) send(EventNewNotification(notification)) return false } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index b3da1d9ff0..d5d1a23c1a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -21,7 +21,7 @@ class InsulinOrefFreePeakPlugin @Inject constructor( } override fun getFriendlyName(): String { - return resourceHelper.gs(R.string.free_peak_oref) ?: "" + return resourceHelper.gs(R.string.free_peak_oref) } override fun commentStandardText(): String { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt index 2eb62f6ee6..05ccefa885 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt @@ -5,8 +5,8 @@ import androidx.annotation.PluralsRes import androidx.annotation.StringRes interface ResourceHelper { - fun gs(@StringRes id: Int): String? - fun gs(@StringRes id: Int, vararg args: Any?): String? - fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String? + fun gs(@StringRes id: Int): String + fun gs(@StringRes id: Int, vararg args: Any?): String + fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String fun gc(@ColorRes id: Int): Int? } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt index 08660d3745..27bae38938 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt @@ -12,11 +12,11 @@ import javax.inject.Inject */ class ResourceHelperImplementation @Inject constructor(private val mainApp: MainApp) : ResourceHelper { - override fun gs(@StringRes id: Int): String? = mainApp.getString(id) + override fun gs(@StringRes id: Int): String = mainApp.getString(id) - override fun gs(@StringRes id: Int, vararg args: Any?): String? = mainApp.getString(id, *args) + override fun gs(@StringRes id: Int, vararg args: Any?): String = mainApp.getString(id, *args) - override fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String? = + override fun gq(@PluralsRes id: Int, quantity: Int, vararg args: Any?): String = mainApp.resources.getQuantityString(id, quantity, *args) override fun gc(@ColorRes id: Int): Int = ContextCompat.getColor(mainApp, id) From 7f8abcf591d969bc4d393b9d3f149932539bc502 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 19:20:38 +0100 Subject: [PATCH 037/316] Constraints, Dialogs daggerize --- .../info/nightscout/androidaps/MainApp.java | 10 +- .../androidaps/data/ConstraintChecker.java | 237 ------------------ .../dependencyInjection/AppModule.kt | 7 + .../dependencyInjection/FragmentsModule.kt | 38 +++ .../androidaps/dialogs/CalibrationDialog.kt | 27 +- .../androidaps/dialogs/CarbsDialog.kt | 54 ++-- .../androidaps/dialogs/CareDialog.kt | 24 +- .../dialogs/DialogFragmentWithDate.kt | 4 +- .../androidaps/dialogs/ExtendedBolusDialog.kt | 30 ++- .../androidaps/dialogs/FillDialog.kt | 56 +++-- .../androidaps/dialogs/InsulinDialog.kt | 72 +++--- .../androidaps/dialogs/ProfileSwitchDialog.kt | 31 ++- .../androidaps/dialogs/ProfileViewerDialog.kt | 13 +- .../androidaps/dialogs/TempBasalDialog.kt | 44 ++-- .../androidaps/dialogs/TempTargetDialog.kt | 66 +++-- .../androidaps/dialogs/TreatmentDialog.kt | 46 ++-- .../androidaps/dialogs/WizardDialog.kt | 95 ++++--- .../interfaces/ConstraintsInterface.kt.ignore | 62 +++++ .../plugins/aps/loop/APSResult.java | 3 +- .../plugins/aps/loop/LoopPlugin.java | 13 +- .../DetermineBasalAdapterAMAJS.java | 10 +- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 7 +- .../aps/openAPSMA/OpenAPSMAPlugin.java | 5 +- .../DetermineBasalAdapterSMBJS.java | 9 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 16 +- .../configBuilder/ConfigBuilderPlugin.java | 14 +- .../configBuilder/ConstraintChecker.kt | 205 +++++++++++++++ .../objectives/objectives/Objective6.java | 4 +- .../constraints/safety/SafetyPlugin.java | 5 +- .../Dialogs/NewNSTreatmentDialog.java | 9 +- .../general/overview/OverviewFragment.java | 6 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 15 +- .../general/wear/ActionStringHandler.java | 17 +- .../pump/danaR/AbstractDanaRPlugin.java | 5 +- .../plugins/pump/danaR/DanaRPlugin.java | 7 +- .../pump/danaR/comm/MsgBolusStart.java | 4 +- .../danaR/comm/MsgBolusStartWithSpeed.java | 4 +- .../danaR/comm/MsgSetExtendedBolusStart.java | 11 +- .../pump/danaRKorean/DanaRKoreanPlugin.java | 7 +- .../plugins/pump/danaRS/DanaRSPlugin.java | 11 +- ...aRS_Packet_Bolus_Set_Step_Bolus_Start.java | 4 +- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 7 +- .../androidaps/queue/CommandQueue.java | 15 +- .../androidaps/utils/BolusWizard.kt | 3 +- .../androidaps/utils/FabricPrivacy.java | 3 +- app/src/test/java/info/AAPSMocker.java | 6 +- .../interfaces/ConstraintsCheckerTest.java | 6 +- .../plugins/aps/loop/APSResultTest.java | 2 +- .../constraints/safety/SafetyPluginTest.java | 4 +- .../SmsCommunicatorPluginTest.java | 19 +- .../androidaps/queue/CommandQueueTest.java | 12 +- .../androidaps/utils/BolusWizardTest.java | 2 +- 52 files changed, 808 insertions(+), 578 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java create mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 9e5ccb7879..5ff629fb9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; -import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; @@ -112,7 +111,6 @@ public class MainApp extends DaggerApplication { static FirebaseAnalytics mFirebaseAnalytics; static DatabaseHelper sDatabaseHelper = null; - static ConstraintChecker sConstraintsChecker = null; static ArrayList pluginsList = null; @@ -138,7 +136,6 @@ public class MainApp extends DaggerApplication { sInstance = this; sResources = getResources(); LocaleHelper.INSTANCE.update(this); - sConstraintsChecker = new ConstraintChecker(); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { @@ -258,7 +255,6 @@ public class MainApp extends DaggerApplication { } - private void doMigrations() { // guarantee that the unreachable threshold is at least 30 and of type String @@ -345,10 +341,6 @@ public class MainApp extends DaggerApplication { return mFirebaseAnalytics; } - public static ConstraintChecker getConstraintChecker() { - return sConstraintsChecker; - } - public static ArrayList getPluginsList() { return pluginsList; } @@ -382,7 +374,7 @@ public class MainApp extends DaggerApplication { return newList; } - public static ArrayList getSpecificPluginsListByInterface(Class interfaceClass) { + public ArrayList getSpecificPluginsListByInterface(Class interfaceClass) { ArrayList newList = new ArrayList<>(); if (pluginsList != null) { diff --git a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java deleted file mode 100644 index 9d7a49493b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java +++ /dev/null @@ -1,237 +0,0 @@ -package info.nightscout.androidaps.data; - -import androidx.annotation.NonNull; - -import java.util.ArrayList; - -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginType; - -/** - * Created by mike on 19.03.2018. - */ - -public class ConstraintChecker implements ConstraintsInterface { - - public Constraint isLoopInvokationAllowed() { - return isLoopInvocationAllowed(new Constraint<>(true)); - } - - public Constraint isClosedLoopAllowed() { - return isClosedLoopAllowed(new Constraint<>(true)); - } - - public Constraint isAutosensModeEnabled() { - return isAutosensModeEnabled(new Constraint<>(true)); - } - - public Constraint isAMAModeEnabled() { - return isAMAModeEnabled(new Constraint<>(true)); - } - - public Constraint isSMBModeEnabled() { - return isSMBModeEnabled(new Constraint<>(true)); - } - - public Constraint isUAMEnabled() { - return isUAMEnabled(new Constraint<>(true)); - } - - public Constraint isAdvancedFilteringEnabled() { - return isAdvancedFilteringEnabled(new Constraint<>(true)); - } - - public Constraint isSuperBolusEnabled() { - return isSuperBolusEnabled(new Constraint<>(true)); - } - - public Constraint getMaxBasalAllowed(Profile profile) { - return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile); - } - - public Constraint getMaxBasalPercentAllowed(Profile profile) { - return applyBasalPercentConstraints(new Constraint<>(Constants.REALLYHIGHPERCENTBASALRATE), profile); - } - - public Constraint getMaxBolusAllowed() { - return applyBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS)); - } - - public Constraint getMaxExtendedBolusAllowed() { - return applyExtendedBolusConstraints(new Constraint<>(Constants.REALLYHIGHBOLUS)); - } - - public Constraint getMaxCarbsAllowed() { - return applyCarbsConstraints(new Constraint<>(Constants.REALLYHIGHCARBS)); - } - - public Constraint getMaxIOBAllowed() { - return applyMaxIOBConstraints(new Constraint<>(Constants.REALLYHIGHIOB)); - } - - @Override - public Constraint isLoopInvocationAllowed(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isLoopInvocationAllowed(value); - } - return value; - } - - @Override - public Constraint isClosedLoopAllowed(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isClosedLoopAllowed(value); - } - return value; - } - - @Override - public Constraint isAutosensModeEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isAutosensModeEnabled(value); - } - return value; - } - - @Override - public Constraint isAMAModeEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.isAMAModeEnabled(value); - } - return value; - } - - @Override - public Constraint isSMBModeEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isSMBModeEnabled(value); - } - return value; - } - - @Override - public Constraint isUAMEnabled(@NonNull Constraint value) { - - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isUAMEnabled(value); - } - return value; - } - - @Override - public Constraint isAdvancedFilteringEnabled(@NonNull Constraint value) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isAdvancedFilteringEnabled(value); - } - return value; - } - - @Override - public Constraint isSuperBolusEnabled(@NonNull Constraint value) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.isSuperBolusEnabled(value); - } - return value; - } - - @Override - public Constraint applyBasalConstraints(@NonNull Constraint absoluteRate, Profile profile) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constraint = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constraint.applyBasalConstraints(absoluteRate, profile); - } - return absoluteRate; - } - - @Override - public Constraint applyBasalPercentConstraints(@NonNull Constraint percentRate, Profile profile) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyBasalPercentConstraints(percentRate, profile); - } - return percentRate; - } - - @Override - public Constraint applyBolusConstraints(@NonNull Constraint insulin) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyBolusConstraints(insulin); - } - return insulin; - } - - @Override - public Constraint applyExtendedBolusConstraints(@NonNull Constraint insulin) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyExtendedBolusConstraints(insulin); - } - return insulin; - } - - @Override - public Constraint applyCarbsConstraints(@NonNull Constraint carbs) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyCarbsConstraints(carbs); - } - return carbs; - } - - @Override - public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) { - ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); - for (PluginBase p : constraintsPlugins) { - ConstraintsInterface constrain = (ConstraintsInterface) p; - if (!p.isEnabled(PluginType.CONSTRAINTS)) continue; - constrain.applyMaxIOBConstraints(maxIob); - } - return maxIob; - } - - -} diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index d031bf7267..9d51eda0a5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -7,6 +7,7 @@ import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS @@ -33,6 +34,12 @@ class AppModule { return ProfileFunctionImplementation(sp) } + @Provides + @Singleton + fun provideConstraintChecker(mainApp: MainApp): ConstraintChecker { + return ConstraintChecker(mainApp) + } + @Provides @Singleton fun provideResources(mainApp: MainApp): ResourceHelper { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index 162f156fe3..ea7ba7e9e2 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -3,13 +3,51 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.activities.MyPreferenceFragment +import info.nightscout.androidaps.dialogs.* import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment @Module abstract class FragmentsModule { + @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + + @ContributesAndroidInjector + abstract fun contributesCalibrationDialog(): CalibrationDialog + + @ContributesAndroidInjector + abstract fun contributesCarbsDialog(): CarbsDialog + + @ContributesAndroidInjector + abstract fun contributesCareDialog(): CareDialog + + @ContributesAndroidInjector + abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog + + @ContributesAndroidInjector + abstract fun contributesFillDialog(): FillDialog + + @ContributesAndroidInjector + abstract fun contributesInsulinDialog(): InsulinDialog + + @ContributesAndroidInjector + abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog + + @ContributesAndroidInjector + abstract fun contributesProfileViewerDialog(): ProfileViewerDialog + + @ContributesAndroidInjector + abstract fun contributesTempBasalDialog(): TempBasalDialog + + @ContributesAndroidInjector + abstract fun contributesTempTargetDialog(): TempTargetDialog + + @ContributesAndroidInjector + abstract fun contributesTreatmentDialog(): TreatmentDialog + + @ContributesAndroidInjector + abstract fun contributesWizardDialog(): WizardDialog } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt index 949e4e5fef..39b0b8a0f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt @@ -6,21 +6,28 @@ import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.XdripCalibrations +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_calibration.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class CalibrationDialog : DialogFragmentWithDate() { + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_calibration_bg", overview_calibration_bg.value) @@ -35,7 +42,7 @@ class CalibrationDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val units = ProfileFunctions.getSystemUnits() + val units = profileFunction.getUnits() val bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData()?.glucose ?: 0.0, units) if (units == Constants.MMOL) @@ -44,24 +51,24 @@ class CalibrationDialog : DialogFragmentWithDate() { else overview_calibration_bg.setParams(savedInstanceState?.getDouble("overview_calibration_bg") ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, ok) - overview_calibration_units.text = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + overview_calibration_units.text = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) } - override fun submit() :Boolean { - val units = ProfileFunctions.getSystemUnits() - val unitLabel = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + override fun submit(): Boolean { + val units = profileFunction.getUnits() + val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val actions: LinkedList = LinkedList() val bg = overview_calibration_bg.value - actions.add(MainApp.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(bg) + " " + unitLabel) + actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(bg) + " " + unitLabel) if (bg > 0) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { XdripCalibrations.confirmAndSendCalibration(bg, context) }) } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.overview_calibration), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.overview_calibration), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index 4e0e2980e8..b7acc5cc58 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -16,28 +16,38 @@ import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_carbs.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.max class CarbsDialog : DialogFragmentWithDate() { + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var constraintChecker: ConstraintChecker + companion object { private const val FAV1_DEFAULT = 5 private const val FAV2_DEFAULT = 10 private const val FAV3_DEFAULT = 20 } - private val maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value().toDouble() - private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) { validateInputs() @@ -48,18 +58,19 @@ class CarbsDialog : DialogFragmentWithDate() { } private fun validateInputs() { + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val time = overview_carbs_time.value.toInt() if (time > 12 * 60 || time < -12 * 60) { overview_carbs_time.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (overview_carbs_duration.value > 10) { overview_carbs_duration.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (overview_carbs_carbs.value.toInt() > maxCarbs) { overview_carbs_carbs.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) } } @@ -79,6 +90,7 @@ class CarbsDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() overview_carbs_time.setParams(savedInstanceState?.getDouble("overview_carbs_time") ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) @@ -133,7 +145,7 @@ class CarbsDialog : DialogFragmentWithDate() { override fun submit(): Boolean { val carbs = overview_carbs_carbs.value.toInt() - val carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() val units = ProfileFunctions.getSystemUnits() val activityTTDuration = DefaultValueHelper.determineActivityTTDuration() val activityTT = DefaultValueHelper.determineActivityTT() @@ -142,42 +154,42 @@ class CarbsDialog : DialogFragmentWithDate() { val hypoTTDuration = DefaultValueHelper.determineHypoTTDuration() val hypoTT = DefaultValueHelper.determineHypoTT() val actions: LinkedList = LinkedList() - val unitLabel = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val activitySelected = overview_carbs_activity_tt.isChecked if (activitySelected) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + activityTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(activityTT) + " " + unitLabel + " (" + activityTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val eatingSoonSelected = overview_carbs_eating_soon_tt.isChecked if (eatingSoonSelected) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val hypoSelected = overview_carbs_hypo_tt.isChecked if (hypoSelected) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + hypoTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(hypoTT) + " " + unitLabel + " (" + hypoTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val timeOffset = overview_carbs_time.value.toInt() val time = DateUtil.now() + timeOffset * 1000 * 60 if (timeOffset != 0) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) val duration = overview_carbs_duration.value.toInt() if (duration > 0) - actions.add(MainApp.gs(R.string.duration) + ": " + duration + MainApp.gs(R.string.shorthour)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) if (carbsAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.carbs) + ": " + "" + MainApp.gs(R.string.format_carbs, carbsAfterConstraints) + "") + actions.add(resourceHelper.gs(R.string.carbs) + ": " + "" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "") if (carbsAfterConstraints != carbs) - actions.add("" + MainApp.gs(R.string.carbsconstraintapplied) + "") + actions.add("" + resourceHelper.gs(R.string.carbsconstraintapplied) + "") } val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (activitySelected) { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(activityTTDuration) - .reason(MainApp.gs(R.string.activity)) + .reason(resourceHelper.gs(R.string.activity)) .source(Source.USER) .low(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits())) .high(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits())) @@ -186,7 +198,7 @@ class CarbsDialog : DialogFragmentWithDate() { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(eatingSoonTTDuration) - .reason(MainApp.gs(R.string.eatingsoon)) + .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) .low(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) .high(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) @@ -195,7 +207,7 @@ class CarbsDialog : DialogFragmentWithDate() { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(hypoTTDuration) - .reason(MainApp.gs(R.string.hypo)) + .reason(resourceHelper.gs(R.string.hypo)) .source(Source.USER) .low(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits())) .high(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits())) @@ -206,14 +218,14 @@ class CarbsDialog : DialogFragmentWithDate() { CarbsGenerator.createCarb(carbsAfterConstraints, time, CareportalEvent.CARBCORRECTION, notes) } else { CarbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes) - NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, MainApp.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) + NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) } } }, null) } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.carbs), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.carbs), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index 946a3fec5b..39329a94e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -21,15 +21,23 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SP import info.nightscout.androidaps.utils.Translator +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_care.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import org.json.JSONObject import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class CareDialog : DialogFragmentWithDate() { + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + enum class EventType { BGCHECK, SENSOR_INSERT, @@ -65,7 +73,7 @@ class CareDialog : DialogFragmentWithDate() { EventType.SENSOR_INSERT -> R.drawable.icon_cp_cgm_insert EventType.BATTERY_CHANGE -> R.drawable.icon_cp_pump_battery }) - actions_care_title.text = MainApp.gs(when (options) { + actions_care_title.text = resourceHelper.gs(when (options) { EventType.BGCHECK -> R.string.careportal_bgcheck EventType.SENSOR_INSERT -> R.string.careportal_cgmsensorinsert EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange @@ -93,11 +101,11 @@ class CareDialog : DialogFragmentWithDate() { } if (ProfileFunctions.getSystemUnits() == Constants.MMOL) { - actions_care_bgunits.text = MainApp.gs(R.string.mmol) + actions_care_bgunits.text = resourceHelper.gs(R.string.mmol) actions_care_bg.setParams(savedInstanceState?.getDouble("actions_care_bg") ?: bg, 2.0, 30.0, 0.1, DecimalFormat("0.0"), false, ok, bgTextWatcher) } else { - actions_care_bgunits.text = MainApp.gs(R.string.mgdl) + actions_care_bgunits.text = resourceHelper.gs(R.string.mgdl) actions_care_bg.setParams(savedInstanceState?.getDouble("actions_care_bg") ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, ok, bgTextWatcher) } @@ -116,18 +124,18 @@ class CareDialog : DialogFragmentWithDate() { actions_care_sensor.isChecked -> "Sensor" else -> "Manual" } - actions.add(MainApp.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) - actions.add(MainApp.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(actions_care_bg.value) + " " + MainApp.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype) + ": " + Translator.translate(type)) + actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(actions_care_bg.value) + " " + resourceHelper.gs(unitResId)) json.put("glucose", actions_care_bg.value) json.put("glucoseType", type) } val notes = notes.text.toString() if (notes.isNotEmpty()) { - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) json.put("notes", notes) } if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) json.put("created_at", DateUtil.toISOString(eventTime)) json.put("eventType", when (options) { @@ -140,7 +148,7 @@ class CareDialog : DialogFragmentWithDate() { json.put("enteredBy", enteredBy) activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(event), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(event), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json) NSUpload.uploadCareportalEntryToNS(json) }, null) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt index da45e77990..407689a53d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt @@ -8,7 +8,7 @@ import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager -import androidx.fragment.app.DialogFragment +import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.SP @@ -19,7 +19,7 @@ import kotlinx.android.synthetic.main.okcancel.* import org.slf4j.LoggerFactory import java.util.* -abstract class DialogFragmentWithDate : DialogFragment() { +abstract class DialogFragmentWithDate : DaggerDialogFragment() { private val log = LoggerFactory.getLogger(DialogFragmentWithDate::class.java) var eventTime = DateUtil.now() diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt index a717e79b49..e730e513fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -11,18 +11,30 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_extendedbolus.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs class ExtendedBolusDialog : DialogFragmentWithDate() { + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var constraintChecker: ConstraintChecker + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("actions_extendedbolus_insulin", actions_extendedbolus_insulin.value) @@ -40,7 +52,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return - val maxInsulin = MainApp.getConstraintChecker().maxExtendedBolusAllowed.value() + val maxInsulin = constraintChecker.getMaxExtendedBolusAllowed().value() val extendedStep = pumpDescription.extendedBolusStep actions_extendedbolus_insulin.setParams(savedInstanceState?.getDouble("actions_extendedbolus_insulin") ?: extendedStep, extendedStep, maxInsulin, extendedStep, DecimalFormat("0.00"), false, ok) @@ -55,23 +67,23 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text) val durationInMinutes = SafeParse.stringToInt(actions_extendedbolus_duration.text) val actions: LinkedList = LinkedList() - val insulinAfterConstraint = MainApp.getConstraintChecker().applyExtendedBolusConstraints(Constraint(insulin)).value() - actions.add(MainApp.gs(R.string.formatinsulinunits, insulinAfterConstraint)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes)) + val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() + actions.add(resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraint)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) if (abs(insulinAfterConstraint - insulin) > 0.01) - actions.add("" + MainApp.gs(R.string.constraintapllied) + "") + actions.add("" + resourceHelper.gs(R.string.constraintapllied) + "") activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { ConfigBuilderPlugin.getPlugin().commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 8d55df9bc1..b865f76745 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -14,17 +14,37 @@ import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.DecimalFormatter +import info.nightscout.androidaps.utils.HtmlHelper +import info.nightscout.androidaps.utils.OKDialog +import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import kotlinx.android.synthetic.main.dialog_fill.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.util.* +import javax.inject.Inject import kotlin.math.abs class FillDialog : DialogFragmentWithDate() { + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var sp: SP + + @Inject + lateinit var mainApp: MainApp + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("fill_insulinamount", fill_insulinamount.value) @@ -39,11 +59,11 @@ class FillDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - val maxInsulin = MainApp.getConstraintChecker().maxBolusAllowed.value() + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val bolusStep = ConfigBuilderPlugin.getPlugin().activePump!!.pumpDescription.bolusStep fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulinamount") ?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), true, ok) - val amount1 = SP.getDouble("fill_button1", 0.3) + val amount1 = sp.getDouble("fill_button1", 0.3) if (amount1 > 0) { fill_preset_button1.visibility = View.VISIBLE fill_preset_button1.text = DecimalFormatter.toPumpSupportedBolus(amount1) // + "U"); @@ -51,7 +71,7 @@ class FillDialog : DialogFragmentWithDate() { } else { fill_preset_button1.visibility = View.GONE } - val amount2 = SP.getDouble("fill_button2", 0.0) + val amount2 = sp.getDouble("fill_button2", 0.0) if (amount2 > 0) { fill_preset_button2.visibility = View.VISIBLE fill_preset_button2.text = DecimalFormatter.toPumpSupportedBolus(amount2) // + "U"); @@ -59,7 +79,7 @@ class FillDialog : DialogFragmentWithDate() { } else { fill_preset_button2.visibility = View.GONE } - val amount3 = SP.getDouble("fill_button3", 0.0) + val amount3 = sp.getDouble("fill_button3", 0.0) if (amount3 > 0) { fill_preset_button3.visibility = View.VISIBLE fill_preset_button3.text = DecimalFormatter.toPumpSupportedBolus(amount3) // + "U"); @@ -74,29 +94,29 @@ class FillDialog : DialogFragmentWithDate() { val insulin = SafeParse.stringToDouble(fill_insulinamount.text) val actions: LinkedList = LinkedList() - val insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() if (insulinAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.fillwarning)) + actions.add(resourceHelper.gs(R.string.fillwarning)) actions.add("") - actions.add(MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") if (abs(insulinAfterConstraints - insulin) > 0.01) - actions.add(MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), insulin, insulinAfterConstraints)) + actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } val siteChange = fill_catheter_change.isChecked if (siteChange) - actions.add("" + "" + MainApp.gs(R.string.record_pump_site_change) + "") + actions.add("" + "" + resourceHelper.gs(R.string.record_pump_site_change) + "") val insulinChange = fill_cartridge_change.isChecked if (insulinChange) - actions.add("" + "" + MainApp.gs(R.string.record_insulin_cartridge_change) + "") + actions.add("" + "" + resourceHelper.gs(R.string.record_insulin_cartridge_change) + "") val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) if (insulinAfterConstraints > 0 || fill_catheter_change.isChecked || fill_cartridge_change.isChecked) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.primefill), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (insulinAfterConstraints > 0) { val detailedBolusInfo = DetailedBolusInfo() detailedBolusInfo.insulin = insulinAfterConstraints @@ -107,12 +127,12 @@ class FillDialog : DialogFragmentWithDate() { ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) @@ -123,7 +143,7 @@ class FillDialog : DialogFragmentWithDate() { } } else { activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.primefill), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.primefill), resourceHelper.gs(R.string.no_action_selected)) } } dismiss() diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index d6f64d87f1..ca48a3f748 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -19,28 +19,41 @@ import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_insulin.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs import kotlin.math.max class InsulinDialog : DialogFragmentWithDate() { + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + companion object { private const val PLUS1_DEFAULT = 0.5 private const val PLUS2_DEFAULT = 1.0 private const val PLUS3_DEFAULT = 2.0 } - private val maxInsulin = MainApp.getConstraintChecker().maxBolusAllowed.value() - private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) { validateInputs() @@ -51,13 +64,14 @@ class InsulinDialog : DialogFragmentWithDate() { } private fun validateInputs() { + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (abs(overview_insulin_time.value.toInt()) > 12 * 60) { overview_insulin_time.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.constraintapllied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.constraintapllied)) } if (overview_insulin_amount.value > maxInsulin) { overview_insulin_amount.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.bolusconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.bolusconstraintapplied)) } } @@ -76,27 +90,29 @@ class InsulinDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() + overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time") ?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) overview_insulin_amount.setParams(savedInstanceState?.getDouble("overview_insulin_amount") ?: 0.0, 0.0, maxInsulin, ConfigBuilderPlugin.getPlugin().activePump!!.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher) - overview_insulin_plus05.text = toSignedString(SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) + overview_insulin_plus05.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) overview_insulin_plus05.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value - + SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) + + SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT)) validateInputs() } - overview_insulin_plus10.text = toSignedString(SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) + overview_insulin_plus10.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) overview_insulin_plus10.setOnClickListener { overview_insulin_amount.value = max(0.0, overview_insulin_amount.value - + SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) + + SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT)) validateInputs() } - overview_insulin_plus20.text = toSignedString(SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) + overview_insulin_plus20.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) overview_insulin_plus20.setOnClickListener { overview_insulin_amount.value = Math.max(0.0, overview_insulin_amount.value - + SP.getDouble(MainApp.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) + + SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT)) validateInputs() } @@ -115,45 +131,45 @@ class InsulinDialog : DialogFragmentWithDate() { val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return false val insulin = SafeParse.stringToDouble(overview_insulin_amount.text) - val insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(insulin)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() val actions: LinkedList = LinkedList() - val units = ProfileFunctions.getSystemUnits() - val unitLabel = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + val units = profileFunction.getUnits() + val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) val recordOnlyChecked = overview_insulin_record_only.isChecked val eatingSoonChecked = overview_insulin_start_eating_soon_tt.isChecked if (insulinAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (recordOnlyChecked) - actions.add("" + MainApp.gs(R.string.bolusrecordedonly) + "") + actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), insulin, insulinAfterConstraints)) + actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } val eatingSoonTTDuration = DefaultValueHelper.determineEatingSoonTTDuration() val eatingSoonTT = DefaultValueHelper.determineEatingSoonTT() if (eatingSoonChecked) - actions.add(MainApp.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + MainApp.gs(R.string.unit_minute_short) + ")") + actions.add(resourceHelper.gs(R.string.temptargetshort) + ": " + "" + DecimalFormatter.to1Decimal(eatingSoonTT) + " " + unitLabel + " (" + eatingSoonTTDuration + " " + resourceHelper.gs(R.string.unit_minute_short) + ")") val timeOffset = overview_insulin_time.value.toInt() val time = DateUtil.now() + T.mins(timeOffset.toLong()).msecs() if (timeOffset != 0) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (insulinAfterConstraints > 0 || eatingSoonChecked) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.bolus), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (eatingSoonChecked) { val tempTarget = TempTarget() .date(System.currentTimeMillis()) .duration(eatingSoonTTDuration) - .reason(MainApp.gs(R.string.eatingsoon)) + .reason(resourceHelper.gs(R.string.eatingsoon)) .source(Source.USER) - .low(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) - .high(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits())) + .low(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) + .high(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits())) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) } if (insulinAfterConstraints > 0) { @@ -171,12 +187,12 @@ class InsulinDialog : DialogFragmentWithDate() { ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) @@ -186,7 +202,7 @@ class InsulinDialog : DialogFragmentWithDate() { } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.bolus), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.bolus), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 172cd24195..57aaad0736 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -7,22 +7,29 @@ import android.view.ViewGroup import android.widget.ArrayAdapter import com.google.common.base.Joiner import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_profileswitch.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class ProfileSwitchDialog : DialogFragmentWithDate() { + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) @@ -55,14 +62,14 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { overview_profileswitch_profile.adapter = adapter // set selected to actual profile for (p in profileList.indices) - if (profileList[p] == ProfileFunctions.getInstance().getProfileName(false)) + if (profileList[p] == profileFunction.getProfileName(false)) overview_profileswitch_profile.setSelection(p) } ?: return TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now())?.let { ps -> if (ps.isCPP) { overview_profileswitch_reuselayout.visibility = View.VISIBLE - overview_profileswitch_reusebutton.text = MainApp.gs(R.string.reuse) + " " + ps.percentage + "% " + ps.timeshift + "h" + overview_profileswitch_reusebutton.text = resourceHelper.gs(R.string.reuse) + " " + ps.percentage + "% " + ps.timeshift + "h" overview_profileswitch_reusebutton.setOnClickListener { overview_profileswitch_percentage.value = ps.percentage.toDouble() overview_profileswitch_timeshift.value = ps.timeshift.toDouble() @@ -80,24 +87,24 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { val actions: LinkedList = LinkedList() val duration = overview_profileswitch_duration.value if (duration > 0) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_hours, duration)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_hours, duration)) val profile = overview_profileswitch_profile.selectedItem.toString() - actions.add(MainApp.gs(R.string.profile) + ": " + profile) + actions.add(resourceHelper.gs(R.string.profile) + ": " + profile) val percent = overview_profileswitch_percentage.value.toInt() if (percent != 100) - actions.add(MainApp.gs(R.string.percent) + ": " + percent + "%") + actions.add(resourceHelper.gs(R.string.percent) + ": " + percent + "%") val timeShift = overview_profileswitch_timeshift.value.toInt() if (timeShift != 0) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + MainApp.gs(R.string.format_hours, timeShift.toDouble())) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label) + ": " + resourceHelper.gs(R.string.format_hours, timeShift.toDouble())) val notes = notes.text.toString() if (notes.isNotEmpty()) - actions.add(MainApp.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) + actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { - ProfileFunctions.getInstance().doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + profileFunction.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt index ef3b19d4d8..a295e3dafa 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -6,18 +6,23 @@ import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager -import androidx.fragment.app.DialogFragment +import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.close.* import kotlinx.android.synthetic.main.dialog_profileviewer.* import org.json.JSONObject +import javax.inject.Inject + +class ProfileViewerDialog : DaggerDialogFragment() { + + @Inject + lateinit var resourceHelper: ResourceHelper -class ProfileViewerDialog : DialogFragment() { private var time: Long = 0 enum class Mode(val i: Int) { @@ -77,7 +82,7 @@ class ProfileViewerDialog : DialogFragment() { profile?.let { profileview_units.text = it.units - profileview_dia.text = MainApp.gs(R.string.format_hours, it.dia) + profileview_dia.text = resourceHelper.gs(R.string.format_hours, it.dia) profileview_activeprofile.text = profileName profileview_date.text = date profileview_ic.text = it.icList diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt index 77c7df319f..32f54a3083 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -12,18 +12,34 @@ import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_tempbasal.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs class TempBasalDialog : DialogFragmentWithDate() { + + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + private var isPercentPump = true override fun onSaveInstanceState(savedInstanceState: Bundle) { @@ -43,7 +59,7 @@ class TempBasalDialog : DialogFragmentWithDate() { super.onViewCreated(view, savedInstanceState) val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return - val profile = ProfileFunctions.getInstance().getProfile() ?: return + val profile = profileFunction.getProfile() ?: return val maxTempPercent = pumpDescription.maxTempPercent.toDouble() val tempPercentStep = pumpDescription.tempPercentStep.toDouble() @@ -73,33 +89,33 @@ class TempBasalDialog : DialogFragmentWithDate() { var percent = 0 var absolute = 0.0 val durationInMinutes = SafeParse.stringToInt(actions_tempbasal_duration.text) - val profile = ProfileFunctions.getInstance().getProfile() ?: return false + val profile = profileFunction.getProfile() ?: return false val actions: LinkedList = LinkedList() if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text) - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() - actions.add(MainApp.gs(R.string.pump_tempbasal_label)+ ": $percent%") - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes)) - if (percent != basalPercentInput) actions.add(MainApp.gs(R.string.constraintapllied)) + percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() + actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": $percent%") + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) + if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) } else { val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text) - absolute = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() - actions.add(MainApp.gs(R.string.pump_tempbasal_label)+ ": " + MainApp.gs(R.string.pump_basebasalrate, absolute)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes)) + absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() + actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) if (abs(absolute - basalAbsoluteInput) > 0.01) - actions.add("" + MainApp.gs(R.string.constraintapllied) + "") + actions.add("" + resourceHelper.gs(R.string.constraintapllied) + "") } activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { val callback: Callback = object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index 5408105a71..e4ef20554b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -9,25 +9,39 @@ import android.widget.ArrayAdapter import com.google.common.base.Joiner import com.google.common.collect.Lists import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog -import info.nightscout.androidaps.utils.SP +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import kotlinx.android.synthetic.main.dialog_temptarget.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject class TempTargetDialog : DialogFragmentWithDate() { + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var sp: SP + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_temptarget_duration", overview_temptarget_duration.value) @@ -46,7 +60,7 @@ class TempTargetDialog : DialogFragmentWithDate() { overview_temptarget_duration.setParams(savedInstanceState?.getDouble("overview_temptarget_duration") ?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok) - if (ProfileFunctions.getSystemUnits() == Constants.MMOL) + if (profileFunction.getUnits() == Constants.MMOL) overview_temptarget_temptarget.setParams( savedInstanceState?.getDouble("overview_temptarget_temptarget") ?: Constants.MIN_TT_MMOL, @@ -57,16 +71,16 @@ class TempTargetDialog : DialogFragmentWithDate() { ?: Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1.0, DecimalFormat("0"), false, ok) - val units = ProfileFunctions.getSystemUnits() - overview_temptarget_units.text = if (units == Constants.MMOL) MainApp.gs(R.string.mmol) else MainApp.gs(R.string.mgdl) + val units = profileFunction.getUnits() + overview_temptarget_units.text = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl) // temp target context?.let { context -> val reasonList: List = Lists.newArrayList( - MainApp.gs(R.string.manual), - MainApp.gs(R.string.cancel), - MainApp.gs(R.string.eatingsoon), - MainApp.gs(R.string.activity), - MainApp.gs(R.string.hypo) + resourceHelper.gs(R.string.manual), + resourceHelper.gs(R.string.cancel), + resourceHelper.gs(R.string.eatingsoon), + resourceHelper.gs(R.string.activity), + resourceHelper.gs(R.string.hypo) ) val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList) overview_temptarget_reason.adapter = adapterReason @@ -75,27 +89,27 @@ class TempTargetDialog : DialogFragmentWithDate() { val defaultDuration: Double val defaultTarget: Double when (reasonList[position]) { - MainApp.gs(R.string.eatingsoon) -> { + resourceHelper.gs(R.string.eatingsoon) -> { defaultDuration = DefaultValueHelper.determineEatingSoonTTDuration().toDouble() defaultTarget = DefaultValueHelper.determineEatingSoonTT() } - MainApp.gs(R.string.activity) -> { + resourceHelper.gs(R.string.activity) -> { defaultDuration = DefaultValueHelper.determineActivityTTDuration().toDouble() defaultTarget = DefaultValueHelper.determineActivityTT() } - MainApp.gs(R.string.hypo) -> { + resourceHelper.gs(R.string.hypo) -> { defaultDuration = DefaultValueHelper.determineHypoTTDuration().toDouble() defaultTarget = DefaultValueHelper.determineHypoTT() } - MainApp.gs(R.string.cancel) -> { + resourceHelper.gs(R.string.cancel) -> { defaultDuration = 0.0 defaultTarget = 0.0 } - else -> { + else -> { defaultDuration = overview_temptarget_duration.value defaultTarget = overview_temptarget_temptarget.value } @@ -112,21 +126,21 @@ class TempTargetDialog : DialogFragmentWithDate() { override fun submit(): Boolean { val actions: LinkedList = LinkedList() val reason = overview_temptarget_reason.selectedItem.toString() - val unitResId = if (ProfileFunctions.getSystemUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol + val unitResId = if (profileFunction.getUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol val target = overview_temptarget_temptarget.value val duration = overview_temptarget_duration.value if (target != 0.0 && duration != 0.0) { - actions.add(MainApp.gs(R.string.reason) + ": " + reason) - actions.add(MainApp.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + MainApp.gs(unitResId)) - actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_hours, duration)) + actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) + actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(target) + " " + resourceHelper.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_hours, duration)) } else { - actions.add(MainApp.gs(R.string.stoptemptarget)) + actions.add(resourceHelper.gs(R.string.stoptemptarget)) } if (eventTimeChanged) - actions.add(MainApp.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { if (target == 0.0 || duration == 0.0) { val tempTarget = TempTarget() .date(eventTime) @@ -140,11 +154,11 @@ class TempTargetDialog : DialogFragmentWithDate() { .duration(duration.toInt()) .reason(reason) .source(Source.USER) - .low(Profile.toMgdl(target, ProfileFunctions.getSystemUnits())) - .high(Profile.toMgdl(target, ProfileFunctions.getSystemUnits())) + .low(Profile.toMgdl(target, profileFunction.getUnits())) + .high(Profile.toMgdl(target, profileFunction.getUnits())) TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget) } - if (duration == 10.0) SP.putBoolean(R.string.key_objectiveusetemptarget, true) + if (duration == 10.0) sp.putBoolean(R.string.key_objectiveusetemptarget, true) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index 8667befaf2..15006a1371 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -16,6 +16,7 @@ import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DecimalFormatter @@ -23,15 +24,24 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.ToastUtils +import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_treatment.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs class TreatmentDialog : DialogFragmentWithDate() { - private var maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value().toDouble() - private var maxInsulin = MainApp.getConstraintChecker().maxBolusAllowed.value() + + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) {} @@ -42,13 +52,15 @@ class TreatmentDialog : DialogFragmentWithDate() { } private fun validateInputs() { + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() if (SafeParse.stringToInt(overview_treatment_carbs.text) > maxCarbs) { overview_treatment_carbs.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) } if (SafeParse.stringToDouble(overview_treatment_insulin.text) > maxInsulin) { overview_treatment_insulin.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.bolusconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.bolusconstraintapplied)) } } @@ -67,6 +79,8 @@ class TreatmentDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() + val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return overview_treatment_carbs.setParams(savedInstanceState?.getDouble("overview_treatment_carbs") ?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher) @@ -81,24 +95,24 @@ class TreatmentDialog : DialogFragmentWithDate() { val carbs = SafeParse.stringToInt(overview_treatment_carbs.text) val recordOnlyChecked = overview_treatment_record_only.isChecked val actions: LinkedList = LinkedList() - val insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(insulin)).value() - val carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value() + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (insulinAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "") + actions.add(resourceHelper.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "") if (recordOnlyChecked) - actions.add("" + MainApp.gs(R.string.bolusrecordedonly) + "") + actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") if (abs(insulinAfterConstraints - insulin) > pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) - actions.add(MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), insulin, insulinAfterConstraints)) + actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints)) } if (carbsAfterConstraints > 0) { - actions.add(MainApp.gs(R.string.carbs) + ": " + "" + MainApp.gs(R.string.format_carbs, carbsAfterConstraints) + "") + actions.add(resourceHelper.gs(R.string.carbs) + ": " + "" + resourceHelper.gs(R.string.format_carbs, carbsAfterConstraints) + "") if (carbsAfterConstraints != carbs) - actions.add("" + MainApp.gs(R.string.carbsconstraintapplied) + "") + actions.add("" + resourceHelper.gs(R.string.carbsconstraintapplied) + "") } if (insulinAfterConstraints > 0 || carbsAfterConstraints > 0) { activity?.let { activity -> - OKDialog.showConfirmation(activity, MainApp.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.overview_treatment_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { val detailedBolusInfo = DetailedBolusInfo() if (insulinAfterConstraints == 0.0) detailedBolusInfo.eventType = CareportalEvent.CARBCORRECTION if (carbsAfterConstraints == 0) detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS @@ -110,12 +124,12 @@ class TreatmentDialog : DialogFragmentWithDate() { ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() { override fun run() { if (!result.success) { - val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java) + val i = Intent(mainApp, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.boluserror) i.putExtra("status", result.comment) - i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)) + i.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - MainApp.instance().startActivity(i) + mainApp.startActivity(i) } } }) @@ -125,7 +139,7 @@ class TreatmentDialog : DialogFragmentWithDate() { } } else activity?.let { activity -> - OKDialog.show(activity, MainApp.gs(R.string.overview_treatment_label), MainApp.gs(R.string.no_action_selected)) + OKDialog.show(activity, resourceHelper.gs(R.string.overview_treatment_label), resourceHelper.gs(R.string.no_action_selected)) } return true } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index d48c28337b..a0fbd28f36 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -12,7 +12,7 @@ import android.widget.AdapterView import android.widget.AdapterView.OnItemSelectedListener import android.widget.ArrayAdapter import android.widget.CompoundButton -import androidx.fragment.app.DialogFragment +import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -22,22 +22,41 @@ import info.nightscout.androidaps.db.DatabaseHelper import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.dialog_wizard.* import org.slf4j.LoggerFactory import java.text.DecimalFormat import java.util.* +import javax.inject.Inject import kotlin.math.abs -class WizardDialog : DialogFragment() { +class WizardDialog : DaggerDialogFragment() { private val log = LoggerFactory.getLogger(WizardDialog::class.java) + @Inject + lateinit var constraintChecker: ConstraintChecker + + @Inject + lateinit var mainApp: MainApp + + @Inject + lateinit var resourceHelper: ResourceHelper + + @Inject + lateinit var profileFunction: ProfileFunction + + @Inject + lateinit var sp: SP + private var wizard: BolusWizard? = null //one shot guards @@ -79,11 +98,11 @@ class WizardDialog : DialogFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { loadCheckedStates() processCobCheckBox() - treatments_wizard_sbcheckbox.visibility = SP.getBoolean(R.string.key_usesuperbolus, false).toVisibility() - treatments_wizard_notes_layout.visibility = SP.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility() + treatments_wizard_sbcheckbox.visibility = sp.getBoolean(R.string.key_usesuperbolus, false).toVisibility() + treatments_wizard_notes_layout.visibility = sp.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility() - val maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value() - val maxCorrection = MainApp.getConstraintChecker().maxBolusAllowed.value() + val maxCarbs = constraintChecker.getMaxCarbsAllowed().value() + val maxCorrection = constraintChecker.getMaxBolusAllowed().value() treatments_wizard_bg_input.setParams(savedInstanceState?.getDouble("treatments_wizard_bg_input") ?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher) @@ -97,7 +116,7 @@ class WizardDialog : DialogFragment() { ?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher) initDialog() - treatments_wizard_percent_used.text = MainApp.gs(R.string.format_percent, SP.getInt(R.string.key_boluswizard_percentage, 100)) + treatments_wizard_percent_used.text = resourceHelper.gs(R.string.format_percent, sp.getInt(R.string.key_boluswizard_percentage, 100)) // ok button ok.setOnClickListener { if (okClicked) { @@ -122,13 +141,13 @@ class WizardDialog : DialogFragment() { treatments_wizard_bgtrendcheckbox.setOnCheckedChangeListener(::onCheckedChanged) treatments_wizard_sbcheckbox.setOnCheckedChangeListener(::onCheckedChanged) - val showCalc = SP.getBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), false) + val showCalc = sp.getBoolean(resourceHelper.gs(R.string.key_wizard_calculation_visible), false) treatments_wizard_delimiter.visibility = showCalc.toVisibility() treatments_wizard_resulttable.visibility = showCalc.toVisibility() treatments_wizard_calculationcheckbox.isChecked = showCalc treatments_wizard_calculationcheckbox.setOnCheckedChangeListener { _, isChecked -> run { - SP.putBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), isChecked) + sp.putBoolean(resourceHelper.gs(R.string.key_wizard_calculation_visible), isChecked) treatments_wizard_delimiter.visibility = isChecked.toVisibility() treatments_wizard_resulttable.visibility = isChecked.toVisibility() } @@ -136,7 +155,7 @@ class WizardDialog : DialogFragment() { // profile spinner treatments_wizard_profile.onItemSelectedListener = object : OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.noprofileselected)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofileselected)) ok.visibility = View.GONE } @@ -184,34 +203,34 @@ class WizardDialog : DialogFragment() { } private fun saveCheckedStates() { - SP.putBoolean(MainApp.gs(R.string.key_wizard_include_cob), treatments_wizard_cobcheckbox.isChecked) - SP.putBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), treatments_wizard_bgtrendcheckbox.isChecked) + sp.putBoolean(resourceHelper.gs(R.string.key_wizard_include_cob), treatments_wizard_cobcheckbox.isChecked) + sp.putBoolean(resourceHelper.gs(R.string.key_wizard_include_trend_bg), treatments_wizard_bgtrendcheckbox.isChecked) } private fun loadCheckedStates() { - treatments_wizard_bgtrendcheckbox.isChecked = SP.getBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), false) - treatments_wizard_cobcheckbox.isChecked = SP.getBoolean(MainApp.gs(R.string.key_wizard_include_cob), false) + treatments_wizard_bgtrendcheckbox.isChecked = sp.getBoolean(resourceHelper.gs(R.string.key_wizard_include_trend_bg), false) + treatments_wizard_cobcheckbox.isChecked = sp.getBoolean(resourceHelper.gs(R.string.key_wizard_include_cob), false) } private fun initDialog() { - val profile = ProfileFunctions.getInstance().getProfile() - val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile + val profile = profileFunction.getProfile() + val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface.profile if (profile == null || profileStore == null) { - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.noprofile)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofile)) dismiss() return } val profileList: ArrayList profileList = profileStore.getProfileList() - profileList.add(0, MainApp.gs(R.string.active)) + profileList.add(0, resourceHelper.gs(R.string.active)) context?.let { context -> val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) treatments_wizard_profile.adapter = adapter } ?: return - val units = ProfileFunctions.getSystemUnits() + val units = profileFunction.getUnits() treatments_wizard_bgunits.text = units if (units == Constants.MGDL) treatments_wizard_bg_input.setStep(1.0) @@ -239,18 +258,18 @@ class WizardDialog : DialogFragment() { calculateInsulin() - treatments_wizard_percent_used.visibility = (SP.getInt(R.string.key_boluswizard_percentage, 100) != 100).toVisibility() + treatments_wizard_percent_used.visibility = (sp.getInt(R.string.key_boluswizard_percentage, 100) != 100).toVisibility() } private fun calculateInsulin() { - val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile + val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface.profile if (treatments_wizard_profile.selectedItem == null || profileStore == null) return // not initialized yet var profileName = treatments_wizard_profile.selectedItem.toString() val specificProfile: Profile? - if (profileName == MainApp.gs(R.string.active)) { - specificProfile = ProfileFunctions.getInstance().getProfile() - profileName = ProfileFunctions.getInstance().getProfileName() ?: return + if (profileName == resourceHelper.gs(R.string.active)) { + specificProfile = profileFunction.getProfile() + profileName = profileFunction.getProfileName() ?: return } else specificProfile = profileStore.getSpecificProfile(profileName) @@ -260,10 +279,10 @@ class WizardDialog : DialogFragment() { var bg = SafeParse.stringToDouble(treatments_wizard_bg_input.text) val carbs = SafeParse.stringToInt(treatments_wizard_carbs_input.text) val correction = SafeParse.stringToDouble(treatments_wizard_correction_input.text) - val carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value() + val carbsAfterConstraint = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() if (abs(carbs - carbsAfterConstraint) > 0.01) { treatments_wizard_carbs_input.value = 0.0 - ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied)) + ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.carbsconstraintapplied)) return } @@ -280,7 +299,7 @@ class WizardDialog : DialogFragment() { val carbTime = SafeParse.stringToInt(treatments_wizard_carb_time_input.text) wizard = BolusWizard(specificProfile, profileName, tempTarget, carbsAfterConstraint, cob, bg, correction, - SP.getInt(R.string.key_boluswizard_percentage, 100).toDouble(), + sp.getInt(R.string.key_boluswizard_percentage, 100).toDouble(), treatments_wizard_bgcheckbox.isChecked, treatments_wizard_cobcheckbox.isChecked, treatments_wizard_bolusiobcheckbox.isChecked, @@ -291,10 +310,10 @@ class WizardDialog : DialogFragment() { treatment_wizard_notes.text.toString(), carbTime) wizard?.let { wizard -> - treatments_wizard_bg.text = String.format(MainApp.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(bg, ProfileFunctions.getSystemUnits())).valueToUnitsToString(ProfileFunctions.getSystemUnits()), wizard.sens) + treatments_wizard_bg.text = String.format(resourceHelper.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(bg, profileFunction.getUnits())).valueToUnitsToString(profileFunction.getUnits()), wizard.sens) treatments_wizard_bginsulin.text = StringUtils.formatInsulin(wizard.insulinFromBG) - treatments_wizard_carbs.text = String.format(MainApp.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) + treatments_wizard_carbs.text = String.format(resourceHelper.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic) treatments_wizard_carbsinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCarbs) treatments_wizard_bolusiobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromBolusIOB) @@ -303,14 +322,14 @@ class WizardDialog : DialogFragment() { treatments_wizard_correctioninsulin.text = StringUtils.formatInsulin(wizard.insulinFromCorrection) // Superbolus - treatments_wizard_sb.text = if (treatments_wizard_sbcheckbox.isChecked) MainApp.gs(R.string.twohours) else "" + treatments_wizard_sb.text = if (treatments_wizard_sbcheckbox.isChecked) resourceHelper.gs(R.string.twohours) else "" treatments_wizard_sbinsulin.text = StringUtils.formatInsulin(wizard.insulinFromSuperBolus) // Trend if (treatments_wizard_bgtrendcheckbox.isChecked && wizard.glucoseStatus != null) { treatments_wizard_bgtrend.text = ((if (wizard.trend > 0) "+" else "") - + Profile.toUnitsString(wizard.trend * 3, wizard.trend * 3 / Constants.MMOLL_TO_MGDL, ProfileFunctions.getSystemUnits()) - + " " + ProfileFunctions.getSystemUnits()) + + Profile.toUnitsString(wizard.trend * 3, wizard.trend * 3 / Constants.MMOLL_TO_MGDL, profileFunction.getUnits()) + + " " + profileFunction.getUnits()) } else { treatments_wizard_bgtrend.text = "" } @@ -318,7 +337,7 @@ class WizardDialog : DialogFragment() { // COB if (treatments_wizard_cobcheckbox.isChecked) { - treatments_wizard_cob.text = String.format(MainApp.gs(R.string.format_cob_ic), cob, wizard.ic) + treatments_wizard_cob.text = String.format(resourceHelper.gs(R.string.format_cob_ic), cob, wizard.ic) treatments_wizard_cobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCOB) } else { treatments_wizard_cob.text = "" @@ -326,12 +345,12 @@ class WizardDialog : DialogFragment() { } if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) { - val insulinText = if (wizard.calculatedTotalInsulin > 0.0) MainApp.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" - val carbsText = if (carbsAfterConstraint > 0.0) MainApp.gs(R.string.format_carbs, carbsAfterConstraint) else "" - treatments_wizard_total.text = MainApp.gs(R.string.result_insulin_carbs, insulinText, carbsText) + val insulinText = if (wizard.calculatedTotalInsulin > 0.0) resourceHelper.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else "" + val carbsText = if (carbsAfterConstraint > 0.0) resourceHelper.gs(R.string.format_carbs, carbsAfterConstraint) else "" + treatments_wizard_total.text = resourceHelper.gs(R.string.result_insulin_carbs, insulinText, carbsText) ok.visibility = View.VISIBLE } else { - treatments_wizard_total.text = MainApp.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt()) + treatments_wizard_total.text = resourceHelper.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt()) ok.visibility = View.INVISIBLE } } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore new file mode 100644 index 0000000000..93af086b7a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore @@ -0,0 +1,62 @@ +package info.nightscout.androidaps.interfaces + +import info.nightscout.androidaps.data.Profile + +interface ConstraintsInterface { + + fun isLoopInvocationAllowed(value: Constraint): Constraint { + return value + } + + fun isClosedLoopAllowed(value: Constraint): Constraint { + return value + } + + fun isAutosensModeEnabled(value: Constraint): Constraint { + return value + } + + fun isAMAModeEnabled(value: Constraint): Constraint { + return value + } + + fun isSMBModeEnabled(value: Constraint): Constraint { + return value + } + + fun isUAMEnabled(value: Constraint): Constraint { + return value + } + + fun isAdvancedFilteringEnabled(value: Constraint): Constraint { + return value + } + + fun isSuperBolusEnabled(value: Constraint): Constraint { + return value + } + + fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { + return absoluteRate + } + + fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { + return percentRate + } + + fun applyBolusConstraints(insulin: Constraint): Constraint { + return insulin + } + + fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { + return insulin + } + + fun applyCarbsConstraints(carbs: Constraint): Constraint { + return carbs + } + + fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { + return maxIob + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java index 7e568af2d9..9f2142771a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java @@ -23,6 +23,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -287,7 +288,7 @@ public class APSResult { } public boolean isChangeRequested() { - Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); + Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); // closed loop mode: handle change at driver level if (closedLoopEnabled.value()) { if (L.isEnabled(L.APS)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 7492dc64dd..e85bccbc2e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -19,6 +19,8 @@ import org.slf4j.LoggerFactory; import java.util.Date; +import javax.inject.Inject; + import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -48,6 +50,7 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.activities.ErrorHelperActivity; @@ -271,7 +274,7 @@ public class LoopPlugin extends PluginBase { try { if (L.isEnabled(L.APS)) log.debug("invoke from " + initiator); - Constraint loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed(); + Constraint loopEnabled = ConstraintChecker.getInstance().isLoopInvocationAllowed(); if (!loopEnabled.value()) { String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); @@ -319,13 +322,13 @@ public class LoopPlugin extends PluginBase { // check rate for constrais final APSResult resultAfterConstraints = result.clone(); resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate); - resultAfterConstraints.rate = MainApp.getConstraintChecker().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); + resultAfterConstraints.rate = ConstraintChecker.getInstance().applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); resultAfterConstraints.percentConstraint = new Constraint<>(resultAfterConstraints.percent); - resultAfterConstraints.percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value(); + resultAfterConstraints.percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(resultAfterConstraints.percentConstraint, profile).value(); resultAfterConstraints.smbConstraint = new Constraint<>(resultAfterConstraints.smb); - resultAfterConstraints.smb = MainApp.getConstraintChecker().applyBolusConstraints(resultAfterConstraints.smbConstraint).value(); + resultAfterConstraints.smb = ConstraintChecker.getInstance().applyBolusConstraints(resultAfterConstraints.smbConstraint).value(); // safety check for multiple SMBs long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); @@ -359,7 +362,7 @@ public class LoopPlugin extends PluginBase { return; } - Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); + Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); if (closedLoopEnabled.value()) { if (resultAfterConstraints.isChangeRequested() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java index 9ea2d39567..a0cf096055 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java @@ -21,19 +21,19 @@ import java.nio.charset.StandardCharsets; import javax.annotation.Nullable; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; @@ -255,7 +255,7 @@ public class DetermineBasalAdapterAMAJS { mMealData.put("boluses", mealData.boluses); mMealData.put("mealCOB", mealData.mealCOB); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { mAutosensData = new JSONObject(); mAutosensData.put("ratio", autosensDataRatio); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index 49881c5158..b4385e3599 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -4,6 +4,7 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -128,7 +129,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { return; } - double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value(); + double maxBasal = ConstraintChecker.getInstance().getMaxBasalAllowed(profile).value(); double minBg = profile.getTargetLowMgdl(); double maxBg = profile.getTargetHighMgdl(); double targetBg = profile.getTargetMgdl(); @@ -147,7 +148,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { if (L.isEnabled(L.APS)) Profiler.log(log, "getMealData()", startPart); - double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + double maxIob = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); minBg = HardLimits.verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); maxBg = HardLimits.verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); @@ -175,7 +176,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { return; startPart = System.currentTimeMillis(); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin"); if (autosensData == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata))); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java index 0380156c74..ec80acfc8f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -127,7 +128,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { return; } - double maxBasal = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value(); + double maxBasal = ConstraintChecker.getInstance().getMaxBasalAllowed(profile).value(); double minBg = profile.getTargetLowMgdl(); double maxBg = profile.getTargetHighMgdl(); @@ -146,7 +147,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); - double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + double maxIob = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); if (L.isEnabled(L.APS)) Profiler.log(log, "MA data gathering", start); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index 76571176d3..7429bebeec 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -23,16 +23,17 @@ import javax.annotation.Nullable; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; @@ -315,7 +316,7 @@ public class DetermineBasalAdapterSMBJS { mMealData.put("lastCarbTime", mealData.lastCarbTime); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { mAutosensData = new JSONObject(); mAutosensData.put("ratio", autosensDataRatio); } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index 426c04090b..7ee3866a9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; +import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,6 +25,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdat import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; @@ -134,7 +136,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr Constraint inputConstraints = new Constraint<>(0d); // fake. only for collecting all results - Constraint maxBasalConstraint = MainApp.getConstraintChecker().getMaxBasalAllowed(profile); + Constraint maxBasalConstraint = ConstraintChecker.getInstance().getMaxBasalAllowed(profile); inputConstraints.copyReasons(maxBasalConstraint); double maxBasal = maxBasalConstraint.value(); double minBg = profile.getTargetLowMgdl(); @@ -151,7 +153,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr if (L.isEnabled(L.APS)) Profiler.log(log, "getMealData()", startPart); - Constraint maxIOBAllowedConstraint = MainApp.getConstraintChecker().getMaxIOBAllowed(); + Constraint maxIOBAllowedConstraint = ConstraintChecker.getInstance().getMaxIOBAllowed(); inputConstraints.copyReasons(maxIOBAllowedConstraint); double maxIob = maxIOBAllowedConstraint.value(); @@ -181,7 +183,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr return; startPart = System.currentTimeMillis(); - if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) { + if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) { AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin"); if (autosensData == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata))); @@ -199,15 +201,15 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr startPart = System.currentTimeMillis(); Constraint smbAllowed = new Constraint<>(!tempBasalFallback); - MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed); + ConstraintChecker.getInstance().isSMBModeEnabled(smbAllowed); inputConstraints.copyReasons(smbAllowed); Constraint advancedFiltering = new Constraint<>(!tempBasalFallback); - MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); + ConstraintChecker.getInstance().isAdvancedFilteringEnabled(advancedFiltering); inputConstraints.copyReasons(advancedFiltering); Constraint uam = new Constraint<>(true); - MainApp.getConstraintChecker().isUAMEnabled(uam); + ConstraintChecker.getInstance().isUAMEnabled(uam); inputConstraints.copyReasons(uam); if (L.isEnabled(L.APS)) @@ -285,6 +287,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr return newvalue; } + @NotNull + @Override public Constraint isSuperBolusEnabled(Constraint value) { value.set(false); return value; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index 02508769dd..04fad732b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -367,7 +367,7 @@ public class ConfigBuilderPlugin extends PluginBase { */ private T determineActivePlugin(Class pluginInterface, PluginType pluginType) { ArrayList pluginsInCategory; - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(pluginInterface); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(pluginInterface); return this.determineActivePlugin(pluginsInCategory, pluginType); } @@ -443,23 +443,23 @@ public class ConfigBuilderPlugin extends PluginBase { break; // Single selection allowed case INSULIN: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(InsulinInterface.class); break; case SENSITIVITY: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(SensitivityInterface.class); break; case APS: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(APSInterface.class); break; case PROFILE: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(ProfileInterface.class); break; case BGSOURCE: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(BgSourceInterface.class); break; case TREATMENT: case PUMP: - pluginsInCategory = MainApp.getSpecificPluginsListByInterface(PumpInterface.class); + pluginsInCategory = MainApp.instance().getSpecificPluginsListByInterface(PumpInterface.class); break; } if (pluginsInCategory != null) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt new file mode 100644 index 0000000000..a3a1e6e2ef --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt @@ -0,0 +1,205 @@ +package info.nightscout.androidaps.plugins.configBuilder + +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.interfaces.Constraint +import info.nightscout.androidaps.interfaces.ConstraintsInterface +import info.nightscout.androidaps.interfaces.PluginType +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : ConstraintsInterface { + + init { + instance = this + } + + companion object { + @JvmStatic + lateinit var instance: ConstraintChecker + } + + fun isLoopInvocationAllowed(): Constraint = + isLoopInvocationAllowed(Constraint(true)) + + fun isClosedLoopAllowed(): Constraint = + isClosedLoopAllowed(Constraint(true)) + + fun isAutosensModeEnabled(): Constraint = + isAutosensModeEnabled(Constraint(true)) + + fun isAMAModeEnabled(): Constraint = + isAMAModeEnabled(Constraint(true)) + + fun isSMBModeEnabled(): Constraint = + isSMBModeEnabled(Constraint(true)) + + fun isUAMEnabled(): Constraint = + isUAMEnabled(Constraint(true)) + + fun isAdvancedFilteringEnabled(): Constraint = + isAdvancedFilteringEnabled(Constraint(true)) + + fun isSuperBolusEnabled(): Constraint = + isSuperBolusEnabled(Constraint(true)) + + fun getMaxBasalAllowed(profile: Profile): Constraint = + applyBasalConstraints(Constraint(Constants.REALLYHIGHBASALRATE), profile) + + fun getMaxBasalPercentAllowed(profile: Profile): Constraint = + applyBasalPercentConstraints(Constraint(Constants.REALLYHIGHPERCENTBASALRATE), profile) + + fun getMaxBolusAllowed(): Constraint = + applyBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS)) + + fun getMaxExtendedBolusAllowed(): Constraint = + applyExtendedBolusConstraints(Constraint(Constants.REALLYHIGHBOLUS)) + + fun getMaxCarbsAllowed(): Constraint = + applyCarbsConstraints(Constraint(Constants.REALLYHIGHCARBS)) + + fun getMaxIOBAllowed(): Constraint = + applyMaxIOBConstraints(Constraint(Constants.REALLYHIGHIOB)) + + override fun isLoopInvocationAllowed(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isLoopInvocationAllowed(value) + } + return value + } + + override fun isClosedLoopAllowed(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isClosedLoopAllowed(value) + } + return value + } + + override fun isAutosensModeEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isAutosensModeEnabled(value) + } + return value + } + + override fun isAMAModeEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.isAMAModeEnabled(value) + } + return value + } + + override fun isSMBModeEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isSMBModeEnabled(value) + } + return value + } + + override fun isUAMEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isUAMEnabled(value) + } + return value + } + + override fun isAdvancedFilteringEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isAdvancedFilteringEnabled(value) + } + return value + } + + override fun isSuperBolusEnabled(value: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.isSuperBolusEnabled(value) + } + return value + } + + override fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constraint = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constraint.applyBasalConstraints(absoluteRate, profile) + } + return absoluteRate + } + + override fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyBasalPercentConstraints(percentRate, profile) + } + return percentRate + } + + override fun applyBolusConstraints(insulin: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyBolusConstraints(insulin) + } + return insulin + } + + override fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyExtendedBolusConstraints(insulin) + } + return insulin + } + + override fun applyCarbsConstraints(carbs: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyCarbsConstraints(carbs) + } + return carbs + } + + override fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { + val constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface::class.java) + for (p in constraintsPlugins) { + val constrain = p as ConstraintsInterface + if (!p.isEnabled(PluginType.CONSTRAINTS)) continue + constrain.applyMaxIOBConstraints(maxIob) + } + return maxIob + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java index 1b224bd40c..d0c8452d4e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective6.java @@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives; import java.util.List; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.utils.T; public class Objective6 extends Objective { @@ -18,7 +18,7 @@ public class Objective6 extends Objective { tasks.add(new Task(R.string.maxiobset) { @Override public boolean isCompleted() { - double maxIOB = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); + double maxIOB = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); return maxIOB > 0; } }); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index 4d66f36194..9e31635f92 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.constraints.safety; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.Constraint; @@ -18,6 +17,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; @@ -90,8 +90,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { boolean enabled = SP.getBoolean(R.string.key_use_smb, false); if (!enabled) value.set(false, MainApp.gs(R.string.smbdisabledinpreferences), this); - ConstraintChecker constraintChecker = MainApp.getConstraintChecker(); - Constraint closedLoop = constraintChecker.isClosedLoopAllowed(); + Constraint closedLoop = ConstraintChecker.getInstance().isClosedLoopAllowed(); if (!closedLoop.value()) value.set(false, MainApp.gs(R.string.smbnotallowedinopenloopmode), this); return value; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java index c4f70f40bf..1236600c10 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java @@ -46,6 +46,7 @@ import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -272,11 +273,11 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie } }); - Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value(); + Integer maxCarbs = ConstraintChecker.getInstance().getMaxCarbsAllowed().value(); editCarbs = view.findViewById(R.id.careportal_newnstreatment_carbsinput); editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - Double maxInsulin = MainApp.getConstraintChecker().getMaxBolusAllowed().value(); + Double maxInsulin = ConstraintChecker.getInstance().getMaxBolusAllowed().value(); editInsulin = view.findViewById(R.id.careportal_newnstreatment_insulininput); editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false, view.findViewById(R.id.ok)); @@ -305,7 +306,7 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie Integer maxPercent = 200; if (profile != null) - maxPercent = MainApp.getConstraintChecker().getMaxBasalPercentAllowed(profile).value(); + maxPercent = ConstraintChecker.getInstance().getMaxBasalPercentAllowed(profile).value(); editPercent = view.findViewById(R.id.careportal_newnstreatment_percentinput); editPercent.setParams(0d, -100d, (double) maxPercent, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok), percentTextWatcher); @@ -329,7 +330,7 @@ public class NewNSTreatmentDialog extends AppCompatDialogFragment implements Vie Double maxAbsolute = HardLimits.maxBasal(); if (profile != null) - maxAbsolute = MainApp.getConstraintChecker().getMaxBasalAllowed(profile).value(); + maxAbsolute = ConstraintChecker.getInstance().getMaxBasalAllowed(profile).value(); editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput); editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, view.findViewById(R.id.ok), absoluteTextWatcher); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 21a3e1b271..b4c3825452 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -25,7 +25,6 @@ import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; -import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.PopupMenu; import androidx.core.content.res.ResourcesCompat; import androidx.fragment.app.Fragment; @@ -90,6 +89,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -930,7 +930,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, final BolusWizard wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true); if (wizard.getCalculatedTotalInsulin() > 0d && quickWizardEntry.carbs() > 0d) { - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value(); if (Math.abs(wizard.getInsulinAfterConstraints() - wizard.getCalculatedTotalInsulin()) >= pump.getPumpDescription().pumpType.determineCorrectBolusStepSize(wizard.getInsulinAfterConstraints()) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) { OKDialog.show(getContext(), MainApp.gs(R.string.treatmentdeliveryerror), MainApp.gs(R.string.constraints_violation) + "\n" + MainApp.gs(R.string.changeyourinput)); @@ -1059,7 +1059,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } - Constraint closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed(); + Constraint closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed(); // open loop mode final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 158864bb74..b2b6515b7d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -10,7 +10,6 @@ import android.telephony.SmsMessage import android.text.TextUtils import com.andreabaccega.widget.ValidatingEditTextPreference import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile @@ -28,6 +27,7 @@ import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBus.send import info.nightscout.androidaps.plugins.bus.RxBus.toObservable import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart @@ -52,7 +52,8 @@ import javax.inject.Singleton @Singleton class SmsCommunicatorPlugin @Inject constructor( val configBuilderPlugin: ConfigBuilderPlugin, - val resourceHelper: ResourceHelper + val resourceHelper: ResourceHelper, + val constraintChecker: ConstraintChecker ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(SmsCommunicatorFragment::class.java.name) @@ -506,7 +507,7 @@ class SmsCommunicatorPlugin @Inject constructor( else if (tempBasalPct == 0 && splitted[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { - tempBasalPct = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() + tempBasalPct = constraintChecker.applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value() val passCode = generatePasscode() val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode) receivedSms.processed = true @@ -538,7 +539,7 @@ class SmsCommunicatorPlugin @Inject constructor( else if (tempBasal == 0.0 && splitted[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { - tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(tempBasal), profile).value() + tempBasal = constraintChecker.applyBasalConstraints(Constraint(tempBasal), profile).value() val passCode = generatePasscode() val reply = String.format(resourceHelper.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode) receivedSms.processed = true @@ -591,7 +592,7 @@ class SmsCommunicatorPlugin @Inject constructor( } else { var extended = SafeParse.stringToDouble(splitted[1]) val duration = SafeParse.stringToInt(splitted[2]) - extended = MainApp.getConstraintChecker().applyExtendedBolusConstraints(Constraint(extended)).value() + extended = constraintChecker.applyExtendedBolusConstraints(Constraint(extended)).value() if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { val passCode = generatePasscode() @@ -621,7 +622,7 @@ class SmsCommunicatorPlugin @Inject constructor( private fun processBOLUS(splitted: Array, receivedSms: Sms) { var bolus = SafeParse.stringToDouble(splitted[1]) val isMeal = splitted.size > 2 && splitted[2].equals("MEAL", ignoreCase = true) - bolus = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(bolus)).value() + bolus = constraintChecker.applyBolusConstraints(Constraint(bolus)).value() if (splitted.size == 3 && !isMeal) { sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) } else if (bolus > 0.0) { @@ -701,7 +702,7 @@ class SmsCommunicatorPlugin @Inject constructor( } time = midnight + T.secs(seconds.toLong()).msecs() } - grams = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(grams)).value() + grams = constraintChecker.applyCarbsConstraints(Constraint(grams)).value() if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat)) else { val passCode = generatePasscode() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java index d25d42bbe2..a137def1d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java @@ -35,6 +35,7 @@ import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; @@ -95,7 +96,7 @@ public class ActionStringHandler { } else { return; } - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); rMessage += MainApp.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U"; if (insulinAfterConstraints - amount != 0) rMessage += "\n" + MainApp.gs(R.string.constraintapllied); @@ -106,7 +107,7 @@ public class ActionStringHandler { ////////////////////////////////////////////// PRIME/FILL double amount = SafeParse.stringToDouble(act[1]); - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); rMessage += MainApp.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U"; if (insulinAfterConstraints - amount != 0) rMessage += "\n" + MainApp.gs(R.string.constraintapllied); @@ -117,8 +118,8 @@ public class ActionStringHandler { ////////////////////////////////////////////// BOLUS double insulin = SafeParse.stringToDouble(act[1]); int carbs = SafeParse.stringToInt(act[2]); - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value(); - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbs)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(insulin)).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(carbs)).value(); rMessage += MainApp.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n"; rMessage += MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g"; @@ -180,7 +181,7 @@ public class ActionStringHandler { } else if ("wizard2".equals(act[0])) { ////////////////////////////////////////////// WIZARD Integer carbsBeforeConstraints = SafeParse.stringToInt(act[1]); - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbsBeforeConstraints)).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(carbsBeforeConstraints)).value(); if (carbsAfterConstraints - carbsBeforeConstraints != 0) { sendError("Carb constraint violation!"); @@ -324,7 +325,7 @@ public class ActionStringHandler { int starttime = SafeParse.stringToInt(act[2]); int duration = SafeParse.stringToInt(act[3]); long starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000; - Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(carbs)).value(); + Integer carbsAfterConstraints = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>(carbs)).value(); rMessage += MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g"; rMessage += "\n" + MainApp.gs(R.string.time) + ": " + DateUtil.timeString(starttimestamp); rMessage += "\n" + MainApp.gs(R.string.duration) + ": " + duration + "h"; @@ -491,7 +492,7 @@ public class ActionStringHandler { // decide if enabled/disabled closed/open; what Plugin as APS? final LoopPlugin loopPlugin = LoopPlugin.getPlugin(); if (loopPlugin.isEnabled(loopPlugin.getType())) { - if (MainApp.getConstraintChecker().isClosedLoopAllowed().value()) { + if (ConstraintChecker.getInstance().isClosedLoopAllowed().value()) { ret += "CLOSED LOOP\n"; } else { ret += "OPEN LOOP\n"; @@ -591,7 +592,7 @@ public class ActionStringHandler { if ("fill".equals(act[0])) { Double amount = SafeParse.stringToDouble(act[1]); - Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + Double insulinAfterConstraints = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); if (amount - insulinAfterConstraints != 0) { ToastUtils.showToastInUiThread(MainApp.instance(), "aborting: previously applied constraint changed"); sendError("aborting: previously applied constraint changed"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index 57dadbdc55..cd25f80ba2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -28,6 +28,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.ManufacturerType; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; @@ -178,7 +179,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -227,7 +228,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); - insulin = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index e9293b39a6..0d0205b734 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService; @@ -139,7 +140,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { Treatment t = new Treatment(); t.isSMB = detailedBolusInfo.isSMB; @@ -183,7 +184,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -280,7 +281,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { Integer durationInHalfHours = Math.max(durationInMinutes / 30, 1); // We keep current basal running so need to sub current basal Double extendedRateToSet = absoluteRate - getBaseBasalRate(); - extendedRateToSet = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); + extendedRateToSet = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); // needs to be rounded to 0.1 extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java index 4b7cd2ff41..f3cd33478d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class MsgBolusStart extends MessageBase { private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -20,7 +20,7 @@ public class MsgBolusStart extends MessageBase { this(); // HARDCODED LIMIT - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); AddParamInt((int) (amount * 100)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java index 0c174807b3..de73ff0491 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class MsgBolusStartWithSpeed extends MessageBase { private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -20,7 +20,7 @@ public class MsgBolusStartWithSpeed extends MessageBase { this(); // HARDCODED LIMIT - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); AddParamInt((int) (amount * 100)); AddParamByte((byte) speed); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java index dad437ac72..f6b3d85aa5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetExtendedBolusStart.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class MsgSetExtendedBolusStart extends MessageBase { private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -22,13 +22,8 @@ public class MsgSetExtendedBolusStart extends MessageBase { // HARDCODED LIMITS if (halfhours < 1) halfhours = 1; if (halfhours > 16) halfhours = 16; - Constraint constrainedAmount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)); - if (constrainedAmount != null) { - AddParamInt((int) (constrainedAmount.value() * 100)); - } else { - log.error("constrainedAmount of insulin is null!!"); - AddParamInt(0); - } + Constraint constrainedAmount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)); + AddParamInt((int) (constrainedAmount.value() * 100)); AddParamByte(halfhours); if (L.isEnabled(L.PUMPCOMM)) log.debug("Set extended bolus start: " + (((int) (amount * 100)) / 100d) + "U halfhours: " + (int) halfhours); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java index 2645e25ade..ba39c52d9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; @@ -142,7 +143,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { Treatment t = new Treatment(); t.isSMB = detailedBolusInfo.isSMB; @@ -186,7 +187,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -283,7 +284,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { Integer durationInHalfHours = Math.max(durationInMinutes / 30, 1); // We keep current basal running so need to sub current basal Double extendedRateToSet = absoluteRate - getBaseBasalRate(); - extendedRateToSet = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); + extendedRateToSet = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(extendedRateToSet), profile).value(); // needs to be rounded to 0.1 extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 8c8780d021..5dcbfb9057 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -7,7 +7,6 @@ import android.content.ServiceConnection; import android.os.IBinder; import android.preference.Preference; -import androidx.annotation.Nullable; import androidx.fragment.app.FragmentActivity; import org.jetbrains.annotations.NotNull; @@ -23,7 +22,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; @@ -39,6 +37,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.ManufacturerType; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; @@ -370,7 +369,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); int speed = 12; @@ -462,7 +461,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -539,7 +538,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; @@ -616,7 +615,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { DanaRPump pump = DanaRPump.getInstance(); - insulin = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + insulin = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // needs to be rounded int durationInHalfHours = Math.max(durationInMinutes / 30, 1); insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java index 7ff91fa9ef..f2a2f1e783 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java @@ -5,9 +5,9 @@ import com.cozmo.danar.util.BleCommandUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); @@ -28,7 +28,7 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { this(); // HARDCODED LIMIT - if there is one that could be created - amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value(); + amount = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(amount)).value(); this.amount = amount; this.speed = speed; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index 3437d37656..e6fac58b9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -16,6 +16,7 @@ import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; @@ -128,7 +129,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { // Pump interface @Override public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { // v2 stores end time for bolus, we need to adjust time // default delivery speed is 12 sec/U @@ -204,7 +205,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { PumpEnactResult result = new PumpEnactResult(); - absoluteRate = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + absoluteRate = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; final boolean doLowTemp = absoluteRate < getBaseBasalRate(); @@ -279,7 +280,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { DanaRPump pump = DanaRPump.getInstance(); PumpEnactResult result = new PumpEnactResult(); - percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + percent = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); if (percent < 0) { result.isTempCancel = false; result.enacted = false; diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index 05efc63aa3..489163eb5a 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -13,20 +13,23 @@ import org.slf4j.LoggerFactory; import java.util.LinkedList; +import javax.inject.Inject; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.BolusProgressHelperActivity; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.events.EventBolusRequested; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -236,8 +239,8 @@ public class CommandQueue { } // apply constraints - detailedBolusInfo.insulin = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); - detailedBolusInfo.carbs = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>((int) detailedBolusInfo.carbs)).value(); + detailedBolusInfo.insulin = ConstraintChecker.getInstance().applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); + detailedBolusInfo.carbs = ConstraintChecker.getInstance().applyCarbsConstraints(new Constraint<>((int) detailedBolusInfo.carbs)).value(); // add new command to queue if (detailedBolusInfo.isSMB) { @@ -293,7 +296,7 @@ public class CommandQueue { // remove all unfinished removeAll(Command.CommandType.TEMPBASAL); - Double rateAfterConstraints = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); + Double rateAfterConstraints = ConstraintChecker.getInstance().applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); // add new command to queue add(new CommandTempBasalAbsolute(rateAfterConstraints, durationInMinutes, enforceNew, profile, callback)); @@ -314,7 +317,7 @@ public class CommandQueue { // remove all unfinished removeAll(Command.CommandType.TEMPBASAL); - Integer percentAfterConstraints = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); + Integer percentAfterConstraints = ConstraintChecker.getInstance().applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); // add new command to queue add(new CommandTempBasalPercent(percentAfterConstraints, durationInMinutes, enforceNew, profile, callback)); @@ -332,7 +335,7 @@ public class CommandQueue { return false; } - Double rateAfterConstraints = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); + Double rateAfterConstraints = ConstraintChecker.getInstance().applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); // remove all unfinished removeAll(Command.CommandType.EXTENDEDBOLUS); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt index df1a0586de..dc5c6b3fc8 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt @@ -19,6 +19,7 @@ import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin @@ -186,7 +187,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile, ?: 0.1 calculatedTotalInsulin = Round.roundTo(calculatedTotalInsulin, bolusStep) - insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() + insulinAfterConstraints = ConstraintChecker.instance.applyBolusConstraints(Constraint(calculatedTotalInsulin)).value() log.debug(this.toString()) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java index 355623f38d..560c44c84e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java @@ -14,6 +14,7 @@ import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin; /** @@ -113,7 +114,7 @@ public class FabricPrivacy { public static void setUserStats() { if (!fabricEnabled()) return; - String closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed().value() ? "CLOSED_LOOP_ENABLED" : "CLOSED_LOOP_DISABLED"; + String closedLoopEnabled = ConstraintChecker.getInstance().isClosedLoopAllowed().value() ? "CLOSED_LOOP_ENABLED" : "CLOSED_LOOP_DISABLED"; // Size is limited to 36 chars String remote = BuildConfig.REMOTE.toLowerCase() .replace("https://", "") diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java index b48942fbc4..2fe8c77c9f 100644 --- a/app/src/test/java/info/AAPSMocker.java +++ b/app/src/test/java/info/AAPSMocker.java @@ -1,7 +1,6 @@ package info; import android.content.Context; -import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; @@ -15,7 +14,7 @@ import java.util.Locale; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; @@ -25,9 +24,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.treatments.TreatmentService; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.CommandQueue; diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java index f3577e35c8..a5112579ff 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java @@ -16,7 +16,7 @@ import java.util.ArrayList; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; @@ -63,7 +63,7 @@ public class ConstraintsCheckerTest { comboPlugin.setPluginEnabled(PluginType.PUMP, true); comboPlugin.setValidBasalRateProfileSelectedOnPump(false); - Constraint c = constraintChecker.isLoopInvokationAllowed(); + Constraint c = constraintChecker.isLoopInvocationAllowed(); Assert.assertEquals(true, c.getReasonList().size() == 2); // Combo & Objectives Assert.assertEquals(true, c.getMostLimitedReasonList().size() == 2); // Combo & Objectives Assert.assertEquals(Boolean.FALSE, c.value()); @@ -129,7 +129,7 @@ public class ConstraintsCheckerTest { public void isSMBModeEnabledTest() throws Exception { objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getSMB_OBJECTIVE()).setStartedOn(0); when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(false); - when(MainApp.getConstraintChecker().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); Constraint c = constraintChecker.isSMBModeEnabled(); Assert.assertEquals(true, c.getReasonList().size() == 2); // Safety & Objectives diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java index 1db142af2c..70cbbf5bac 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java @@ -12,7 +12,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java index 1dabf0ff30..959e1620cd 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java @@ -69,7 +69,7 @@ public class SafetyPluginTest { @Test public void notEnabledSMBInPreferencesDisablesSMB() { when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(false); - when(MainApp.getConstraintChecker().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(true)); Constraint c = new Constraint<>(true); c = safetyPlugin.isSMBModeEnabled(c); @@ -80,7 +80,7 @@ public class SafetyPluginTest { @Test public void openLoopPreventsSMB() { when(SP.getBoolean(R.string.key_use_smb, false)).thenReturn(true); - when(MainApp.getConstraintChecker().isClosedLoopAllowed()).thenReturn(new Constraint<>(false)); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(new Constraint<>(false)); Constraint c = new Constraint<>(true); c = safetyPlugin.isSMBModeEnabled(c); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java index a00c029ce9..641f11bed3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java @@ -29,6 +29,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; @@ -552,7 +553,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBasalPercentConstraints(any(), any())).thenReturn(new Constraint<>(20)); + when(ConstraintChecker.getInstance().applyBasalPercentConstraints(any(), any())).thenReturn(new Constraint<>(20)); //BASAL 20% 20 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -579,7 +580,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BASAL 1 0", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBasalConstraints(any(), any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyBasalConstraints(any(), any())).thenReturn(new Constraint<>(1d)); //BASAL 1 20 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -632,7 +633,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("EXTENDED a%", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); //EXTENDED 1 0 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -673,7 +674,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BOLUS", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); when(DateUtil.now()).thenReturn(1000L); //BOLUS 1 @@ -683,7 +684,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(0d)); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(0d)); when(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L); @@ -701,9 +702,9 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("BOLUS a", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d)); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d)); //BOLUS 1 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -807,7 +808,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("CARBS", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(new Constraint<>(0)); + when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(new Constraint<>(0)); //CARBS 0 smsCommunicatorPlugin.setMessages(new ArrayList<>()); @@ -816,7 +817,7 @@ public class SmsCommunicatorPluginTest { Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.getMessages().get(0).getText()); Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText()); - when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(new Constraint<>(1)); + when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(new Constraint<>(1)); //CARBS 1 smsCommunicatorPlugin.setMessages(new ArrayList<>()); diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java index baaccd95b3..57be6e1f24 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java @@ -17,7 +17,7 @@ import java.util.Date; import info.AAPSMocker; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.Constraint; @@ -123,14 +123,14 @@ public class CommandQueueTest extends CommandQueue { when(MainApp.getConstraintChecker()).thenReturn(constraintChecker); when(MainApp.isEngineeringModeOrRelease()).thenReturn(true); Constraint bolusConstraint = new Constraint<>(0d); - when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(bolusConstraint); - when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(bolusConstraint); + when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(bolusConstraint); + when(ConstraintChecker.getInstance().applyExtendedBolusConstraints(any())).thenReturn(bolusConstraint); Constraint carbsConstraint = new Constraint<>(0); - when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(carbsConstraint); + when(ConstraintChecker.getInstance().applyCarbsConstraints(any())).thenReturn(carbsConstraint); Constraint rateConstraint = new Constraint<>(0d); - when(MainApp.getConstraintChecker().applyBasalConstraints(any(), any())).thenReturn(rateConstraint); + when(ConstraintChecker.getInstance().applyBasalConstraints(any(), any())).thenReturn(rateConstraint); Constraint percentageConstraint = new Constraint<>(0); - when(MainApp.getConstraintChecker().applyBasalPercentConstraints(any(), any())).thenReturn(percentageConstraint); + when(ConstraintChecker.getInstance().applyBasalPercentConstraints(any(), any())).thenReturn(percentageConstraint); PowerMockito.mockStatic(ToastUtils.class); Context context = mock(Context.class); diff --git a/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java b/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java index 43bdbc48b7..4788b39a27 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java +++ b/app/src/test/java/info/nightscout/androidaps/utils/BolusWizardTest.java @@ -10,7 +10,7 @@ import org.powermock.modules.junit4.PowerMockRunner; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.data.ConstraintChecker; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; From f24949ba024f2ed9ff488509fc072b935bc14a21 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Fri, 27 Dec 2019 21:06:56 +0100 Subject: [PATCH 038/316] deprecate warning and todo for workaround fields --- .../androidaps/plugins/configBuilder/ConstraintChecker.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt index a3a1e6e2ef..68dcb9d5a8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConstraintChecker.kt @@ -18,7 +18,8 @@ class ConstraintChecker @Inject constructor(private val mainApp: MainApp) : Cons companion object { @JvmStatic - lateinit var instance: ConstraintChecker + @Deprecated("Get via Dagger. Will be removed once fully transitioned to Dagger") + lateinit var instance: ConstraintChecker //TODO: remove as soon as Dagger is fully set up } fun isLoopInvocationAllowed(): Constraint = From 4b8696123545debd1c83b1ddfc4b635e1c1671e0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 21:38:59 +0100 Subject: [PATCH 039/316] Use DaggerIntentService --- .../nightscout/androidaps/services/DataService.java | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) 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 07193d14f7..147ef1fa43 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -13,6 +13,7 @@ import org.slf4j.LoggerFactory; import javax.inject.Inject; +import dagger.android.DaggerIntentService; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; @@ -42,7 +43,7 @@ import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.SP; -public class DataService extends IntentService { +public class DataService extends DaggerIntentService { private Logger log = LoggerFactory.getLogger(L.DATASERVICE); public DataService() { @@ -52,13 +53,6 @@ public class DataService extends IntentService { @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; - @Override - public void onCreate() { - super.onCreate(); - ((MainApp) getApplication()).androidInjector().inject(this); - - } - @Override protected void onHandleIntent(final Intent intent) { if (L.isEnabled(L.DATASERVICE)) { From 8b88e2d270b1e5065ec0c44a79d7ab219f11b4f7 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 21:39:34 +0100 Subject: [PATCH 040/316] make tests compile --- app/src/test/java/info/AAPSMocker.java | 7 ++++--- .../androidaps/interfaces/ConstraintsCheckerTest.java | 2 +- .../androidaps/plugins/aps/loop/APSResultTest.java | 8 ++++---- .../plugins/constraints/safety/SafetyPluginTest.java | 1 + .../smsCommunicator/SmsCommunicatorPluginTest.java | 6 ++++-- .../nightscout/androidaps/queue/CommandQueueTest.java | 3 ++- 6 files changed, 16 insertions(+), 11 deletions(-) diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java index 2fe8c77c9f..0a11093683 100644 --- a/app/src/test/java/info/AAPSMocker.java +++ b/app/src/test/java/info/AAPSMocker.java @@ -14,13 +14,13 @@ import java.util.Locale; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; @@ -34,7 +34,6 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -184,8 +183,10 @@ public class AAPSMocker { } public static ConstraintChecker mockConstraintsChecker() { + PowerMockito.mockStatic(ConstraintChecker.class); constraintChecker = mock(ConstraintChecker.class); - when(MainApp.getConstraintChecker()).thenReturn(constraintChecker); + when(ConstraintChecker.getInstance()) + .thenReturn(constraintChecker); return constraintChecker; } diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java index a5112579ff..818c1e2863 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java @@ -287,7 +287,7 @@ public class ConstraintsCheckerTest { //SafetyPlugin when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump); - constraintChecker = new ConstraintChecker(); + constraintChecker = ConstraintChecker.getInstance(); safetyPlugin = SafetyPlugin.getPlugin(); objectivesPlugin = ObjectivesPlugin.INSTANCE; diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java index 70cbbf5bac..6c30ca910a 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java @@ -30,7 +30,7 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, ConfigBuilderPlugin.class, SP.class, Context.class, ProfileFunctions.class, TreatmentsPlugin.class, L.class}) +@PrepareForTest({MainApp.class, ConfigBuilderPlugin.class, SP.class, Context.class, ProfileFunctions.class, TreatmentsPlugin.class, L.class, ConstraintChecker.class}) public class APSResultTest { VirtualPumpPlugin virtualPumpPlugin; TreatmentsPlugin treatmentsPlugin; @@ -183,13 +183,13 @@ public class APSResultTest { AAPSMocker.mockTreatmentService(); AAPSMocker.mockL(); treatmentsPlugin = AAPSMocker.mockTreatmentPlugin(); - ConstraintChecker constraintChecker = AAPSMocker.mockConstraintsChecker(); + AAPSMocker.mockConstraintsChecker(); + when(ConstraintChecker.getInstance().isClosedLoopAllowed()).thenReturn(closedLoopEnabled); + virtualPumpPlugin = VirtualPumpPlugin.getPlugin(); when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(virtualPumpPlugin); - when(constraintChecker.isClosedLoopAllowed()).thenReturn(closedLoopEnabled); - Mockito.when(SP.getDouble(anyInt(), anyDouble())).thenReturn(30d); } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java index 959e1620cd..f2e5067126 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java @@ -18,6 +18,7 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.source.SourceGlimpPlugin; import info.nightscout.androidaps.utils.SP; diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java index 641f11bed3..a243464cb1 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java @@ -43,6 +43,7 @@ import info.nightscout.androidaps.queue.CommandQueue; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.XdripCalibrations; +import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -889,7 +890,7 @@ public class SmsCommunicatorPluginTest { AAPSMocker.mockConfigBuilder(); AAPSMocker.mockCommandQueue(); AAPSMocker.mockNSUpload(); - AAPSMocker.mockConstraintsChecker(); + ConstraintChecker constraintChecker = AAPSMocker.mockConstraintsChecker(); BgReading reading = new BgReading(); reading.value = 100; @@ -907,7 +908,8 @@ public class SmsCommunicatorPluginTest { when(SP.getString(R.string.key_smscommunicator_allowednumbers, "")).thenReturn("1234;5678"); Lazy insulinOrefRapidActingPlugin = InsulinOrefRapidActingPlugin::new; ConfigBuilderPlugin configBuilderPlugin = new ConfigBuilderPlugin(insulinOrefRapidActingPlugin); - smsCommunicatorPlugin = new SmsCommunicatorPlugin(configBuilderPlugin); + ResourceHelperImplementation resourceHelperImplementation = mock(ResourceHelperImplementation.class); + smsCommunicatorPlugin = new SmsCommunicatorPlugin(configBuilderPlugin, resourceHelperImplementation, constraintChecker); smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true); mockStatic(LoopPlugin.class); diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java index 57be6e1f24..775e7ca051 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java @@ -113,6 +113,7 @@ public class CommandQueueTest extends CommandQueue { } private void prepareMock(Double insulin, Integer carbs) throws Exception { + PowerMockito.mockStatic(ConstraintChecker.class); ConstraintChecker constraintChecker = mock(ConstraintChecker.class); AAPSMocker.mockMainApp(); @@ -120,7 +121,7 @@ public class CommandQueueTest extends CommandQueue { PumpInterface pump = VirtualPumpPlugin.getPlugin(); when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump); - when(MainApp.getConstraintChecker()).thenReturn(constraintChecker); + when(ConstraintChecker.getInstance()).thenReturn(constraintChecker); when(MainApp.isEngineeringModeOrRelease()).thenReturn(true); Constraint bolusConstraint = new Constraint<>(0d); when(ConstraintChecker.getInstance().applyBolusConstraints(any())).thenReturn(bolusConstraint); From 5335b075b9d8d960f12e139ae0e76e34bf4191b0 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 21:43:51 +0100 Subject: [PATCH 041/316] DataService inject SP --- .../info/nightscout/androidaps/services/DataService.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 147ef1fa43..f24129f036 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -40,7 +40,7 @@ import info.nightscout.androidaps.plugins.source.SourceTomatoPlugin; import info.nightscout.androidaps.plugins.source.SourceXdripPlugin; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.utils.JsonHelper; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; public class DataService extends DaggerIntentService { @@ -53,6 +53,9 @@ public class DataService extends DaggerIntentService { @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; + @Inject + SP sp; + @Override protected void onHandleIntent(final Intent intent) { if (L.isEnabled(L.DATASERVICE)) { @@ -60,7 +63,7 @@ public class DataService extends DaggerIntentService { log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras())); } - boolean acceptNSData = !SP.getBoolean(R.string.key_ns_upload_only, false); + boolean acceptNSData = !sp.getBoolean(R.string.key_ns_upload_only, false); Bundle bundles = intent.getExtras(); final String action = intent.getAction(); @@ -244,7 +247,7 @@ public class DataService extends DaggerIntentService { String enteredBy = JsonHelper.safeGetString(json, "enteredBy", ""); String notes = JsonHelper.safeGetString(json, "notes", ""); if (date > now - 15 * 60 * 1000L && !notes.isEmpty() - && !enteredBy.equals(SP.getString("careportal_enteredby", "AndroidAPS"))) { + && !enteredBy.equals(sp.getString("careportal_enteredby", "AndroidAPS"))) { Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60); RxBus.INSTANCE.send(new EventNewNotification(announcement)); } From fca775a4e7968245bae96056bd743db8558bc68e Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Fri, 27 Dec 2019 22:44:12 +0100 Subject: [PATCH 042/316] L -> kt --- .../info/nightscout/androidaps/logging/L.java | 133 ------------------ .../info/nightscout/androidaps/logging/L.kt | 121 ++++++++++++++++ .../activities/LogSettingActivity.kt | 2 +- 3 files changed, 122 insertions(+), 134 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/logging/L.java create mode 100644 app/src/main/java/info/nightscout/androidaps/logging/L.kt diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.java b/app/src/main/java/info/nightscout/androidaps/logging/L.java deleted file mode 100644 index 25b6750844..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/logging/L.java +++ /dev/null @@ -1,133 +0,0 @@ -package info.nightscout.androidaps.logging; - -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.utils.SP; - -public class L { - - public static class LogElement { - public String name; - boolean defaultValue; - public boolean enabled; - boolean requiresRestart = false; - - LogElement(String name, boolean defaultValue) { - this.name = name; - this.defaultValue = defaultValue; - enabled = SP.getBoolean(getSPName(), defaultValue); - } - - LogElement(String name, boolean defaultValue, boolean requiresRestart) { - this.name = name; - this.defaultValue = defaultValue; - this.requiresRestart = requiresRestart; - enabled = SP.getBoolean(getSPName(), defaultValue); - } - - LogElement(boolean defaultValue) { - this.name = "NONEXISTING"; - this.defaultValue = defaultValue; - enabled = defaultValue; - } - - private String getSPName() { - return "log_" + name; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - SP.putBoolean(getSPName(), enabled); - } - - void resetToDefault() { - setEnabled(defaultValue); - } - } - - private static List logElements; - - static { - initialize(); - } - - private static LogElement findByName(String name) { - for (LogElement element : logElements) { - if (element.name.equals(name)) - return element; - } - return new LogElement(false); - } - - public static boolean isEnabled(String name) { - return findByName(name).enabled; - } - - public static List getLogElements() { - return logElements; - } - - public static void resetToDefaults() { - for (LogElement element : logElements) { - element.resetToDefault(); - } - } - - - public static final String CORE = "CORE"; - public static final String AUTOSENS = "AUTOSENS"; - public static final String AUTOMATION = "AUTOMATION"; - public static final String EVENTS = "EVENTS"; - public static final String GLUCOSE = "GLUCOSE"; - public static final String BGSOURCE = "BGSOURCE"; - public static final String OVERVIEW = "OVERVIEW"; - public static final String NOTIFICATION = "NOTIFICATION"; - public static final String DATASERVICE = "DATASERVICE"; - public static final String DATABASE = "DATABASE"; - public static final String DATAFOOD = "DATAFOOD"; - public static final String DATATREATMENTS = "DATATREATMENTS"; - public static final String NSCLIENT = "NSCLIENT"; - public static final String TIDEPOOL = "TIDEPOOL"; - public static final String CONSTRAINTS = "CONSTRAINTS"; - public static final String PUMP = "PUMP"; - public static final String PUMPQUEUE = "PUMPQUEUE"; - public static final String PUMPCOMM = "PUMPCOMM"; - public static final String PUMPBTCOMM = "PUMPBTCOMM"; - public static final String APS = "APS"; - public static final String PROFILE = "PROFILE"; - public static final String CONFIGBUILDER = "CONFIGBUILDER"; - public static final String UI = "UI"; - public static final String LOCATION = "LOCATION"; - public static final String SMS = "SMS"; - - private static void initialize() { - logElements = new ArrayList<>(); - logElements.add(new LogElement(APS, true)); - logElements.add(new LogElement(AUTOMATION, true)); - logElements.add(new LogElement(AUTOSENS, false)); - logElements.add(new LogElement(BGSOURCE, true)); - logElements.add(new LogElement(GLUCOSE, false)); - logElements.add(new LogElement(CONFIGBUILDER, false)); - logElements.add(new LogElement(CONSTRAINTS, true)); - logElements.add(new LogElement(CORE, true)); - logElements.add(new LogElement(DATABASE, true)); - logElements.add(new LogElement(DATAFOOD, false)); - logElements.add(new LogElement(DATASERVICE, true)); - logElements.add(new LogElement(DATATREATMENTS, true)); - logElements.add(new LogElement(EVENTS, false, true)); - logElements.add(new LogElement(LOCATION, true)); - logElements.add(new LogElement(NOTIFICATION, true)); - logElements.add(new LogElement(NSCLIENT, true)); - logElements.add(new LogElement(TIDEPOOL, true)); - logElements.add(new LogElement(OVERVIEW, true)); - logElements.add(new LogElement(PROFILE, true)); - logElements.add(new LogElement(PUMP, true)); - logElements.add(new LogElement(PUMPBTCOMM, false)); - logElements.add(new LogElement(PUMPCOMM, true)); - logElements.add(new LogElement(PUMPQUEUE, true)); - logElements.add(new LogElement(SMS, true)); - logElements.add(new LogElement(UI, true)); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.kt b/app/src/main/java/info/nightscout/androidaps/logging/L.kt new file mode 100644 index 0000000000..3e3dfae6e9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/logging/L.kt @@ -0,0 +1,121 @@ +package info.nightscout.androidaps.logging + +import info.nightscout.androidaps.utils.SP +import java.util.* + +object L { + private var logElements: MutableList = ArrayList() + + const val CORE = "CORE" + const val AUTOSENS = "AUTOSENS" + const val AUTOMATION = "AUTOMATION" + const val EVENTS = "EVENTS" + const val GLUCOSE = "GLUCOSE" + const val BGSOURCE = "BGSOURCE" + const val OVERVIEW = "OVERVIEW" + const val NOTIFICATION = "NOTIFICATION" + const val DATASERVICE = "DATASERVICE" + const val DATABASE = "DATABASE" + const val DATAFOOD = "DATAFOOD" + const val DATATREATMENTS = "DATATREATMENTS" + const val NSCLIENT = "NSCLIENT" + const val TIDEPOOL = "TIDEPOOL" + const val CONSTRAINTS = "CONSTRAINTS" + const val PUMP = "PUMP" + const val PUMPQUEUE = "PUMPQUEUE" + const val PUMPCOMM = "PUMPCOMM" + const val PUMPBTCOMM = "PUMPBTCOMM" + const val APS = "APS" + const val PROFILE = "PROFILE" + const val CONFIGBUILDER = "CONFIGBUILDER" + const val UI = "UI" + const val LOCATION = "LOCATION" + const val SMS = "SMS" + + init { + logElements.add(LogElement(APS, defaultValue = true)) + logElements.add(LogElement(AUTOMATION, defaultValue = true)) + logElements.add(LogElement(AUTOSENS, defaultValue = false)) + logElements.add(LogElement(BGSOURCE, defaultValue = true)) + logElements.add(LogElement(GLUCOSE, defaultValue = false)) + logElements.add(LogElement(CONFIGBUILDER, defaultValue = false)) + logElements.add(LogElement(CONSTRAINTS, defaultValue = true)) + logElements.add(LogElement(CORE, defaultValue = true)) + logElements.add(LogElement(DATABASE, defaultValue = true)) + logElements.add(LogElement(DATAFOOD, false)) + logElements.add(LogElement(DATASERVICE, true)) + logElements.add(LogElement(DATATREATMENTS, true)) + logElements.add(LogElement(EVENTS, false, requiresRestart = true)) + logElements.add(LogElement(LOCATION, true)) + logElements.add(LogElement(NOTIFICATION, true)) + logElements.add(LogElement(NSCLIENT, true)) + logElements.add(LogElement(TIDEPOOL, true)) + logElements.add(LogElement(OVERVIEW, true)) + logElements.add(LogElement(PROFILE, true)) + logElements.add(LogElement(PUMP, true)) + logElements.add(LogElement(PUMPBTCOMM, false)) + logElements.add(LogElement(PUMPCOMM, true)) + logElements.add(LogElement(PUMPQUEUE, true)) + logElements.add(LogElement(SMS, true)) + logElements.add(LogElement(UI, true)) + } + + private fun findByName(name: String): LogElement { + for (element in logElements) { + if (element.name == name) return element + } + return LogElement(false) + } + + @JvmStatic + fun isEnabled(name: String): Boolean { + return findByName(name).enabled + } + + fun getLogElements(): List { + return logElements + } + + fun resetToDefaults() { + for (element in logElements) { + element.resetToDefault() + } + } + + class LogElement { + var name: String + var defaultValue: Boolean + var enabled: Boolean + private var requiresRestart = false + + internal constructor(name: String, defaultValue: Boolean) { + this.name = name + this.defaultValue = defaultValue + enabled = SP.getBoolean(getSPName(), defaultValue) + } + + internal constructor(name: String, defaultValue: Boolean, requiresRestart: Boolean) { + this.name = name + this.defaultValue = defaultValue + this.requiresRestart = requiresRestart + enabled = SP.getBoolean(getSPName(), defaultValue) + } + + internal constructor(defaultValue: Boolean) { + name = "NONEXISTING" + this.defaultValue = defaultValue + enabled = defaultValue + } + + private fun getSPName(): String = "log_$name" + + fun enable(enabled: Boolean) { + this.enabled = enabled + SP.putBoolean(getSPName(), enabled) + } + + fun resetToDefault() { + enable(defaultValue) + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt index d9ed0c590c..4f72107f84 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt @@ -40,7 +40,7 @@ class LogSettingActivity : NoSplashAppCompatActivity() { (baseView.findViewById(R.id.logsettings_description) as TextView).text = element.name val enabled = baseView.findViewById(R.id.logsettings_visibility) enabled.isChecked = element.enabled - enabled.setOnClickListener { element.setEnabled(enabled.isChecked) } + enabled.setOnClickListener { element.enable(enabled.isChecked) } } } From 7805fbc5db10eba19060afd1537c5f186653cb12 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 28 Dec 2019 01:14:04 +0100 Subject: [PATCH 043/316] APSPlugins, SafetyPlugin -> dagger --- .../info/nightscout/androidaps/MainApp.java | 12 +++-- .../activities/MyPreferenceFragment.java | 20 ++++++-- .../dependencyInjection/AppComponent.kt | 3 ++ .../dependencyInjection/AppModule.kt | 4 ++ .../dependencyInjection/FragmentsModule.kt | 12 +++++ .../aps/openAPSAMA/OpenAPSAMAFragment.kt | 48 +++++++++-------- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 19 +++---- .../aps/openAPSMA/OpenAPSMAFragment.kt | 46 +++++++++-------- .../aps/openAPSMA/OpenAPSMAPlugin.java | 19 +++---- .../aps/openAPSSMB/OpenAPSSMBFragment.kt | 51 ++++++++++--------- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 22 +++++--- .../objectives/objectives/Objective5.java | 9 +++- .../constraints/safety/SafetyPlugin.java | 29 ++++++----- 13 files changed, 171 insertions(+), 123 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 5ff629fb9a..77ef53cc7c 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -126,7 +126,11 @@ public class MainApp extends DaggerApplication { @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; @Inject InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin; @Inject InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin; + @Inject SafetyPlugin safetyPlugin; @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; + @Inject OpenAPSMAPlugin openAPSMAPlugin; + @Inject OpenAPSAMAPlugin openAPSAMAPlugin; + @Inject OpenAPSSMBPlugin openAPSSMBPlugin; @Override public void onCreate() { @@ -201,13 +205,13 @@ public class MainApp extends DaggerApplication { pluginsList.add(VirtualPumpPlugin.getPlugin()); pluginsList.add(CareportalPlugin.getPlugin()); if (Config.APS) pluginsList.add(LoopPlugin.getPlugin()); - if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin()); - if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin()); - if (Config.APS) pluginsList.add(OpenAPSSMBPlugin.getPlugin()); + if (Config.APS) pluginsList.add(openAPSMAPlugin); + if (Config.APS) pluginsList.add(openAPSAMAPlugin); + if (Config.APS) pluginsList.add(openAPSSMBPlugin); pluginsList.add(NSProfilePlugin.getPlugin()); if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.INSTANCE); pluginsList.add(TreatmentsPlugin.getPlugin()); - if (!Config.NSCLIENT) pluginsList.add(SafetyPlugin.getPlugin()); + if (!Config.NSCLIENT) pluginsList.add(safetyPlugin); if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE); if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin()); if (Config.APS) pluginsList.add(SignatureVerifierPlugin.getPlugin()); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java index 67c309c82d..585d3aff33 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java @@ -50,9 +50,21 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro @Inject DispatchingAndroidInjector androidInjector; + @Inject + OpenAPSAMAPlugin openAPSAMAPlugin; + + @Inject + OpenAPSMAPlugin openAPSMAPlugin; + + @Inject + OpenAPSSMBPlugin openAPSSMBPlugin; + @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + @Inject + SafetyPlugin safetyPlugin; + @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; @@ -97,12 +109,12 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro addPreferencesFromResourceIfEnabled(SourceDexcomPlugin.INSTANCE, PluginType.BGSOURCE); addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginType.CONSTRAINTS); + addPreferencesFromResourceIfEnabled(safetyPlugin, PluginType.CONSTRAINTS); if (Config.APS) { addPreferencesFromResourceIfEnabled(LoopPlugin.getPlugin(), PluginType.LOOP); - addPreferencesFromResourceIfEnabled(OpenAPSMAPlugin.getPlugin(), PluginType.APS); - addPreferencesFromResourceIfEnabled(OpenAPSAMAPlugin.getPlugin(), PluginType.APS); - addPreferencesFromResourceIfEnabled(OpenAPSSMBPlugin.getPlugin(), PluginType.APS); + addPreferencesFromResourceIfEnabled(openAPSMAPlugin, PluginType.APS); + addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, PluginType.APS); + addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, PluginType.APS); } addPreferencesFromResourceIfEnabled(SensitivityAAPSPlugin.getPlugin(), PluginType.SENSITIVITY); diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index d7ed6d04a4..770495bb1c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,6 +5,7 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5 import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS import info.nightscout.androidaps.queue.commands.CommandSetProfile import info.nightscout.androidaps.services.DataService @@ -27,6 +28,8 @@ interface AppComponent : AndroidInjector { fun injectActionSendSMS(actionSendSMS: ActionSendSMS) + fun injectObjective5(objective5: Objective5) + @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 9d51eda0a5..2ab9d962df 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -10,6 +10,7 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation +import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5 import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS import info.nightscout.androidaps.queue.commands.CommandSetProfile import info.nightscout.androidaps.services.DataService @@ -58,6 +59,9 @@ class AppModule { @ContributesAndroidInjector fun bindActionSendSMS(): ActionSendSMS + @ContributesAndroidInjector + fun bindObjective5(): Objective5 + @Binds fun bindContext(mainApp: MainApp): Context } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index ea7ba7e9e2..b3bf7d47dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -4,6 +4,9 @@ import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.activities.MyPreferenceFragment import info.nightscout.androidaps.dialogs.* +import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAFragment +import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAFragment +import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment @Module @@ -12,6 +15,15 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment + @ContributesAndroidInjector + abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment + + @ContributesAndroidInjector + abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment + + @ContributesAndroidInjector + abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment + @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt index 94747a4597..1b05d58a29 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt @@ -5,7 +5,7 @@ import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import androidx.fragment.app.Fragment +import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L @@ -22,11 +22,15 @@ import kotlinx.android.synthetic.main.openapsama_fragment.* import org.json.JSONArray import org.json.JSONException import org.slf4j.LoggerFactory +import javax.inject.Inject -class OpenAPSAMAFragment : Fragment() { +class OpenAPSAMAFragment : DaggerFragment() { private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() + @Inject + lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.openapsama_fragment, container, false) @@ -36,7 +40,7 @@ class OpenAPSAMAFragment : Fragment() { super.onViewCreated(view, savedInstanceState) openapsma_run.setOnClickListener { - OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button", false) + openAPSAMAPlugin.invoke("OpenAPSAMA button", false) } } @@ -45,21 +49,21 @@ class OpenAPSAMAFragment : Fragment() { super.onResume() disposable += RxBus - .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - updateGUI() - }, { - FabricPrivacy.logException(it) - }) + .toObservable(EventOpenAPSUpdateGui::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + updateGUI() + }, { + FabricPrivacy.logException(it) + }) disposable += RxBus - .toObservable(EventOpenAPSUpdateResultGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - updateResultGUI(it.text) - }, { - FabricPrivacy.logException(it) - }) + .toObservable(EventOpenAPSUpdateResultGui::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + updateResultGUI(it.text) + }, { + FabricPrivacy.logException(it) + }) updateGUI() } @@ -73,11 +77,11 @@ class OpenAPSAMAFragment : Fragment() { @Synchronized private fun updateGUI() { if (openapsma_result == null) return - OpenAPSAMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult -> + openAPSAMAPlugin.lastAPSResult?.let { lastAPSResult -> openapsma_result.text = JSONFormatter.format(lastAPSResult.json) openapsma_request.text = lastAPSResult.toSpanned() } - OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS -> + openAPSAMAPlugin.lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS -> openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam) openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterAMAJS.currentTempParam) try { @@ -92,10 +96,10 @@ class OpenAPSAMAFragment : Fragment() { openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterAMAJS.mealDataParam) openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug } - if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != 0L) { - openapsma_lastrun.text = DateUtil.dateAndTimeFullString(OpenAPSAMAPlugin.getPlugin().lastAPSRun) + if (openAPSAMAPlugin.lastAPSRun != 0L) { + openapsma_lastrun.text = DateUtil.dateAndTimeFullString(openAPSAMAPlugin.lastAPSRun) } - OpenAPSAMAPlugin.getPlugin().lastAutosensResult?.let { + openAPSAMAPlugin.lastAutosensResult?.let { openapsma_autosensdata.text = JSONFormatter.format(it.json()) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index b4385e3599..5e626004de 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -4,6 +4,9 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -35,28 +38,18 @@ import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Round; -/** - * Created by mike on 05.08.2016. - */ +@Singleton public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { private static Logger log = LoggerFactory.getLogger(L.APS); - private static OpenAPSAMAPlugin openAPSAMAPlugin; - - public static OpenAPSAMAPlugin getPlugin() { - if (openAPSAMAPlugin == null) { - openAPSAMAPlugin = new OpenAPSAMAPlugin(); - } - return openAPSAMAPlugin; - } - // last values DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null; long lastAPSRun = 0; DetermineBasalResultAMA lastAPSResult = null; AutosensResult lastAutosensResult = null; - private OpenAPSAMAPlugin() { + @Inject + public OpenAPSAMAPlugin() { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSAMAFragment.class.getName()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt index 1b72f57365..e712378603 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt @@ -4,7 +4,7 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import androidx.fragment.app.Fragment +import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui @@ -18,11 +18,15 @@ import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.openapsama_fragment.* import org.slf4j.LoggerFactory +import javax.inject.Inject -class OpenAPSMAFragment : Fragment() { +class OpenAPSMAFragment : DaggerFragment() { private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() + @Inject + lateinit var openAPSMAPlugin: OpenAPSMAPlugin + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.openapsma_fragment, container, false) @@ -32,7 +36,7 @@ class OpenAPSMAFragment : Fragment() { super.onViewCreated(view, savedInstanceState) openapsma_run.setOnClickListener { - OpenAPSMAPlugin.getPlugin().invoke("OpenAPSMA button", false) + openAPSMAPlugin.invoke("OpenAPSMA button", false) } } @@ -42,21 +46,21 @@ class OpenAPSMAFragment : Fragment() { super.onResume() disposable += RxBus - .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - updateGUI() - }, { - FabricPrivacy.logException(it) - }) + .toObservable(EventOpenAPSUpdateGui::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + updateGUI() + }, { + FabricPrivacy.logException(it) + }) disposable += RxBus - .toObservable(EventOpenAPSUpdateResultGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - updateResultGUI(it.text) - }, { - FabricPrivacy.logException(it) - }) + .toObservable(EventOpenAPSUpdateResultGui::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + updateResultGUI(it.text) + }, { + FabricPrivacy.logException(it) + }) updateGUI() } @@ -69,19 +73,19 @@ class OpenAPSMAFragment : Fragment() { @Synchronized private fun updateGUI() { if (openapsma_result == null) return - OpenAPSMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult -> + openAPSMAPlugin.lastAPSResult?.let { lastAPSResult -> openapsma_result.text = JSONFormatter.format(lastAPSResult.json) openapsma_request.text = lastAPSResult.toSpanned() } - OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS?.let { determineBasalAdapterMAJS -> + openAPSMAPlugin.lastDetermineBasalAdapterMAJS?.let { determineBasalAdapterMAJS -> openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterMAJS.glucoseStatusParam) openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterMAJS.currentTempParam) openapsma_iobdata.text = JSONFormatter.format(determineBasalAdapterMAJS.iobDataParam) openapsma_profile.text = JSONFormatter.format(determineBasalAdapterMAJS.profileParam) openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterMAJS.mealDataParam) } - if (OpenAPSMAPlugin.getPlugin().lastAPSRun != 0L) { - openapsma_lastrun.text = DateUtil.dateAndTimeString(OpenAPSMAPlugin.getPlugin().lastAPSRun) + if (openAPSMAPlugin.lastAPSRun != 0L) { + openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSMAPlugin.lastAPSRun) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java index ec80acfc8f..1740dbf55c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java @@ -4,6 +4,9 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -35,27 +38,17 @@ import info.nightscout.androidaps.utils.Round; import static info.nightscout.androidaps.utils.HardLimits.checkOnlyHardLimits; import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits; -/** - * Created by mike on 05.08.2016. - */ +@Singleton public class OpenAPSMAPlugin extends PluginBase implements APSInterface { private static Logger log = LoggerFactory.getLogger(L.APS); - private static OpenAPSMAPlugin openAPSMAPlugin; - - public static OpenAPSMAPlugin getPlugin() { - if (openAPSMAPlugin == null) { - openAPSMAPlugin = new OpenAPSMAPlugin(); - } - return openAPSMAPlugin; - } - // last values DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null; long lastAPSRun = 0; DetermineBasalResultMA lastAPSResult = null; - private OpenAPSMAPlugin() { + @Inject + public OpenAPSMAPlugin() { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSMAFragment.class.getName()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt index 06ad0d01fd..1ec66a0edd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt @@ -6,7 +6,7 @@ import android.text.TextUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup -import androidx.fragment.app.Fragment +import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L @@ -23,11 +23,15 @@ import kotlinx.android.synthetic.main.openapsama_fragment.* import org.json.JSONArray import org.json.JSONException import org.slf4j.LoggerFactory +import javax.inject.Inject -class OpenAPSSMBFragment : Fragment() { +class OpenAPSSMBFragment : DaggerFragment() { private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() + @Inject + lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.openapsama_fragment, container, false) @@ -37,7 +41,7 @@ class OpenAPSSMBFragment : Fragment() { super.onViewCreated(view, savedInstanceState) openapsma_run.setOnClickListener { - OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button", false) + openAPSSMBPlugin.invoke("OpenAPSSMB button", false) } } @@ -45,21 +49,21 @@ class OpenAPSSMBFragment : Fragment() { override fun onResume() { super.onResume() disposable += RxBus - .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - updateGUI() - }, { - FabricPrivacy.logException(it) - }) + .toObservable(EventOpenAPSUpdateGui::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + updateGUI() + }, { + FabricPrivacy.logException(it) + }) disposable += RxBus - .toObservable(EventOpenAPSUpdateResultGui::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ - updateResultGUI(it.text) - }, { - FabricPrivacy.logException(it) - }) + .toObservable(EventOpenAPSUpdateResultGui::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + updateResultGUI(it.text) + }, { + FabricPrivacy.logException(it) + }) updateGUI() } @@ -73,12 +77,11 @@ class OpenAPSSMBFragment : Fragment() { @Synchronized fun updateGUI() { if (openapsma_result == null) return - val plugin = OpenAPSSMBPlugin.getPlugin() - plugin.lastAPSResult?.let { lastAPSResult -> + openAPSSMBPlugin.lastAPSResult?.let { lastAPSResult -> openapsma_result.text = JSONFormatter.format(lastAPSResult.json) openapsma_request.text = lastAPSResult.toSpanned() } - plugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS -> + openAPSSMBPlugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS -> openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterSMBJS.glucoseStatusParam) openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterSMBJS.currentTempParam) try { @@ -93,14 +96,14 @@ class OpenAPSSMBFragment : Fragment() { openapsma_profile.text = JSONFormatter.format(determineBasalAdapterSMBJS.profileParam) openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterSMBJS.mealDataParam) openapsma_scriptdebugdata.text = determineBasalAdapterSMBJS.scriptDebug - plugin.lastAPSResult?.inputConstraints?.let { + openAPSSMBPlugin.lastAPSResult?.inputConstraints?.let { openapsma_constraints.text = it.reasons } } - if (plugin.lastAPSRun != 0L) { - openapsma_lastrun.text = DateUtil.dateAndTimeFullString(plugin.lastAPSRun) + if (openAPSSMBPlugin.lastAPSRun != 0L) { + openapsma_lastrun.text = DateUtil.dateAndTimeFullString(openAPSSMBPlugin.lastAPSRun) } - plugin.lastAutosensResult?.let { + openAPSSMBPlugin.lastAutosensResult?.let { openapsma_autosensdata.text = JSONFormatter.format(it.json()) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index 7ee3866a9a..1565bf819e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -5,6 +5,9 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -40,18 +43,19 @@ import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.ToastUtils; -/** - * Created by mike on 05.08.2016. - */ +@Singleton public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { private static Logger log = LoggerFactory.getLogger(L.APS); private static OpenAPSSMBPlugin openAPSSMBPlugin; - public static OpenAPSSMBPlugin getPlugin() { - if (openAPSSMBPlugin == null) { - openAPSSMBPlugin = new OpenAPSSMBPlugin(); - } + /** + * @deprecated Use dagger to get an instance + */ + @Deprecated + static public OpenAPSSMBPlugin getPlugin() { + if (openAPSSMBPlugin == null) + throw new IllegalStateException("Accessing OpenAPSSMBPlugin before first instantiation"); return openAPSSMBPlugin; } @@ -61,7 +65,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr DetermineBasalResultSMB lastAPSResult = null; AutosensResult lastAutosensResult = null; - private OpenAPSSMBPlugin() { + @Inject + public OpenAPSSMBPlugin() { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSSMBFragment.class.getName()) @@ -70,6 +75,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr .preferencesId(R.xml.pref_openapssmb) .description(R.string.description_smb) ); + this.openAPSSMBPlugin = this; // TODO: only while transitioning to Dagger } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java index bd3e69c751..608942c442 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective5.java @@ -2,6 +2,9 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives; import java.util.List; +import javax.inject.Inject; + +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; @@ -9,8 +12,12 @@ import info.nightscout.androidaps.utils.T; public class Objective5 extends Objective { + @Inject + SafetyPlugin safetyPlugin; + public Objective5() { super("maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate); + MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger } @Override @@ -20,7 +27,7 @@ public class Objective5 extends Objective { @Override public boolean isCompleted() { Constraint closedLoopEnabled = new Constraint<>(true); - SafetyPlugin.getPlugin().isClosedLoopAllowed(closedLoopEnabled); + safetyPlugin.isClosedLoopAllowed(closedLoopEnabled); return closedLoopEnabled.value(); } }); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index 9e31635f92..17bdb0133d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -1,5 +1,8 @@ package info.nightscout.androidaps.plugins.constraints.safety; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -26,19 +29,19 @@ import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; -/** - * Created by mike on 05.08.2016. - */ +@Singleton public class SafetyPlugin extends PluginBase implements ConstraintsInterface { - static SafetyPlugin plugin = null; + @Inject + OpenAPSAMAPlugin openAPSAMAPlugin; - public static SafetyPlugin getPlugin() { - if (plugin == null) - plugin = new SafetyPlugin(); - return plugin; - } + @Inject + OpenAPSMAPlugin openAPSMAPlugin; + @Inject + OpenAPSSMBPlugin openAPSSMBPlugin; + + @Inject public SafetyPlugin() { super(new PluginDescription() .mainType(PluginType.CONSTRAINTS) @@ -236,17 +239,17 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @Override public Constraint applyMaxIOBConstraints(Constraint maxIob) { double maxIobPref; - if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) + if (openAPSSMBPlugin.isEnabled(PluginType.APS)) maxIobPref = SP.getDouble(R.string.key_openapssmb_max_iob, 3d); else maxIobPref = SP.getDouble(R.string.key_openapsma_max_iob, 1.5d); maxIob.setIfSmaller(maxIobPref, String.format(MainApp.gs(R.string.limitingiob), maxIobPref, MainApp.gs(R.string.maxvalueinpreferences)), this); - if (OpenAPSMAPlugin.getPlugin().isEnabled(PluginType.APS)) + if (openAPSMAPlugin.isEnabled(PluginType.APS)) maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(MainApp.gs(R.string.limitingiob), HardLimits.maxIobAMA(), MainApp.gs(R.string.hardlimit)), this); - if (OpenAPSAMAPlugin.getPlugin().isEnabled(PluginType.APS)) + if (openAPSAMAPlugin.isEnabled(PluginType.APS)) maxIob.setIfSmaller(HardLimits.maxIobAMA(), String.format(MainApp.gs(R.string.limitingiob), HardLimits.maxIobAMA(), MainApp.gs(R.string.hardlimit)), this); - if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) + if (openAPSSMBPlugin.isEnabled(PluginType.APS)) maxIob.setIfSmaller(HardLimits.maxIobSMB(), String.format(MainApp.gs(R.string.limitingiob), HardLimits.maxIobSMB(), MainApp.gs(R.string.hardlimit)), this); return maxIob; } From 9a729122814f8f8ca1c4c7668e111627dbe08652 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 28 Dec 2019 01:52:20 +0100 Subject: [PATCH 044/316] dagger logging start --- .../nightscout/androidaps/MainActivity.java | 12 +-- .../info/nightscout/androidaps/MainApp.java | 24 ++++-- .../dependencyInjection/AppModule.kt | 14 ++++ .../interfaces/ConstraintsInterface.kt.ignore | 62 --------------- .../androidaps/logging/AAPSLogger.kt | 13 +++ .../androidaps/logging/AAPSLoggerDebug.kt | 28 +++++++ .../logging/AAPSLoggerProduction.kt | 38 +++++++++ .../info/nightscout/androidaps/logging/L.kt | 28 +++++++ .../configBuilder/ConfigBuilderPlugin.java | 79 ++++++++----------- .../smsCommunicator/SmsCommunicatorPlugin.kt | 17 ++-- .../androidaps/services/DataService.java | 31 ++++---- 11 files changed, 202 insertions(+), 144 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore create mode 100644 app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index d6cf1bcd28..419004a64d 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -34,9 +34,6 @@ import com.google.android.material.tabs.TabLayout; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import javax.inject.Inject; import dagger.android.AndroidInjection; @@ -53,7 +50,8 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRebuildTabs; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt; @@ -71,7 +69,6 @@ import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; public class MainActivity extends NoSplashAppCompatActivity implements HasAndroidInjector { - private static Logger log = LoggerFactory.getLogger(L.CORE); @Inject DispatchingAndroidInjector androidInjector; @@ -85,6 +82,9 @@ public class MainActivity extends NoSplashAppCompatActivity implements HasAndroi @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; + @Inject + AAPSLogger aapsLogger; + @Override public void onCreate(Bundle savedInstanceState) { AndroidInjection.inject(this); @@ -327,7 +327,7 @@ public class MainActivity extends NoSplashAppCompatActivity implements HasAndroi ((TextView) alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); return true; case R.id.nav_exit: - log.debug("Exiting"); + aapsLogger.debug(LTag.CORE, "Exiting"); RxBus.INSTANCE.send(new EventAppExit()); finish(); System.runFinalization(); diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 5ff629fb9a..b39f7b1c5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -33,7 +33,9 @@ import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; @@ -121,12 +123,20 @@ public class MainApp extends DaggerApplication { public static boolean devBranch; public static boolean engineeringMode; - @Inject ConfigBuilderPlugin configBuilderPlugin; + @Inject + AAPSLogger aapsLogger; - @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; - @Inject InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin; - @Inject InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin; - @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; + @Inject + ConfigBuilderPlugin configBuilderPlugin; + + @Inject + InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; + @Inject + InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin; + @Inject + InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin; + @Inject + SmsCommunicatorPlugin smsCommunicatorPlugin; @Override public void onCreate() { @@ -433,8 +443,8 @@ public class MainApp extends DaggerApplication { @Override public void onTerminate() { - if (L.isEnabled(L.CORE)) - log.debug("onTerminate"); + + aapsLogger.debug(LTag.CORE, "onTerminate"); if (timeDateOrTZChangeReceiver != null) unregisterReceiver(timeDateOrTZChangeReceiver); diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 9d51eda0a5..faa789adbf 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -6,7 +6,11 @@ import dagger.Binds import dagger.Module import dagger.Provides import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.AAPSLoggerDebug +import info.nightscout.androidaps.logging.AAPSLoggerProduction import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation @@ -46,6 +50,16 @@ class AppModule { return ResourceHelperImplementation(mainApp) } + @Provides + @Singleton + fun provideAAPSLogger(): AAPSLogger { + return if (BuildConfig.DEBUG) { + AAPSLoggerDebug() + } else { + AAPSLoggerProduction() + } + } + @Module interface AppBindings { diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore deleted file mode 100644 index 93af086b7a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt.ignore +++ /dev/null @@ -1,62 +0,0 @@ -package info.nightscout.androidaps.interfaces - -import info.nightscout.androidaps.data.Profile - -interface ConstraintsInterface { - - fun isLoopInvocationAllowed(value: Constraint): Constraint { - return value - } - - fun isClosedLoopAllowed(value: Constraint): Constraint { - return value - } - - fun isAutosensModeEnabled(value: Constraint): Constraint { - return value - } - - fun isAMAModeEnabled(value: Constraint): Constraint { - return value - } - - fun isSMBModeEnabled(value: Constraint): Constraint { - return value - } - - fun isUAMEnabled(value: Constraint): Constraint { - return value - } - - fun isAdvancedFilteringEnabled(value: Constraint): Constraint { - return value - } - - fun isSuperBolusEnabled(value: Constraint): Constraint { - return value - } - - fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { - return absoluteRate - } - - fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { - return percentRate - } - - fun applyBolusConstraints(insulin: Constraint): Constraint { - return insulin - } - - fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { - return insulin - } - - fun applyCarbsConstraints(carbs: Constraint): Constraint { - return carbs - } - - fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { - return maxIob - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt new file mode 100644 index 0000000000..e3f74fdb10 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.logging + +/** + * Created by adrian on 2019-12-27. + */ + +interface AAPSLogger { + + fun debug(tag: LTag, message: String) + fun info(tag: LTag, message: String) + fun error(tag: LTag, message: String) + fun error(tag: LTag, message: String, throwable: Throwable) +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt new file mode 100644 index 0000000000..d512725176 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.logging + +import android.util.Log + +/** + * Created by adrian on 2019-12-27. + */ + +class AAPSLoggerDebug : AAPSLogger { + + override fun debug(tag: LTag, message: String) { + Log.d(tag.tag, message) + } + + override fun info(tag: LTag, message: String) { + Log.i(tag.tag, message) + } + + override fun error(tag: LTag, message: String) { + Log.e(tag.tag, message) + + } + + override fun error(tag: LTag, message: String, throwable: Throwable) { + Log.e(tag.tag, message, throwable) + + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt new file mode 100644 index 0000000000..414fad2859 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.logging + +import org.slf4j.LoggerFactory + +/** + * Created by adrian on 2019-12-27. + */ + +class AAPSLoggerProduction : AAPSLogger { + + override fun debug(tag: LTag, message: String) { + if (L.isEnabled(tag.tag)) { + LoggerFactory.getLogger(tag.tag).debug(message) + + } + } + + override fun info(tag: LTag, message: String) { + if (L.isEnabled(tag.tag)) { + LoggerFactory.getLogger(tag.tag).info(message) + + } + } + + override fun error(tag: LTag, message: String) { + if (L.isEnabled(tag.tag)) { + LoggerFactory.getLogger(tag.tag).error(message) + + } + } + + override fun error(tag: LTag, message: String, throwable: Throwable) { + if (L.isEnabled(tag.tag)) { + LoggerFactory.getLogger(tag.tag).error(message, throwable) + + } + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.kt b/app/src/main/java/info/nightscout/androidaps/logging/L.kt index 3e3dfae6e9..2ec1473c08 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/L.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/L.kt @@ -118,4 +118,32 @@ object L { enable(defaultValue) } } +} + +enum class LTag(val tag: String) { + CORE("CORE"), + AUTOSENS("AUTOSENS"), + AUTOMATION("AUTOMATION"), + EVENTS("EVENTS"), + GLUCOSE("GLUCOSE"), + BGSOURCE("BGSOURCE"), + OVERVIEW("OVERVIEW"), + NOTIFICATION("NOTIFICATION"), + DATASERVICE("DATASERVICE"), + DATABASE("DATABASE"), + DATAFOOD("DATAFOOD"), + DATATREATMENTS("DATATREATMENTS"), + NSCLIENT("NSCLIENT"), + TIDEPOOL("TIDEPOOL"), + CONSTRAINTS("CONSTRAINTS"), + PUMP("PUMP"), + PUMPQUEUE("PUMPQUEUE"), + PUMPCOMM("PUMPCOMM"), + PUMPBTCOMM("PUMPBTCOMM"), + APS("APS"), + PROFILE("PROFILE"), + CONFIGBUILDER("CONFIGBUILDER"), + UI("UI"), + LOCATION("LOCATION"), + SMS("SMS"), } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index 04fad732b4..076d29382b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.configBuilder; import androidx.annotation.Nullable; import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; @@ -24,7 +22,8 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin; @@ -39,9 +38,8 @@ import info.nightscout.androidaps.utils.SP; */ @Singleton public class ConfigBuilderPlugin extends PluginBase { - private Logger log = LoggerFactory.getLogger(L.CONFIGBUILDER); - private static ConfigBuilderPlugin configBuilderPlugin; + private final AAPSLogger aapsLogger; // TODO move to plugin base /** @@ -78,7 +76,10 @@ public class ConfigBuilderPlugin extends PluginBase { * Lazy dependencies in this constructor. * */ @Inject - public ConfigBuilderPlugin(Lazy insulinOrefRapidActingPlugin) { + public ConfigBuilderPlugin( + Lazy insulinOrefRapidActingPlugin, + AAPSLogger aapsLogger + ) { super(new PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ConfigBuilderFragment.class.getName()) @@ -90,6 +91,7 @@ public class ConfigBuilderPlugin extends PluginBase { .description(R.string.description_config_builder) ); this.insulinOrefRapidActingPlugin = insulinOrefRapidActingPlugin; + this.aapsLogger = aapsLogger; configBuilderPlugin = this; // TODO: only while transitioning to Dagger } @@ -122,8 +124,7 @@ public class ConfigBuilderPlugin extends PluginBase { public void storeSettings(String from) { if (pluginList != null) { - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Storing settings from: " + from); + aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: " + from); verifySelectionInCategories(); @@ -146,19 +147,16 @@ public class ConfigBuilderPlugin extends PluginBase { private void savePref(PluginBase p, PluginType type, boolean storeVisible) { String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled"; SP.putBoolean(settingEnabled, p.isEnabled(type)); - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type)); + aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type)); if (storeVisible) { String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible"; SP.putBoolean(settingVisible, p.isFragmentVisible()); - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible()); + aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible()); } } private void loadSettings() { - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Loading stored settings"); + aapsLogger.debug(LTag.CONFIGBUILDER, "Loading stored settings"); for (PluginBase p : pluginList) { PluginType type = p.getType(); loadPref(p, type, true); @@ -178,8 +176,7 @@ public class ConfigBuilderPlugin extends PluginBase { else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) { p.setPluginEnabled(type, true); } - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type)); + aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type)); if (loadVisible) { String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible"; if (SP.contains(settingVisible)) @@ -187,8 +184,7 @@ public class ConfigBuilderPlugin extends PluginBase { else if (p.getType() == type && p.pluginDescription.visibleByDefault) { p.setFragmentVisible(type, true); } - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible()); + aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingVisible + ":" + p.isFragmentVisible()); } } @@ -196,11 +192,9 @@ public class ConfigBuilderPlugin extends PluginBase { private void upgradeSettings() { if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled")) return; - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Upgrading stored settings"); + aapsLogger.debug(LTag.CONFIGBUILDER, "Upgrading stored settings"); for (PluginBase p : pluginList) { - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Processing " + p.getName()); + aapsLogger.debug(LTag.CONFIGBUILDER, "Processing " + p.getName()); for (int type = 1; type < 11; type++) { PluginType newType; switch (type) { @@ -291,21 +285,20 @@ public class ConfigBuilderPlugin extends PluginBase { } public void logPluginStatus() { - if (L.isEnabled(L.CONFIGBUILDER)) - for (PluginBase p : pluginList) { - log.debug(p.getName() + ":" + - (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") + - (p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") + - (p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") + - (p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") + - (p.isEnabled(PluginType.APS) ? " APS" : "") + - (p.isEnabled(PluginType.PUMP) ? " PUMP" : "") + - (p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") + - (p.isEnabled(PluginType.LOOP) ? " LOOP" : "") + - (p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") + - (p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "") - ); - } + for (PluginBase p : pluginList) { + aapsLogger.debug(LTag.CONFIGBUILDER, p.getName() + ":" + + (p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") + + (p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") + + (p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") + + (p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") + + (p.isEnabled(PluginType.APS) ? " APS" : "") + + (p.isEnabled(PluginType.PUMP) ? " PUMP" : "") + + (p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") + + (p.isEnabled(PluginType.LOOP) ? " LOOP" : "") + + (p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") + + (p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "") + ); + } } private void verifySelectionInCategories() { @@ -320,8 +313,7 @@ public class ConfigBuilderPlugin extends PluginBase { if (activeInsulin == null) { activeInsulin = insulinOrefRapidActingPlugin.get(); insulinOrefRapidActingPlugin.get().setPluginEnabled(PluginType.INSULIN, true); - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Defaulting InsulinOrefRapidActingPlugin"); + aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting InsulinOrefRapidActingPlugin"); } this.setFragmentVisiblities(((PluginBase) activeInsulin).getName(), pluginsInCategory, PluginType.INSULIN); @@ -331,8 +323,7 @@ public class ConfigBuilderPlugin extends PluginBase { if (activeSensitivity == null) { activeSensitivity = SensitivityOref0Plugin.getPlugin(); SensitivityOref0Plugin.getPlugin().setPluginEnabled(PluginType.SENSITIVITY, true); - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Defaulting SensitivityOref0Plugin"); + aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting SensitivityOref0Plugin"); } this.setFragmentVisiblities(((PluginBase) activeSensitivity).getName(), pluginsInCategory, PluginType.SENSITIVITY); @@ -348,8 +339,7 @@ public class ConfigBuilderPlugin extends PluginBase { if (activePump == null) { activePump = VirtualPumpPlugin.getPlugin(); VirtualPumpPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true); - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Defaulting VirtualPumpPlugin"); + aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting VirtualPumpPlugin"); } this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP); @@ -407,8 +397,7 @@ public class ConfigBuilderPlugin extends PluginBase { private void setFragmentVisiblities(String activePluginName, ArrayList pluginsInCategory, PluginType pluginType) { - if (L.isEnabled(L.CONFIGBUILDER)) - log.debug("Selected interface: " + activePluginName); + aapsLogger.debug(LTag.CONFIGBUILDER, "Selected interface: " + activePluginName); for (PluginBase p : pluginsInCategory) { if (!p.getName().equals(activePluginName)) { p.setFragmentVisible(pluginType, false); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index b2b6515b7d..425217e15f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -22,7 +22,9 @@ import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBus.send import info.nightscout.androidaps.plugins.bus.RxBus.toObservable @@ -53,7 +55,8 @@ import javax.inject.Singleton class SmsCommunicatorPlugin @Inject constructor( val configBuilderPlugin: ConfigBuilderPlugin, val resourceHelper: ResourceHelper, - val constraintChecker: ConstraintChecker + val constraintChecker: ConstraintChecker, + val aapsLogger: AAPSLogger ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(SmsCommunicatorFragment::class.java.name) @@ -62,8 +65,6 @@ class SmsCommunicatorPlugin @Inject constructor( .preferencesId(R.xml.pref_smscommunicator) .description(R.string.description_sms_communicator) ) { - - private val log = LoggerFactory.getLogger(L.SMS) private val disposable = CompositeDisposable() var allowedNumbers: MutableList = ArrayList() var messageToConfirm: AuthRequest? = null @@ -149,7 +150,7 @@ class SmsCommunicatorPlugin @Inject constructor( for (number in substrings) { val cleaned = number.replace("\\s+".toRegex(), "") allowedNumbers.add(cleaned) - log.debug("Found allowed number: $cleaned") + aapsLogger.debug(LTag.SMS,"Found allowed number: $cleaned") } } } @@ -181,11 +182,11 @@ class SmsCommunicatorPlugin @Inject constructor( fun processSms(receivedSms: Sms) { if (!isEnabled(PluginType.GENERAL)) { - log.debug("Ignoring SMS. Plugin disabled.") + aapsLogger.debug(LTag.SMS,"Ignoring SMS. Plugin disabled.") return } if (!isAllowedNumber(receivedSms.phoneNumber)) { - log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed") + aapsLogger.debug(LTag.SMS,"Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed") receivedSms.ignored = true messages.add(receivedSms) send(EventSmsCommunicatorUpdateGui()) @@ -193,7 +194,7 @@ class SmsCommunicatorPlugin @Inject constructor( } val pump = configBuilderPlugin.activePump ?: return messages.add(receivedSms) - log.debug(receivedSms.toString()) + aapsLogger.debug(LTag.SMS,receivedSms.toString()) val splitted = receivedSms.text.split(Regex("\\s+")).toTypedArray() val remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false) if (splitted.isNotEmpty() && isCommand(splitted[0].toUpperCase(Locale.getDefault()), receivedSms.phoneNumber)) { @@ -858,7 +859,7 @@ class SmsCommunicatorPlugin @Inject constructor( val smsManager = SmsManager.getDefault() sms.text = stripAccents(sms.text) try { - if (L.isEnabled(L.SMS)) log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text) + aapsLogger.debug(LTag.SMS,"Sending SMS to " + sms.phoneNumber + ": " + sms.text) if (sms.text.toByteArray().size <= 140) smsManager.sendTextMessage(sms.phoneNumber, null, sms.text, null, null) else { val parts = smsManager.divideMessage(sms.text) 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 f24129f036..3153b2c4bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.services; -import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.provider.Telephony; @@ -19,8 +18,10 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventNsTreatment; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.BundleLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg; @@ -44,7 +45,6 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; public class DataService extends DaggerIntentService { - private Logger log = LoggerFactory.getLogger(L.DATASERVICE); public DataService() { super("DataService"); @@ -53,15 +53,17 @@ public class DataService extends DaggerIntentService { @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; + @Inject + AAPSLogger aapsLogger; + @Inject SP sp; @Override protected void onHandleIntent(final Intent intent) { - if (L.isEnabled(L.DATASERVICE)) { - log.debug("onHandleIntent " + intent); - log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras())); - } + aapsLogger.debug(LTag.DATASERVICE, "onHandleIntent " + intent); + aapsLogger.debug(LTag.DATASERVICE, "onHandleIntent " + BundleLogger.log(intent.getExtras())); + boolean acceptNSData = !sp.getBoolean(R.string.key_ns_upload_only, false); Bundle bundles = intent.getExtras(); @@ -111,8 +113,7 @@ public class DataService extends DaggerIntentService { smsCommunicatorPlugin.handleNewData(intent); } - if (L.isEnabled(L.DATASERVICE)) - log.debug("onHandleIntent exit " + intent); + aapsLogger.debug(LTag.DATASERVICE, "onHandleIntent exit " + intent); DataReceiver.completeWakefulIntent(intent); } @@ -124,8 +125,7 @@ public class DataService extends DaggerIntentService { private void handleNewDataFromNSClient(Intent intent) { Bundle bundles = intent.getExtras(); if (bundles == null) return; - if (L.isEnabled(L.DATASERVICE)) - log.debug("Got intent: " + intent.getAction()); + aapsLogger.debug(LTag.DATASERVICE, "Got intent: " + intent.getAction()); if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { @@ -143,7 +143,7 @@ public class DataService extends DaggerIntentService { } } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.DATASERVICE, "Unhandled exception", e); } } @@ -164,7 +164,7 @@ public class DataService extends DaggerIntentService { } } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.DATASERVICE, "Unhandled exception", e); } } @@ -185,7 +185,7 @@ public class DataService extends DaggerIntentService { } } } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.DATASERVICE, "Unhandled exception", e); } } } @@ -210,7 +210,7 @@ public class DataService extends DaggerIntentService { double carbs = JsonHelper.safeGetDouble(json, "carbs"); String eventType = JsonHelper.safeGetString(json, "eventType"); if (eventType == null) { - log.debug("Wrong treatment. Ignoring : " + json.toString()); + aapsLogger.debug(LTag.DATASERVICE, "Wrong treatment. Ignoring : " + json.toString()); return; } if (insulin > 0 || carbs > 0) { @@ -258,8 +258,7 @@ public class DataService extends DaggerIntentService { NSMbg nsMbg = new NSMbg(mbgJson); CareportalEvent careportalEvent = new CareportalEvent(nsMbg); MainApp.getDbHelper().createOrUpdate(careportalEvent); - if (L.isEnabled(L.DATASERVICE)) - log.debug("Adding/Updating new MBG: " + careportalEvent.toString()); + aapsLogger.debug(LTag.DATASERVICE, "Adding/Updating new MBG: " + careportalEvent.toString()); } } From 93bc1791816346e09f8bbf25378cc94db8779856 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 28 Dec 2019 02:49:00 +0100 Subject: [PATCH 045/316] add new logger to APS plugins --- .../dependencyInjection/AppComponent.kt | 3 ++ .../dependencyInjection/AppModule.kt | 12 +++-- .../DetermineBasalAdapterAMAJS.java | 48 ++++++++--------- .../openAPSAMA/DetermineBasalResultAMA.java | 18 +++---- .../aps/openAPSAMA/OpenAPSAMAFragment.kt | 10 ++-- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 49 +++++++---------- .../openAPSMA/DetermineBasalAdapterMAJS.java | 27 +++++----- .../aps/openAPSMA/DetermineBasalResultMA.java | 17 +++--- .../plugins/aps/openAPSMA/LoggerCallback.java | 18 ++++--- .../aps/openAPSMA/OpenAPSMAFragment.kt | 1 - .../aps/openAPSMA/OpenAPSMAPlugin.java | 38 ++++++------- .../DetermineBasalAdapterSMBJS.java | 54 +++++++++---------- .../openAPSSMB/DetermineBasalResultSMB.java | 22 ++++---- .../aps/openAPSSMB/OpenAPSSMBFragment.kt | 10 ++-- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 53 ++++++++---------- .../nightscout/androidaps/utils/Profiler.java | 12 ++++- 16 files changed, 191 insertions(+), 201 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 770495bb1c..a35de81bab 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,6 +5,7 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5 import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS import info.nightscout.androidaps.queue.commands.CommandSetProfile @@ -30,6 +31,8 @@ interface AppComponent : AndroidInjector { fun injectObjective5(objective5: Objective5) + fun injectLoggerCallback(loggerCallback: LoggerCallback) + @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index a202f18dff..7cee10e9b3 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.AAPSLoggerDebug import info.nightscout.androidaps.logging.AAPSLoggerProduction +import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation @@ -65,16 +66,19 @@ class AppModule { interface AppBindings { @ContributesAndroidInjector - fun bindDataService(): DataService + fun dataServiceInjector(): DataService @ContributesAndroidInjector - fun bindCommandSetProfile(): CommandSetProfile + fun commandSetProfileInjector(): CommandSetProfile @ContributesAndroidInjector - fun bindActionSendSMS(): ActionSendSMS + fun actionSendSMSInjector(): ActionSendSMS @ContributesAndroidInjector - fun bindObjective5(): Objective5 + fun objective5Injector(): Objective5 + + @ContributesAndroidInjector + fun loggerCallbackInjector(): LoggerCallback @Binds fun bindContext(mainApp: MainApp): Context diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java index a0cf096055..ca0cee394d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java @@ -11,8 +11,6 @@ import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Undefined; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -26,7 +24,8 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; @@ -38,7 +37,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; public class DetermineBasalAdapterAMAJS { - private static Logger log = LoggerFactory.getLogger(L.APS); + private final AAPSLogger aapsLogger; private ScriptReader mScriptReader = null; @@ -59,25 +58,25 @@ public class DetermineBasalAdapterAMAJS { private String scriptDebug = ""; - public DetermineBasalAdapterAMAJS(ScriptReader scriptReader) { + public DetermineBasalAdapterAMAJS(ScriptReader scriptReader, AAPSLogger aapsLogger) { mScriptReader = scriptReader; + this.aapsLogger = aapsLogger; } @Nullable public DetermineBasalResultAMA invoke() { - if (L.isEnabled(L.APS)) { - log.debug(">>> Invoking detemine_basal <<<"); - log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString())); - log.debug("IOB data: " + (storedIobData = mIobData.toString())); - log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString())); - log.debug("Profile: " + (storedProfile = mProfile.toString())); - log.debug("Meal data: " + (storedMeal_data = mMealData.toString())); - if (mAutosensData != null) - log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString())); - else - log.debug("Autosens data: " + (storedAutosens_data = "undefined")); - } + aapsLogger.debug(LTag.APS, ">>> Invoking detemine_basal <<<"); + aapsLogger.debug(LTag.APS, "Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString())); + aapsLogger.debug(LTag.APS, "IOB data: " + (storedIobData = mIobData.toString())); + aapsLogger.debug(LTag.APS, "Current temp: " + (storedCurrentTemp = mCurrentTemp.toString())); + aapsLogger.debug(LTag.APS, "Profile: " + (storedProfile = mProfile.toString())); + aapsLogger.debug(LTag.APS, "Meal data: " + (storedMeal_data = mMealData.toString())); + if (mAutosensData != null) + aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = mAutosensData.toString())); + else + aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = "undefined")); + DetermineBasalResultAMA determineBasalResultAMA = null; @@ -124,22 +123,21 @@ public class DetermineBasalAdapterAMAJS { // Parse the jsResult object to a JSON-String String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); - if (L.isEnabled(L.APS)) - log.debug("Result: " + result); + aapsLogger.debug(LTag.APS, "Result: " + result); try { - determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result)); + determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result), aapsLogger); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } } else { - log.error("Problem loading JS Functions"); + aapsLogger.error(LTag.APS, "Problem loading JS Functions"); } } catch (IOException e) { - log.error("IOException"); + aapsLogger.error(LTag.APS, "IOException"); } catch (RhinoException e) { - log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); + aapsLogger.error(LTag.APS, "RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { - log.error(e.toString()); + aapsLogger.error(LTag.APS, e.toString()); } finally { Context.exit(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java index 46f1057e27..3986be9117 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java @@ -3,21 +3,20 @@ package info.nightscout.androidaps.plugins.aps.openAPSAMA; import org.json.JSONException; import org.json.JSONObject; import org.mozilla.javascript.NativeObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.utils.DateUtil; public class DetermineBasalResultAMA extends APSResult { - private static Logger log = LoggerFactory.getLogger(L.APS); + private AAPSLogger aapsLogger; private double eventualBG; private double snoozeBG; - DetermineBasalResultAMA(NativeObject result, JSONObject j) { - this(); + DetermineBasalResultAMA(NativeObject result, JSONObject j, AAPSLogger aapsLogger) { + this(aapsLogger); date = DateUtil.now(); json = j; if (result.containsKey("error")) { @@ -48,13 +47,14 @@ public class DetermineBasalResultAMA extends APSResult { bolusRequested = false; } - private DetermineBasalResultAMA() { + private DetermineBasalResultAMA(AAPSLogger aapsLogger) { hasPredictions = true; + this.aapsLogger = aapsLogger; } @Override public DetermineBasalResultAMA clone() { - DetermineBasalResultAMA newResult = new DetermineBasalResultAMA(); + DetermineBasalResultAMA newResult = new DetermineBasalResultAMA(aapsLogger); doClone(newResult); newResult.eventualBG = eventualBG; @@ -68,7 +68,7 @@ public class DetermineBasalResultAMA extends APSResult { JSONObject ret = new JSONObject(this.json.toString()); return ret; } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } return null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt index 1b05d58a29..64f5d1aa91 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt @@ -8,7 +8,8 @@ import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R -import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui import info.nightscout.androidaps.plugins.bus.RxBus @@ -21,16 +22,17 @@ import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.openapsama_fragment.* import org.json.JSONArray import org.json.JSONException -import org.slf4j.LoggerFactory import javax.inject.Inject class OpenAPSAMAFragment : DaggerFragment() { - private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin + @Inject + lateinit var aapsLogger: AAPSLogger + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.openapsama_fragment, container, false) @@ -88,7 +90,7 @@ class OpenAPSAMAFragment : DaggerFragment() { val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam) openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0))) } catch (e: JSONException) { - log.error("Unhandled exception", e) + aapsLogger.error(LTag.APS,"Unhandled exception", e) openapsma_iobdata.text = "JSONException see log for details" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index 5e626004de..282bada76c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -1,13 +1,10 @@ package info.nightscout.androidaps.plugins.aps.openAPSAMA; import org.json.JSONException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -19,13 +16,15 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; @@ -40,8 +39,8 @@ import info.nightscout.androidaps.utils.Round; @Singleton public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { - private static Logger log = LoggerFactory.getLogger(L.APS); + private final AAPSLogger aapsLogger; // last values DetermineBasalAdapterAMAJS lastDetermineBasalAdapterAMAJS = null; long lastAPSRun = 0; @@ -49,7 +48,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { AutosensResult lastAutosensResult = null; @Inject - public OpenAPSAMAPlugin() { + public OpenAPSAMAPlugin(AAPSLogger aapsLogger) { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSAMAFragment.class.getName()) @@ -58,6 +57,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { .preferencesId(R.xml.pref_openapsama) .description(R.string.description_ama) ); + this.aapsLogger = aapsLogger; } @Override @@ -84,11 +84,10 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { @Override public void invoke(String initiator, boolean tempBasalFallback) { - if (L.isEnabled(L.APS)) - log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); + aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; - determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext())); + determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext()), aapsLogger); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = ProfileFunctions.getInstance().getProfile(); @@ -96,29 +95,25 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { if (profile == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.noprofileselected)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.noprofileselected)); return; } if (pump == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.nopumpselected)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.nopumpselected)); return; } if (!isEnabled(PluginType.APS)) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.openapsma_disabled)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_noglucosedata)); return; } @@ -133,13 +128,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { long start = System.currentTimeMillis(); long startPart = System.currentTimeMillis(); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile); - if (L.isEnabled(L.APS)) - Profiler.log(log, "calculateIobArrayInDia()", startPart); + Profiler.log(aapsLogger, LTag.APS, "calculateIobArrayInDia()", startPart); startPart = System.currentTimeMillis(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); - if (L.isEnabled(L.APS)) - Profiler.log(log, "getMealData()", startPart); + Profiler.log(aapsLogger, LTag.APS, "getMealData()", startPart); double maxIob = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); @@ -180,10 +173,8 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { lastAutosensResult = new AutosensResult(); lastAutosensResult.sensResult = "autosens disabled"; } - if (L.isEnabled(L.APS)) - Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); - if (L.isEnabled(L.APS)) - Profiler.log(log, "AMA data gathering", start); + Profiler.log(aapsLogger, LTag.APS, "detectSensitivityandCarbAbsorption()", startPart); + Profiler.log(aapsLogger, LTag.APS, "AMA data gathering", start); start = System.currentTimeMillis(); @@ -199,12 +190,10 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { DetermineBasalResultAMA determineBasalResultAMA = determineBasalAdapterAMAJS.invoke(); - if (L.isEnabled(L.APS)) - Profiler.log(log, "AMA calculation", start); + Profiler.log(aapsLogger, LTag.APS, "AMA calculation", start); // Fix bug determine basal if (determineBasalResultAMA == null) { - if (L.isEnabled(L.APS)) - log.error("SMB calculation returned null"); + aapsLogger.error(LTag.APS, "SMB calculation returned null"); lastDetermineBasalAdapterAMAJS = null; lastAPSResult = null; lastAPSRun = 0; @@ -219,7 +208,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { try { determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java index dbc7782ab3..657d1baab6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java @@ -9,8 +9,6 @@ import org.mozilla.javascript.NativeObject; import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -20,20 +18,22 @@ import javax.annotation.Nullable; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SP; public class DetermineBasalAdapterMAJS { - private static Logger log = LoggerFactory.getLogger(L.APS); + private final AAPSLogger aapsLogger; private ScriptReader mScriptReader; private JSONObject mProfile; private JSONObject mGlucoseStatus; @@ -47,8 +47,9 @@ public class DetermineBasalAdapterMAJS { private String storedProfile = null; private String storedMeal_data = null; - DetermineBasalAdapterMAJS(ScriptReader scriptReader) { + DetermineBasalAdapterMAJS(ScriptReader scriptReader, AAPSLogger aapsLogger) { mScriptReader = scriptReader; + this.aapsLogger = aapsLogger; } @Nullable @@ -102,21 +103,21 @@ public class DetermineBasalAdapterMAJS { // Parse the jsResult object to a JSON-String String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); if (L.isEnabled(L.APS)) - log.debug("Result: " + result); + aapsLogger.debug(LTag.APS, "Result: " + result); try { - determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result)); + determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result), aapsLogger); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } } else { - log.debug("Problem loading JS Functions"); + aapsLogger.debug(LTag.APS, "Problem loading JS Functions"); } } catch (IOException e) { - log.error("IOException"); + aapsLogger.error(LTag.APS, "IOException"); } catch (RhinoException e) { - log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); + aapsLogger.error(LTag.APS, "RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { - log.error(e.toString()); + aapsLogger.error(LTag.APS, e.toString()); } finally { Context.exit(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java index bbbcf7f893..60877fd773 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java @@ -3,20 +3,20 @@ package info.nightscout.androidaps.plugins.aps.openAPSMA; import org.json.JSONException; import org.json.JSONObject; import org.mozilla.javascript.NativeObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; public class DetermineBasalResultMA extends APSResult { - private static Logger log = LoggerFactory.getLogger(L.APS); + private AAPSLogger aapsLogger; private double eventualBG; private double snoozeBG; private String mealAssist; - DetermineBasalResultMA(NativeObject result, JSONObject j) { + DetermineBasalResultMA(NativeObject result, JSONObject j, AAPSLogger aapsLogger) { + this(aapsLogger); json = j; if (result.containsKey("error")) { reason = (String) result.get("error"); @@ -49,12 +49,13 @@ public class DetermineBasalResultMA extends APSResult { } } - private DetermineBasalResultMA() { + private DetermineBasalResultMA(AAPSLogger aapsLogger) { + this.aapsLogger = aapsLogger; } @Override public DetermineBasalResultMA clone() { - DetermineBasalResultMA newResult = new DetermineBasalResultMA(); + DetermineBasalResultMA newResult = new DetermineBasalResultMA(aapsLogger); doClone(newResult); newResult.eventualBG = eventualBG; @@ -69,7 +70,7 @@ public class DetermineBasalResultMA extends APSResult { JSONObject ret = new JSONObject(this.json.toString()); return ret; } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } return null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java index a2596d9174..d7e0c44d42 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java @@ -1,10 +1,12 @@ package info.nightscout.androidaps.plugins.aps.openAPSMA; import org.mozilla.javascript.ScriptableObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.logging.L; +import javax.inject.Inject; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; /** * Created by adrian on 15/10/17. @@ -13,7 +15,8 @@ import info.nightscout.androidaps.logging.L; public class LoggerCallback extends ScriptableObject { - private static Logger log = LoggerFactory.getLogger(L.APS); + @Inject + AAPSLogger aapsLogger; private static StringBuffer errorBuffer = new StringBuffer(); private static StringBuffer logBuffer = new StringBuffer(); @@ -23,6 +26,7 @@ public class LoggerCallback extends ScriptableObject { //empty constructor needed for Rhino errorBuffer = new StringBuffer(); logBuffer = new StringBuffer(); + MainApp.instance().androidInjector().inject(this); } @Override @@ -35,14 +39,12 @@ public class LoggerCallback extends ScriptableObject { } public void jsFunction_log(Object obj1) { - if (L.isEnabled(L.APS)) - log.debug(obj1.toString().trim()); + aapsLogger.debug(LTag.APS, obj1.toString().trim()); logBuffer.append(obj1.toString()); } public void jsFunction_error(Object obj1) { - if (L.isEnabled(L.APS)) - log.error(obj1.toString().trim()); + aapsLogger.error(LTag.APS, obj1.toString().trim()); errorBuffer.append(obj1.toString()); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt index e712378603..8d66a056dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt @@ -21,7 +21,6 @@ import org.slf4j.LoggerFactory import javax.inject.Inject class OpenAPSMAFragment : DaggerFragment() { - private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() @Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java index 1740dbf55c..b98b200c8d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java @@ -1,8 +1,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSMA; import org.json.JSONException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; @@ -18,7 +16,8 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; @@ -40,7 +39,7 @@ import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits; @Singleton public class OpenAPSMAPlugin extends PluginBase implements APSInterface { - private static Logger log = LoggerFactory.getLogger(L.APS); + private final AAPSLogger aapsLogger; // last values DetermineBasalAdapterMAJS lastDetermineBasalAdapterMAJS = null; @@ -48,7 +47,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { DetermineBasalResultMA lastAPSResult = null; @Inject - public OpenAPSMAPlugin() { + public OpenAPSMAPlugin(AAPSLogger aapsLogger) { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSMAFragment.class.getName()) @@ -57,6 +56,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { .preferencesId(R.xml.pref_openapsma) .description(R.string.description_ma) ); + this.aapsLogger = aapsLogger; } @Override @@ -83,11 +83,10 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { @Override public void invoke(String initiator, boolean tempBasalFallback) { - if (L.isEnabled(L.APS)) - log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); + aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterMAJS determineBasalAdapterMAJS; - determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext())); + determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()), aapsLogger); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = ProfileFunctions.getInstance().getProfile(); @@ -95,29 +94,25 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { if (profile == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.noprofileselected)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.noprofileselected)); return; } if (pump == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.nopumpselected)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.nopumpselected)); return; } if (!isEnabled(PluginType.APS)) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.openapsma_disabled)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_noglucosedata)); return; } @@ -141,8 +136,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); double maxIob = ConstraintChecker.getInstance().getMaxIOBAllowed().value(); - if (L.isEnabled(L.APS)) - Profiler.log(log, "MA data gathering", start); + Profiler.log(aapsLogger, LTag.APS, "MA data gathering", start); minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); @@ -173,16 +167,14 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { FabricPrivacy.logException(e); return; } - if (L.isEnabled(L.APS)) - Profiler.log(log, "MA calculation", start); + Profiler.log(aapsLogger, LTag.APS, "MA calculation", start); long now = System.currentTimeMillis(); DetermineBasalResultMA determineBasalResultMA = determineBasalAdapterMAJS.invoke(); if (determineBasalResultMA == null) { - if (L.isEnabled(L.APS)) - log.error("MA calculation returned null"); + aapsLogger.error(LTag.APS, "MA calculation returned null"); lastDetermineBasalAdapterMAJS = null; lastAPSResult = null; lastAPSRun = 0; @@ -196,7 +188,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { try { determineBasalResultMA.json.put("timestamp", DateUtil.toISOString(now)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } lastDetermineBasalAdapterMAJS = determineBasalAdapterMAJS; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index 7429bebeec..5d0ec02213 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -11,8 +11,6 @@ import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Undefined; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; @@ -27,7 +25,8 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; @@ -39,7 +38,7 @@ import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; public class DetermineBasalAdapterSMBJS { - private static Logger log = LoggerFactory.getLogger(L.APS); + private final AAPSLogger aapsLogger; private ScriptReader mScriptReader; @@ -68,8 +67,9 @@ public class DetermineBasalAdapterSMBJS { * Main code */ - DetermineBasalAdapterSMBJS(ScriptReader scriptReader) { + DetermineBasalAdapterSMBJS(ScriptReader scriptReader, AAPSLogger aapsLogger) { mScriptReader = scriptReader; + this.aapsLogger = aapsLogger; } @@ -77,21 +77,20 @@ public class DetermineBasalAdapterSMBJS { public DetermineBasalResultSMB invoke() { - if (L.isEnabled(L.APS)) { - log.debug(">>> Invoking detemine_basal <<<"); - log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString())); - log.debug("IOB data: " + (storedIobData = mIobData.toString())); - log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString())); - log.debug("Profile: " + (storedProfile = mProfile.toString())); - log.debug("Meal data: " + (storedMeal_data = mMealData.toString())); - if (mAutosensData != null) - log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString())); - else - log.debug("Autosens data: " + (storedAutosens_data = "undefined")); - log.debug("Reservoir data: " + "undefined"); - log.debug("MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed)); - log.debug("SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed)); - } + aapsLogger.debug(LTag.APS, ">>> Invoking detemine_basal <<<"); + aapsLogger.debug(LTag.APS, "Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString())); + aapsLogger.debug(LTag.APS, "IOB data: " + (storedIobData = mIobData.toString())); + aapsLogger.debug(LTag.APS, "Current temp: " + (storedCurrentTemp = mCurrentTemp.toString())); + aapsLogger.debug(LTag.APS, "Profile: " + (storedProfile = mProfile.toString())); + aapsLogger.debug(LTag.APS, "Meal data: " + (storedMeal_data = mMealData.toString())); + if (mAutosensData != null) + aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = mAutosensData.toString())); + else + aapsLogger.debug(LTag.APS, "Autosens data: " + (storedAutosens_data = "undefined")); + aapsLogger.debug(LTag.APS, "Reservoir data: " + "undefined"); + aapsLogger.debug(LTag.APS, "MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed)); + aapsLogger.debug(LTag.APS, "SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed)); + DetermineBasalResultSMB determineBasalResultSMB = null; @@ -142,22 +141,21 @@ public class DetermineBasalAdapterSMBJS { // Parse the jsResult object to a JSON-String String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); - if (L.isEnabled(L.APS)) - log.debug("Result: " + result); + aapsLogger.debug(LTag.APS, "Result: " + result); try { - determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result)); + determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result), aapsLogger); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } } else { - log.error("Problem loading JS Functions"); + aapsLogger.error(LTag.APS, "Problem loading JS Functions"); } } catch (IOException e) { - log.error("IOException"); + aapsLogger.error(LTag.APS, "IOException"); } catch (RhinoException e) { - log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); + aapsLogger.error(LTag.APS, "RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { - log.error(e.toString()); + aapsLogger.error(LTag.APS, e.toString()); } finally { Context.exit(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java index 9d0bd22557..f259ed2fa4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java @@ -2,21 +2,20 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.utils.DateUtil; public class DetermineBasalResultSMB extends APSResult { - private static final Logger log = LoggerFactory.getLogger(L.APS); + private final AAPSLogger aapsLogger; private double eventualBG; private double snoozeBG; - DetermineBasalResultSMB(JSONObject result) { - this(); + DetermineBasalResultSMB(JSONObject result, AAPSLogger aapsLogger) { + this(aapsLogger); date = DateUtil.now(); json = result; try { @@ -53,21 +52,22 @@ public class DetermineBasalResultSMB extends APSResult { try { deliverAt = DateUtil.fromISODateString(date).getTime(); } catch (Exception e) { - log.warn("Error parsing 'deliverAt' date: " + date, e); + aapsLogger.error(LTag.APS, "Error parsing 'deliverAt' date: " + date, e); } } } catch (JSONException e) { - log.error("Error parsing determine-basal result JSON", e); + aapsLogger.error(LTag.APS, "Error parsing determine-basal result JSON", e); } } - private DetermineBasalResultSMB() { + private DetermineBasalResultSMB(AAPSLogger aapsLogger) { hasPredictions = true; + this.aapsLogger = aapsLogger; } @Override public DetermineBasalResultSMB clone() { - DetermineBasalResultSMB newResult = new DetermineBasalResultSMB(); + DetermineBasalResultSMB newResult = new DetermineBasalResultSMB(aapsLogger); doClone(newResult); newResult.eventualBG = eventualBG; @@ -80,7 +80,7 @@ public class DetermineBasalResultSMB extends APSResult { try { return new JSONObject(this.json.toString()); } catch (JSONException e) { - log.error("Error converting determine-basal result to JSON", e); + aapsLogger.error(LTag.APS, "Error converting determine-basal result to JSON", e); } return null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt index 1ec66a0edd..b68542b40a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt @@ -9,7 +9,8 @@ import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R -import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui import info.nightscout.androidaps.plugins.bus.RxBus @@ -22,16 +23,17 @@ import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.openapsama_fragment.* import org.json.JSONArray import org.json.JSONException -import org.slf4j.LoggerFactory import javax.inject.Inject class OpenAPSSMBFragment : DaggerFragment() { - private val log = LoggerFactory.getLogger(L.APS) private var disposable: CompositeDisposable = CompositeDisposable() @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin + @Inject + lateinit var aapsLogger: AAPSLogger + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.openapsama_fragment, container, false) @@ -88,7 +90,7 @@ class OpenAPSSMBFragment : DaggerFragment() { val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam) openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0))) } catch (e: JSONException) { - log.error("Unhandled exception", e) + aapsLogger.error(LTag.APS, "Unhandled exception", e) @SuppressLint("SetTextl18n") openapsma_iobdata.text = "JSONException see log for details" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index 1565bf819e..513efc36ea 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -2,8 +2,6 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; import org.jetbrains.annotations.NotNull; import org.json.JSONException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; @@ -21,7 +19,8 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; @@ -45,9 +44,9 @@ import info.nightscout.androidaps.utils.ToastUtils; @Singleton public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { - private static Logger log = LoggerFactory.getLogger(L.APS); private static OpenAPSSMBPlugin openAPSSMBPlugin; + private final AAPSLogger aapsLogger; /** * @deprecated Use dagger to get an instance @@ -66,7 +65,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr AutosensResult lastAutosensResult = null; @Inject - public OpenAPSSMBPlugin() { + public OpenAPSSMBPlugin(AAPSLogger aapsLogger) { super(new PluginDescription() .mainType(PluginType.APS) .fragmentClass(OpenAPSSMBFragment.class.getName()) @@ -76,6 +75,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr .description(R.string.description_smb) ); this.openAPSSMBPlugin = this; // TODO: only while transitioning to Dagger + this.aapsLogger = aapsLogger; } @Override @@ -102,11 +102,10 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr @Override public void invoke(String initiator, boolean tempBasalFallback) { - if (L.isEnabled(L.APS)) - log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); + aapsLogger.debug(LTag.APS, "invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS; - determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext())); + determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext()), aapsLogger); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); Profile profile = ProfileFunctions.getInstance().getProfile(); @@ -114,29 +113,25 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr if (profile == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.noprofileselected)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.noprofileselected)); return; } if (pump == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.nopumpselected)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.nopumpselected)); return; } if (!isEnabled(PluginType.APS)) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.openapsma_disabled)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); - if (L.isEnabled(L.APS)) - log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); + aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_noglucosedata)); return; } @@ -156,8 +151,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr long startPart = System.currentTimeMillis(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); - if (L.isEnabled(L.APS)) - Profiler.log(log, "getMealData()", startPart); + Profiler.log(aapsLogger, LTag.APS, "getMealData()", startPart); Constraint maxIOBAllowedConstraint = ConstraintChecker.getInstance().getMaxIOBAllowed(); inputConstraints.copyReasons(maxIOBAllowedConstraint); @@ -202,8 +196,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr } IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget); - if (L.isEnabled(L.APS)) - Profiler.log(log, "calculateIobArrayInDia()", startPart); + Profiler.log(aapsLogger, LTag.APS, "calculateIobArrayInDia()", startPart); startPart = System.currentTimeMillis(); Constraint smbAllowed = new Constraint<>(!tempBasalFallback); @@ -218,10 +211,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr ConstraintChecker.getInstance().isUAMEnabled(uam); inputConstraints.copyReasons(uam); - if (L.isEnabled(L.APS)) - Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); - if (L.isEnabled(L.APS)) - Profiler.log(log, "SMB data gathering", start); + Profiler.log(aapsLogger, LTag.APS, "detectSensitivityandCarbAbsorption()", startPart); + Profiler.log(aapsLogger, LTag.APS, "SMB data gathering", start); start = System.currentTimeMillis(); try { @@ -240,11 +231,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr long now = System.currentTimeMillis(); DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke(); - if (L.isEnabled(L.APS)) - Profiler.log(log, "SMB calculation", start); + Profiler.log(aapsLogger, LTag.APS, "SMB calculation", start); if (determineBasalResultSMB == null) { - if (L.isEnabled(L.APS)) - log.error("SMB calculation returned null"); + aapsLogger.error(LTag.APS, "SMB calculation returned null"); lastDetermineBasalAdapterSMBJS = null; lastAPSResult = null; lastAPSRun = 0; @@ -259,7 +248,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr try { determineBasalResultSMB.json.put("timestamp", DateUtil.toISOString(now)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error(LTag.APS, "Unhandled exception", e); } determineBasalResultSMB.inputConstraints = inputConstraints; @@ -274,11 +263,11 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr } // safety checks - private static boolean checkOnlyHardLimits(Double value, String valueName, double lowLimit, double highLimit) { + private boolean checkOnlyHardLimits(Double value, String valueName, double lowLimit, double highLimit) { return value.equals(verifyHardLimits(value, valueName, lowLimit, highLimit)); } - private static Double verifyHardLimits(Double value, String valueName, double lowLimit, double highLimit) { + private Double verifyHardLimits(Double value, String valueName, double lowLimit, double highLimit) { Double newvalue = value; if (newvalue < lowLimit || newvalue > highLimit) { newvalue = Math.max(newvalue, lowLimit); @@ -286,7 +275,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr String msg = String.format(MainApp.gs(R.string.valueoutofrange), valueName); msg += ".\n"; msg += String.format(MainApp.gs(R.string.valuelimitedto), value, newvalue); - log.error(msg); + aapsLogger.error(LTag.APS, msg); NSUpload.uploadError(msg); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/Profiler.java b/app/src/main/java/info/nightscout/androidaps/utils/Profiler.java index 05eed9e97d..b23f664261 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/Profiler.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/Profiler.java @@ -2,15 +2,25 @@ package info.nightscout.androidaps.utils; import org.slf4j.Logger; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; + /** * Created by mike on 29.01.2017. */ public class Profiler { - public Profiler(){} + public Profiler() { + } + @Deprecated static public void log(Logger log, String function, long start) { long msec = System.currentTimeMillis() - start; log.debug(">>> " + function + " <<< executed in " + msec + " miliseconds"); } + + static public void log(AAPSLogger log, LTag lTag, String function, long start) { + long msec = System.currentTimeMillis() - start; + log.debug(lTag, ">>> " + function + " <<< executed in " + msec + " miliseconds"); + } } From a98b3ed6ac622c5804158a11681cb404de7ad49c Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 28 Dec 2019 02:53:55 +0100 Subject: [PATCH 046/316] constraintsInterface java -> kotlin --- .../interfaces/ConstraintsInterface.java | 66 ---------------- .../interfaces/ConstraintsInterface.kt | 79 +++++++++++++++++++ build.gradle | 7 ++ 3 files changed, 86 insertions(+), 66 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java create mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java deleted file mode 100644 index 14b2d549af..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java +++ /dev/null @@ -1,66 +0,0 @@ -package info.nightscout.androidaps.interfaces; - -import info.nightscout.androidaps.data.Profile; - -/** - * Created by mike on 15.06.2016. - */ -public interface ConstraintsInterface { - - default Constraint isLoopInvocationAllowed(Constraint value) { - return value; - } - - default Constraint isClosedLoopAllowed(Constraint value) { - return value; - } - - default Constraint isAutosensModeEnabled(Constraint value) { - return value; - } - - default Constraint isAMAModeEnabled(Constraint value) { - return value; - } - - default Constraint isSMBModeEnabled(Constraint value) { - return value; - } - - default Constraint isUAMEnabled(Constraint value) { - return value; - } - - default Constraint isAdvancedFilteringEnabled(Constraint value) { - return value; - } - - default Constraint isSuperBolusEnabled(Constraint value) { - return value; - } - - default Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) { - return absoluteRate; - } - - default Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) { - return percentRate; - } - - default Constraint applyBolusConstraints(Constraint insulin) { - return insulin; - } - - default Constraint applyExtendedBolusConstraints(Constraint insulin) { - return insulin; - } - - default Constraint applyCarbsConstraints(Constraint carbs) { - return carbs; - } - - default Constraint applyMaxIOBConstraints(Constraint maxIob) { - return maxIob; - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt new file mode 100644 index 0000000000..0634bbb139 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.kt @@ -0,0 +1,79 @@ +package info.nightscout.androidaps.interfaces + +import info.nightscout.androidaps.data.Profile + +/** + * Created by mike on 15.06.2016. + */ +interface ConstraintsInterface { + + @JvmDefault + fun isLoopInvocationAllowed(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isClosedLoopAllowed(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isAutosensModeEnabled(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isAMAModeEnabled(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isSMBModeEnabled(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isUAMEnabled(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isAdvancedFilteringEnabled(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun isSuperBolusEnabled(value: Constraint): Constraint { + return value + } + + @JvmDefault + fun applyBasalConstraints(absoluteRate: Constraint, profile: Profile): Constraint { + return absoluteRate + } + + @JvmDefault + fun applyBasalPercentConstraints(percentRate: Constraint, profile: Profile): Constraint { + return percentRate + } + + @JvmDefault + fun applyBolusConstraints(insulin: Constraint): Constraint { + return insulin + } + + @JvmDefault + fun applyExtendedBolusConstraints(insulin: Constraint): Constraint { + return insulin + } + + @JvmDefault + fun applyCarbsConstraints(carbs: Constraint): Constraint { + return carbs + } + + @JvmDefault + fun applyMaxIOBConstraints(maxIob: Constraint): Constraint { + return maxIob + } +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 3327014f1f..520a0dfa18 100644 --- a/build.gradle +++ b/build.gradle @@ -34,6 +34,13 @@ allprojects { } } } + //Support @JvmDefault + tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { + kotlinOptions { + freeCompilerArgs = ['-Xjvm-default=enable'] //enable or compatibility + jvmTarget = "1.8" + } + } } task clean(type: Delete) { From 3c58559a757ec5fce90e53d267f82f062d7d4d8a Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 28 Dec 2019 14:12:35 +0100 Subject: [PATCH 047/316] PluginBase -> kt --- .../androidaps/interfaces/PluginBase.java | 223 ------------------ .../androidaps/interfaces/PluginBase.kt | 180 ++++++++++++++ .../plugins/configBuilder/PluginViewHolder.kt | 2 +- .../plugins/insulin/InsulinOrefBasePlugin.kt | 4 +- .../InsulinOrefUltraRapidActingPlugin.kt | 4 - .../pump/danaR/AbstractDanaRPlugin.java | 10 - .../plugins/pump/danaRS/DanaRSPlugin.java | 10 - 7 files changed, 183 insertions(+), 250 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java create mode 100644 app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java deleted file mode 100644 index e236125255..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ /dev/null @@ -1,223 +0,0 @@ -package info.nightscout.androidaps.interfaces; - -import android.os.SystemClock; -import android.preference.Preference; -import android.preference.PreferenceFragment; - -import androidx.fragment.app.FragmentActivity; - -import org.jetbrains.annotations.NotNull; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventConfigBuilderChange; -import info.nightscout.androidaps.events.EventRebuildTabs; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui; -import info.nightscout.androidaps.queue.CommandQueue; -import info.nightscout.androidaps.utils.OKDialog; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by mike on 09.06.2016. - */ -public abstract class PluginBase { - private static Logger log = LoggerFactory.getLogger(L.CORE); - - public enum State { - NOT_INITIALIZED, - ENABLED, - DISABLED - } - - private State state = State.NOT_INITIALIZED; - private boolean isFragmentVisible = false; - public PluginDescription pluginDescription; - - - // Specific plugin with more Interfaces - protected boolean isProfileInterfaceEnabled = false; - - public PluginBase(PluginDescription pluginDescription) { - this.pluginDescription = pluginDescription; - } - - // Default always calls invoke - // Plugins that have special constraints if they get switched to may override this method - public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) { - performPluginSwitch(newState, type); - } - - protected void confirmPumpPluginActivation(boolean newState, FragmentActivity activity, PluginType type) { - if (type == PluginType.PUMP) { - boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); - if (allowHardwarePump || activity == null) { - performPluginSwitch(newState, type); - } else { - OKDialog.showConfirmation(activity, MainApp.gs(R.string.allow_hardware_pump_text), () -> { - performPluginSwitch(newState, type); - SP.putBoolean("allow_hardware_pump", true); - if (L.isEnabled(L.PUMP)) - log.debug("First time HW pump allowed!"); - }, () -> { - RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui()); - if (L.isEnabled(L.PUMP)) - log.debug("User does not allow switching to HW pump!"); - }); - } - } else { - performPluginSwitch(newState, type); - } - } - - private void performPluginSwitch(boolean enabled, PluginType type) { - setPluginEnabled(type, enabled); - setFragmentVisible(type, enabled); - ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, getType()); - ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled"); - RxBus.INSTANCE.send(new EventRebuildTabs()); - RxBus.INSTANCE.send(new EventConfigBuilderChange()); - RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui()); - ConfigBuilderPlugin.getPlugin().logPluginStatus(); - } - - public String getName() { - if (pluginDescription.pluginName == -1) - return "UKNOWN"; - else - return MainApp.gs(pluginDescription.pluginName); - } - - public String getNameShort() { - if (pluginDescription.shortName == -1) - return getName(); - String name = MainApp.gs(pluginDescription.shortName); - if (!name.trim().isEmpty()) //only if translation exists - return name; - // use long name as fallback - return getName(); - } - - public String getDescription() { - if (pluginDescription.description == -1) return null; - else return MainApp.gs(pluginDescription.description); - } - - public PluginType getType() { - return pluginDescription.mainType; - } - - public int getPreferencesId() { - return pluginDescription.preferencesId; - } - - public boolean isEnabled(PluginType type) { - if (pluginDescription.alwaysEnabled && type == pluginDescription.mainType) - return true; - if (pluginDescription.mainType == PluginType.CONSTRAINTS && type == PluginType.CONSTRAINTS) - return true; - if (type == pluginDescription.mainType) - return state == State.ENABLED && specialEnableCondition(); - if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP)) - return true; - if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.APS && isEnabled(PluginType.APS)) - return true; - if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) - return isProfileInterfaceEnabled; - return false; - } - - public boolean hasFragment() { - return pluginDescription.fragmentClass != null; - } - - - /** - * So far plugin can have it's main type + ConstraintInterface + ProfileInterface - * ConstraintInterface is enabled if main plugin is enabled - * ProfileInterface can be enabled only if main iterface is enable - */ - - public void setPluginEnabled(PluginType type, boolean newState) { - if (type == pluginDescription.mainType) { - if (newState == true) { // enabling plugin - if (state != State.ENABLED) { - onStateChange(type, state, State.ENABLED); - state = State.ENABLED; - if (L.isEnabled(L.CORE)) - log.debug("Starting: " + getName()); - onStart(); - } - } else { // disabling plugin - if (state == State.ENABLED) { - onStateChange(type, state, State.DISABLED); - state = State.DISABLED; - onStop(); - if (L.isEnabled(L.CORE)) - log.debug("Stopping: " + getName()); - } - } - } else if (type == PluginType.PROFILE) { - isProfileInterfaceEnabled = newState; - } - - } - - public void setFragmentVisible(PluginType type, boolean fragmentVisible) { - if (type == pluginDescription.mainType) { - isFragmentVisible = fragmentVisible && specialEnableCondition(); - } - } - - public boolean isFragmentVisible() { - if (pluginDescription.alwaysVisible) - return true; - if (pluginDescription.neverVisible) - return false; - return isFragmentVisible; - } - - public boolean showInList(PluginType type) { - if (pluginDescription.mainType == type) - return pluginDescription.showInList && specialShowInListCondition(); - - if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) - return isEnabled(PluginType.PUMP); - return false; - } - - public boolean specialEnableCondition() { - return true; - } - - public boolean specialShowInListCondition() { - return true; - } - - protected void onStart() { - if (getType() == PluginType.PUMP) { - new Thread(() -> { - SystemClock.sleep(3000); - CommandQueue commandQueue = ConfigBuilderPlugin.getPlugin().getCommandQueue(); - if (commandQueue != null) - commandQueue.readStatus("Pump driver changed.", null); - }).start(); - } - } - - protected void onStop() { - } - - protected void onStateChange(PluginType type, State oldState, State newState) { - } - - public void preprocessPreferences(@NotNull final PreferenceFragment preferenceFragment) { - } - - public void updatePreferenceSummary(@NotNull final Preference pref) { - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt new file mode 100644 index 0000000000..fba61e6810 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt @@ -0,0 +1,180 @@ +package info.nightscout.androidaps.interfaces + +import android.os.SystemClock +import android.preference.Preference +import android.preference.PreferenceFragment +import androidx.fragment.app.FragmentActivity +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventConfigBuilderChange +import info.nightscout.androidaps.events.EventRebuildTabs +import info.nightscout.androidaps.logging.L +import info.nightscout.androidaps.logging.L.isEnabled +import info.nightscout.androidaps.plugins.bus.RxBus.send +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui +import info.nightscout.androidaps.utils.OKDialog.showConfirmation +import info.nightscout.androidaps.utils.SP +import org.slf4j.LoggerFactory + +/** + * Created by mike on 09.06.2016. + */ +abstract class PluginBase(pluginDesc: PluginDescription) { + companion object { + private val log = LoggerFactory.getLogger(L.CORE) + } + + enum class State { + NOT_INITIALIZED, ENABLED, DISABLED + } + + lateinit var pluginDescription: PluginDescription // TODO: workaround to have pluginDescription accessible in child classes + + private var state = State.NOT_INITIALIZED + private var fragmentVisible = false + // Specific plugin with more Interfaces + protected var isProfileInterfaceEnabled = false + + init { + pluginDescription = pluginDesc + } + + // Default always calls invoke + // Plugins that have special constraints if they get switched to may override this method + open fun switchAllowed(newState: Boolean, activity: FragmentActivity?, type: PluginType) { + performPluginSwitch(newState, type) + } + + protected fun confirmPumpPluginActivation(newState: Boolean, activity: FragmentActivity?, type: PluginType) { + if (type == PluginType.PUMP) { + val allowHardwarePump = SP.getBoolean("allow_hardware_pump", false) + if (allowHardwarePump || activity == null) { + performPluginSwitch(newState, type) + } else { + showConfirmation(activity, MainApp.gs(R.string.allow_hardware_pump_text), Runnable { + performPluginSwitch(newState, type) + SP.putBoolean("allow_hardware_pump", true) + if (isEnabled(L.PUMP)) log.debug("First time HW pump allowed!") + }, Runnable { + send(EventConfigBuilderUpdateGui()) + if (isEnabled(L.PUMP)) log.debug("User does not allow switching to HW pump!") + }) + } + } else { + performPluginSwitch(newState, type) + } + } + + private fun performPluginSwitch(enabled: Boolean, type: PluginType) { + setPluginEnabled(type, enabled) + setFragmentVisible(type, enabled) + ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, type) + ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled") + send(EventRebuildTabs()) + send(EventConfigBuilderChange()) + send(EventConfigBuilderUpdateGui()) + ConfigBuilderPlugin.getPlugin().logPluginStatus() + } + + open val name: String + get() = if (pluginDescription.pluginName == -1) "UNKNOWN" else MainApp.gs(pluginDescription.pluginName) + + //only if translation exists + // use long name as fallback + val nameShort: String + get() { + if (pluginDescription.shortName == -1) return name + val translatedName = MainApp.gs(pluginDescription.shortName) + return if (!translatedName.trim { it <= ' ' }.isEmpty()) translatedName else name + // use long name as fallback + } + + val description: String? + get() = if (pluginDescription.description == -1) null else MainApp.gs(pluginDescription.description) + + val type: PluginType + get() = pluginDescription.mainType + + open val preferencesId: Int + get() = pluginDescription.preferencesId + + fun isEnabled(type: PluginType): Boolean { + if (pluginDescription.alwaysEnabled && type == pluginDescription.mainType) return true + if (pluginDescription.mainType == PluginType.CONSTRAINTS && type == PluginType.CONSTRAINTS) return true + if (type == pluginDescription.mainType) return state == State.ENABLED && specialEnableCondition() + if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP)) return true + if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.APS && isEnabled(PluginType.APS)) return true + return if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) isProfileInterfaceEnabled else false + } + + fun hasFragment(): Boolean { + return pluginDescription.fragmentClass != null + } + + /** + * So far plugin can have it's main type + ConstraintInterface + ProfileInterface + * ConstraintInterface is enabled if main plugin is enabled + * ProfileInterface can be enabled only if main iterface is enable + */ + fun setPluginEnabled(type: PluginType, newState: Boolean) { + if (type == pluginDescription.mainType) { + if (newState) { // enabling plugin + if (state != State.ENABLED) { + onStateChange(type, state, State.ENABLED) + state = State.ENABLED + if (isEnabled(L.CORE)) log.debug("Starting: $name") + onStart() + } + } else { // disabling plugin + if (state == State.ENABLED) { + onStateChange(type, state, State.DISABLED) + state = State.DISABLED + onStop() + if (isEnabled(L.CORE)) log.debug("Stopping: $name") + } + } + } else if (type == PluginType.PROFILE) { + isProfileInterfaceEnabled = newState + } + } + + fun setFragmentVisible(type: PluginType, fragmentVisible: Boolean) { + if (type == pluginDescription.mainType) { + this.fragmentVisible = fragmentVisible && specialEnableCondition() + } + } + + fun isFragmentVisible(): Boolean { + if (pluginDescription.alwaysVisible) return true + return if (pluginDescription.neverVisible) false else fragmentVisible + } + + fun showInList(type: PluginType): Boolean { + if (pluginDescription.mainType == type) return pluginDescription.showInList && specialShowInListCondition() + return if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) isEnabled(PluginType.PUMP) else false + } + + open fun specialEnableCondition(): Boolean { + return true + } + + open fun specialShowInListCondition(): Boolean { + return true + } + + protected open fun onStart() { + if (type == PluginType.PUMP) { + Thread(Runnable { + SystemClock.sleep(3000) + val commandQueue = ConfigBuilderPlugin.getPlugin().commandQueue + commandQueue?.readStatus("Pump driver changed.", null) + }).start() + } + } + + protected open fun onStop() {} + protected open fun onStateChange(type: PluginType?, oldState: State?, newState: State?) {} + open fun preprocessPreferences(preferenceFragment: PreferenceFragment) {} + open fun updatePreferenceSummary(pref: Preference) {} +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt index 2670e78633..2376ebe635 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt @@ -77,7 +77,7 @@ class PluginViewHolder internal constructor(private val fragment: ConfigBuilderF pluginPreferences.visibility = if (plugin.preferencesId == -1 || !plugin.isEnabled(pluginType)) View.INVISIBLE else View.VISIBLE pluginVisibility.visibility = plugin.hasFragment().toVisibility() pluginVisibility.isEnabled = !(plugin.pluginDescription.neverVisible || plugin.pluginDescription.alwaysVisible) && plugin.isEnabled(pluginType) - pluginVisibility.isChecked = plugin.isFragmentVisible + pluginVisibility.isChecked = plugin.isFragmentVisible() } private fun areMultipleSelectionsAllowed(type: PluginType): Boolean { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt index d802abd28f..f76b174684 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt @@ -23,7 +23,7 @@ abstract class InsulinOrefBasePlugin() : PluginBase(PluginDescription() .visibleByDefault(false) ), InsulinInterface { - var lastWarned: Long = 0 + private var lastWarned: Long = 0 override fun getDia(): Double { val dia = userDefinedDia return if (dia >= MIN_DIA) { @@ -42,7 +42,7 @@ abstract class InsulinOrefBasePlugin() : PluginBase(PluginDescription() } } - val notificationPattern: String + private val notificationPattern: String get() = MainApp.gs(R.string.dia_too_short) open val userDefinedDia: Double diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt index 6d854bbdee..d5ce7bd7c6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt @@ -14,10 +14,6 @@ class InsulinOrefUltraRapidActingPlugin @Inject constructor(): InsulinOrefBasePl return InsulinInterface.OREF_ULTRA_RAPID_ACTING } - override fun getName(): String { - return MainApp.gs(R.string.ultrarapid_oref) - } - override fun getFriendlyName(): String { return MainApp.gs(R.string.ultrarapid_oref) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index cd25f80ba2..b243635e45 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -67,16 +67,6 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte ); } - @Override - public void onStateChange(PluginType type, State oldState, State newState) { - // if pump profile was enabled need to switch to another too - if (type == PluginType.PUMP && newState == State.DISABLED && isProfileInterfaceEnabled) { - setPluginEnabled(PluginType.PROFILE, false); - NSProfilePlugin.getPlugin().setPluginEnabled(PluginType.PROFILE, true); - NSProfilePlugin.getPlugin().setFragmentVisible(PluginType.PROFILE, true); - } - } - @Override public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) { confirmPumpPluginActivation(newState, activity, type); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 5dcbfb9057..416ec8fba2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -100,16 +100,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte pumpDescription.setPumpDescription(PumpType.DanaRS); } - @Override - public void onStateChange(PluginType type, State oldState, State newState) { - // if pump profile was enabled need to switch to another too - if (type == PluginType.PUMP && newState == State.DISABLED && isProfileInterfaceEnabled) { - setPluginEnabled(PluginType.PROFILE, false); - NSProfilePlugin.getPlugin().setPluginEnabled(PluginType.PROFILE, true); - NSProfilePlugin.getPlugin().setFragmentVisible(PluginType.PROFILE, true); - } - } - @Override public void updatePreferenceSummary(@NotNull Preference pref) { super.updatePreferenceSummary(pref); From 377b5a9991e1b6c83274614c692b0a19c7b9f216 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 28 Dec 2019 15:00:16 +0100 Subject: [PATCH 048/316] StatusLinePlugin -> kt, dagger --- .../info/nightscout/androidaps/MainApp.java | 9 +- .../activities/MyPreferenceFragment.java | 18 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 2 +- .../xdripStatusline/StatusLinePlugin.kt | 141 ++++++++++++ .../xdripStatusline/StatuslinePlugin.java | 216 ------------------ app/src/main/res/values/strings.xml | 2 + app/src/main/res/xml/pref_danarprofile.xml | 15 -- app/src/main/res/xml/pref_xdripstatus.xml | 4 +- 8 files changed, 154 insertions(+), 253 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java delete mode 100644 app/src/main/res/xml/pref_danarprofile.xml diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 31d23d68b2..6132ad1c48 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -60,7 +60,7 @@ import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin; import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; -import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; +import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin; @@ -126,9 +126,7 @@ public class MainApp extends DaggerApplication { @Inject AAPSLogger aapsLogger; - @Inject - ConfigBuilderPlugin configBuilderPlugin; - + @Inject ConfigBuilderPlugin configBuilderPlugin; @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; @Inject InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin; @Inject InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin; @@ -137,6 +135,7 @@ public class MainApp extends DaggerApplication { @Inject OpenAPSMAPlugin openAPSMAPlugin; @Inject OpenAPSAMAPlugin openAPSAMAPlugin; @Inject OpenAPSSMBPlugin openAPSSMBPlugin; + @Inject StatusLinePlugin statusLinePlugin; @Override public void onCreate() { @@ -235,7 +234,7 @@ public class MainApp extends DaggerApplication { pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(WearPlugin.initPlugin(this)); - pluginsList.add(StatuslinePlugin.initPlugin(this)); + pluginsList.add(statusLinePlugin); pluginsList.add(PersistentNotificationPlugin.getPlugin()); pluginsList.add(NSClientPlugin.getPlugin()); // if (engineeringMode) pluginsList.add(TidepoolPlugin.INSTANCE); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java index 585d3aff33..c34de1ff5e 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.java @@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; -import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; +import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; @@ -52,21 +52,18 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro @Inject OpenAPSAMAPlugin openAPSAMAPlugin; - @Inject OpenAPSMAPlugin openAPSMAPlugin; - @Inject OpenAPSSMBPlugin openAPSSMBPlugin; - @Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin; - @Inject SafetyPlugin safetyPlugin; - @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; + @Inject + StatusLinePlugin statusLinePlugin; @Override public void setArguments(Bundle args) { @@ -130,13 +127,6 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP); - - if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE) - || DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE) - || DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE) - || DanaRSPlugin.getPlugin().isEnabled(PluginType.PROFILE)) { - addPreferencesFromResource(R.xml.pref_danarprofile); - } } if (!Config.NSCLIENT) { @@ -154,7 +144,7 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro addPreferencesFromResource(R.xml.pref_datachoices); addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL); - addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL); + addPreferencesFromResourceIfEnabled(statusLinePlugin, PluginType.GENERAL); } PreferencesActivity.initSummary(getPreferenceScreen()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 425217e15f..46f58a8d2c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -93,7 +93,7 @@ class SmsCommunicatorPlugin @Inject constructor( super.onStart() disposable.add(toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) - .subscribe({ event: EventPreferenceChange? -> processSettings(event) }) { throwable: Throwable? -> FabricPrivacy.logException(throwable) } + .subscribe({ event: EventPreferenceChange? -> processSettings(event) }) { FabricPrivacy.logException(it) } ) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt new file mode 100644 index 0000000000..28e0f3c984 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -0,0 +1,141 @@ +package info.nightscout.androidaps.plugins.general.xdripStatusline + +import android.content.Intent +import android.os.Bundle +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.events.* +import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.PluginDescription +import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.TreatmentsInterface +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBus.toObservable +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.utils.DecimalFormatter +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.schedulers.Schedulers +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class StatusLinePlugin @Inject constructor( + private val sp: SP, + private val profileFunction: ProfileFunction, + private val resourceHelper: ResourceHelper, + private val configBuilderPlugin: ConfigBuilderPlugin, + private val mainApp: MainApp) : PluginBase( + PluginDescription() + .mainType(PluginType.GENERAL) + .pluginName(R.string.xdripstatus) + .shortName(R.string.xdripstatus_shortname) + .neverVisible(true) + .preferencesId(R.xml.pref_xdripstatus) + .description(R.string.description_xdrip_status_line)) { + + private val disposable = CompositeDisposable() + private var lastLoopStatus = false + + companion object { + //broadcast related constants + @Suppress("SpellCheckingInspection") + private const val EXTRA_STATUSLINE = "com.eveningoutpost.dexdrip.Extras.Statusline" + @Suppress("SpellCheckingInspection") + private const val ACTION_NEW_EXTERNAL_STATUSLINE = "com.eveningoutpost.dexdrip.ExternalStatusline" + @Suppress("SpellCheckingInspection", "unused") + private const val RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_EXTERNAL_STATUSLINE" + } + + override fun onStart() { + super.onStart() + disposable.add(toObservable(EventRefreshOverview::class.java) + .observeOn(Schedulers.io()) + .subscribe({ if (lastLoopStatus != LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventExtendedBolusChange::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventTempBasalChange::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventTreatmentChange::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventConfigBuilderChange::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventAutosensCalculationFinished::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventPreferenceChange::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + disposable.add(toObservable(EventAppInitialized::class.java) + .observeOn(Schedulers.io()) + .subscribe({ sendStatus() }) { FabricPrivacy.logException(it) }) + } + + override fun onStop() { + super.onStop() + disposable.clear() + sendStatus() + } + + private fun sendStatus() { + var status = "" // sent once on disable + val profile = profileFunction.getProfile() + if (isEnabled(PluginType.GENERAL) && profile != null) { + status = buildStatusString(profile) + } + //sendData + val bundle = Bundle() + bundle.putString(EXTRA_STATUSLINE, status) + val intent = Intent(ACTION_NEW_EXTERNAL_STATUSLINE) + intent.putExtras(bundle) + intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) + mainApp.sendBroadcast(intent, null) + } + + private fun buildStatusString(profile: Profile): String { + var status = "" + if (configBuilderPlugin.activePump == null) return "" + val loopPlugin = LoopPlugin.getPlugin() + if (!loopPlugin.isEnabled(PluginType.LOOP)) { + status += resourceHelper.gs(R.string.disabledloop) + "\n" + lastLoopStatus = false + } else if (loopPlugin.isEnabled(PluginType.LOOP)) { + lastLoopStatus = true + } + //Temp basal + val treatmentsInterface: TreatmentsInterface = TreatmentsPlugin.getPlugin() + val activeTemp = treatmentsInterface.getTempBasalFromHistory(System.currentTimeMillis()) + if (activeTemp != null) { + status += activeTemp.toStringShort() + " " + } + //IOB + treatmentsInterface.updateTotalIOBTreatments() + val bolusIob = treatmentsInterface.lastCalculationTreatments.round() + treatmentsInterface.updateTotalIOBTempBasals() + val basalIob = treatmentsInterface.lastCalculationTempBasals.round() + status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U" + if (sp.getBoolean(R.string.key_xdripstatus_detailediob, true)) { + status += ("(" + + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" + + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")") + } + if (!sp.getBoolean(R.string.key_xdripstatus_showbgi, false)) { + return status + } + val bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.isfMgdl, profileFunction.getUnits()) + status += " " + (if (bgi >= 0) "+" else "") + DecimalFormatter.to2Decimal(bgi) + status += " " + IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "StatusLinePlugin").generateCOBString() + return status + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java deleted file mode 100644 index b810624e87..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ /dev/null @@ -1,216 +0,0 @@ -package info.nightscout.androidaps.plugins.general.xdripStatusline; - -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; - -import androidx.annotation.NonNull; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.events.EventAppInitialized; -import info.nightscout.androidaps.events.EventConfigBuilderChange; -import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.events.EventPreferenceChange; -import info.nightscout.androidaps.events.EventRefreshOverview; -import info.nightscout.androidaps.events.EventTempBasalChange; -import info.nightscout.androidaps.events.EventTreatmentChange; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.FabricPrivacy; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - -/** - * Created by adrian on 17/11/16. - */ - -public class StatuslinePlugin extends PluginBase { - - private CompositeDisposable disposable = new CompositeDisposable(); - - private static StatuslinePlugin statuslinePlugin; - - public static StatuslinePlugin getPlugin() { - return statuslinePlugin; - } - - //broadcast related constants - private static final String EXTRA_STATUSLINE = "com.eveningoutpost.dexdrip.Extras.Statusline"; - private static final String ACTION_NEW_EXTERNAL_STATUSLINE = "com.eveningoutpost.dexdrip.ExternalStatusline"; - private static final String RECEIVER_PERMISSION = "com.eveningoutpost.dexdrip.permissions.RECEIVE_EXTERNAL_STATUSLINE"; - - - private boolean lastLoopStatus; - - private final Context ctx; - private SharedPreferences mPrefs; - - - public static StatuslinePlugin initPlugin(Context ctx) { - if (statuslinePlugin == null) { - statuslinePlugin = new StatuslinePlugin(ctx); - } - - return statuslinePlugin; - } - - public StatuslinePlugin(Context ctx) { - super(new PluginDescription() - .mainType(PluginType.GENERAL) - .pluginName(R.string.xdripstatus) - .shortName(R.string.xdripstatus_shortname) - .neverVisible(true) - .preferencesId(R.xml.pref_xdripstatus) - .description(R.string.description_xdrip_status_line) - ); - this.ctx = ctx; - this.mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx); - } - - @Override - protected void onStart() { - super.onStart(); - disposable.add(RxBus.INSTANCE - .toObservable(EventRefreshOverview.class) - .observeOn(Schedulers.io()) - .subscribe(event -> { - if ((lastLoopStatus != LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) - sendStatus(); - }, - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventExtendedBolusChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventTempBasalChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventTreatmentChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventConfigBuilderChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventAutosensCalculationFinished.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventPreferenceChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventAppInitialized.class) - .observeOn(Schedulers.io()) - .subscribe(event -> sendStatus(), - FabricPrivacy::logException - )); - } - - @Override - protected void onStop() { - super.onStop(); - disposable.clear(); - sendStatus(); - } - - private void sendStatus() { - String status = ""; // sent once on disable - - Profile profile = ProfileFunctions.getInstance().getProfile(); - - if (isEnabled(PluginType.GENERAL) && profile != null) { - status = buildStatusString(profile); - } - - //sendData - final Bundle bundle = new Bundle(); - bundle.putString(EXTRA_STATUSLINE, status); - Intent intent = new Intent(ACTION_NEW_EXTERNAL_STATUSLINE); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - ctx.sendBroadcast(intent, null); - } - - @NonNull - private String buildStatusString(Profile profile) { - String status = ""; - - if (ConfigBuilderPlugin.getPlugin().getActivePump() == null) - return ""; - - LoopPlugin loopPlugin = LoopPlugin.getPlugin(); - - if (!loopPlugin.isEnabled(PluginType.LOOP)) { - status += MainApp.gs(R.string.disabledloop) + "\n"; - lastLoopStatus = false; - } else if (loopPlugin.isEnabled(PluginType.LOOP)) { - lastLoopStatus = true; - } - - //Temp basal - TreatmentsInterface treatmentsInterface = TreatmentsPlugin.getPlugin(); - - TemporaryBasal activeTemp = treatmentsInterface.getTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - status += activeTemp.toStringShort() + " "; - } - - //IOB - treatmentsInterface.updateTotalIOBTreatments(); - IobTotal bolusIob = treatmentsInterface.getLastCalculationTreatments().round(); - treatmentsInterface.updateTotalIOBTempBasals(); - IobTotal basalIob = treatmentsInterface.getLastCalculationTempBasals().round(); - status += DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U"; - - - if (mPrefs.getBoolean("xdripstatus_detailediob", true)) { - status += "(" - + DecimalFormatter.to2Decimal(bolusIob.iob) + "|" - + DecimalFormatter.to2Decimal(basalIob.basaliob) + ")"; - } - - if (!mPrefs.getBoolean("xdripstatus_showbgi", false)) { - return status; - } - - double bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.getIsfMgdl(), ProfileFunctions.getSystemUnits()); - - status += " " + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to2Decimal(bgi); - status += " " + IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "StatuslinePlugin").generateCOBString(); - - return status; - } -} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index f34ec9c784..80656e4881 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1687,5 +1687,7 @@ Already set Message Clear queue? All data in queue will be lost! + xdripstatus_detailediob + xdripstatus_showbgi diff --git a/app/src/main/res/xml/pref_danarprofile.xml b/app/src/main/res/xml/pref_danarprofile.xml deleted file mode 100644 index 9129735748..0000000000 --- a/app/src/main/res/xml/pref_danarprofile.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/xml/pref_xdripstatus.xml b/app/src/main/res/xml/pref_xdripstatus.xml index 959377ea7b..46d85d3b91 100644 --- a/app/src/main/res/xml/pref_xdripstatus.xml +++ b/app/src/main/res/xml/pref_xdripstatus.xml @@ -6,12 +6,12 @@ From ca9486fab340170a216e9135bf7bff08357066d6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 28 Dec 2019 22:51:04 +0100 Subject: [PATCH 049/316] TreatmentsPlugin -> dagger --- .../nightscout/androidaps/MainActivity.java | 16 +- .../info/nightscout/androidaps/MainApp.java | 3 +- .../activities/NoSplashAppCompatActivity.kt | 6 +- .../androidaps/activities/StatsActivity.kt | 6 +- .../androidaps/activities/SurveyActivity.kt | 6 +- .../dependencyInjection/ActivitiesModule.kt | 42 +++- .../dependencyInjection/AppModule.kt | 1 + .../dependencyInjection/FragmentsModule.kt | 41 ++-- .../androidaps/dialogs/ProfileSwitchDialog.kt | 5 +- .../interfaces/TreatmentsInterface.java | 10 +- .../androidaps/logging/AAPSLogger.kt | 4 + .../androidaps/logging/AAPSLoggerDebug.kt | 16 ++ .../logging/AAPSLoggerProduction.kt | 21 +- .../plugins/configBuilder/ProfileFunction.kt | 2 - .../ProfileFunctionImplementation.kt | 28 +-- .../configBuilder/ProfileFunctions.java | 26 --- .../actions/ActionProfileSwitch.java | 13 +- .../actions/ActionProfileSwitchPercent.java | 8 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 3 +- .../general/wear/ActionStringHandler.java | 3 +- .../plugins/profile/ns/NSProfileFragment.kt | 12 +- .../plugins/treatments/TreatmentsPlugin.java | 188 +++++++++++------- .../androidaps/utils/TddCalculator.kt | 31 ++- 23 files changed, 276 insertions(+), 215 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 419004a64d..8e6a20dc04 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -37,9 +37,6 @@ import com.joanzapata.iconify.fonts.FontAwesomeModule; import javax.inject.Inject; import dagger.android.AndroidInjection; -import dagger.android.AndroidInjector; -import dagger.android.DispatchingAndroidInjector; -import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.activities.PreferencesActivity; @@ -68,10 +65,7 @@ import info.nightscout.androidaps.utils.SP; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -public class MainActivity extends NoSplashAppCompatActivity implements HasAndroidInjector { - - @Inject - DispatchingAndroidInjector androidInjector; +public class MainActivity extends NoSplashAppCompatActivity { private CompositeDisposable disposable = new CompositeDisposable(); @@ -354,12 +348,4 @@ public class MainActivity extends NoSplashAppCompatActivity implements HasAndroi return actionBarDrawerToggle.onOptionsItemSelected(item); } - - /** - * Returns an {@link AndroidInjector}. - */ - @Override - public AndroidInjector androidInjector() { - return androidInjector; - } } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 6132ad1c48..ef139464da 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -136,6 +136,7 @@ public class MainApp extends DaggerApplication { @Inject OpenAPSAMAPlugin openAPSAMAPlugin; @Inject OpenAPSSMBPlugin openAPSSMBPlugin; @Inject StatusLinePlugin statusLinePlugin; + @Inject TreatmentsPlugin treatmentsPlugin; @Override public void onCreate() { @@ -215,7 +216,7 @@ public class MainApp extends DaggerApplication { if (Config.APS) pluginsList.add(openAPSSMBPlugin); pluginsList.add(NSProfilePlugin.getPlugin()); if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.INSTANCE); - pluginsList.add(TreatmentsPlugin.getPlugin()); + pluginsList.add(treatmentsPlugin); if (!Config.NSCLIENT) pluginsList.add(safetyPlugin); if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE); if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin()); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt index 3f59cd56ef..b4ac7eff51 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt @@ -2,11 +2,13 @@ package info.nightscout.androidaps.activities import android.content.Context import android.os.Bundle -import androidx.appcompat.app.AppCompatActivity +import dagger.android.support.DaggerAppCompatActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.LocaleHelper -open class NoSplashAppCompatActivity : AppCompatActivity() { +@Suppress("registered") +open class NoSplashAppCompatActivity : DaggerAppCompatActivity() { + public override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme_NoActionBar) super.onCreate(savedInstanceState) diff --git a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt index d0ac8e3f6f..ef55984f5f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt @@ -8,14 +8,18 @@ import info.nightscout.androidaps.utils.OKDialog import info.nightscout.androidaps.utils.TddCalculator import info.nightscout.androidaps.utils.TirCalculator import kotlinx.android.synthetic.main.stats_activity.* +import javax.inject.Inject class StatsActivity : NoSplashAppCompatActivity() { + @Inject + lateinit var tddCalculator: TddCalculator + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.stats_activity) - stats_tdds.text = TddCalculator.stats() + stats_tdds.text = tddCalculator.stats() stats_tir.text = TirCalculator.stats() stats_activity.text = ActivityMonitor.stats() diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt index bf07eda9af..df4b8bd242 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -12,10 +12,14 @@ import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.utils.* import kotlinx.android.synthetic.main.survey_activity.* import org.slf4j.LoggerFactory +import javax.inject.Inject class SurveyActivity : NoSplashAppCompatActivity() { private val log = LoggerFactory.getLogger(SurveyActivity::class.java) + @Inject + lateinit var tddCalculator: TddCalculator + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.survey_activity) @@ -26,7 +30,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { val profileList = profileStore?.getProfileList() ?: return survey_spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList) - survey_tdds.text = TddCalculator.stats() + survey_tdds.text = tddCalculator.stats() survey_tir.text = TirCalculator.stats() survey_activity.text = ActivityMonitor.stats() diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt index cb3d910e5e..64446c54d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -3,14 +3,44 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.MainActivity -import info.nightscout.androidaps.activities.PreferencesActivity +import info.nightscout.androidaps.activities.* +import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity +import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity +import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity +import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRHistoryActivity +import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRUserOptionsActivity +import info.nightscout.androidaps.plugins.pump.danaRS.activities.BLEScanActivity +import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity +import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity +import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity +import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity +import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistoryActivity +import info.nightscout.androidaps.setupwizard.SetupWizardActivity @Module abstract class ActivitiesModule { - @ContributesAndroidInjector - abstract fun contributeMainActivity(): MainActivity - - @ContributesAndroidInjector - abstract fun contributesPreferencesActivity(): PreferencesActivity + @ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity + @ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity + @ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaRHistoryActivity + @ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaRUserOptionsActivity + @ContributesAndroidInjector abstract fun contributeErrorHelperActivity(): ErrorHelperActivity + @ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity + @ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity + @ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity + @ContributesAndroidInjector abstract fun contributesInsightPairingInformationActivity(): InsightPairingInformationActivity + @ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity + @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity + @ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity + @ContributesAndroidInjector abstract fun contributesPairingHelperActivity(): PairingHelperActivity + @ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity + @ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity + @ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity + @ContributesAndroidInjector abstract fun contributesRileyLinkStatusActivity(): RileyLinkStatusActivity + @ContributesAndroidInjector abstract fun contributesRileyLinkBLEScanActivity(): RileyLinkBLEScanActivity + @ContributesAndroidInjector abstract fun contributesSetupWizardActivity(): SetupWizardActivity + @ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity + @ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity + @ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 7cee10e9b3..2e520f3a04 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -17,6 +17,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5 import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.commands.CommandSetProfile import info.nightscout.androidaps.services.DataService import info.nightscout.androidaps.utils.resources.ResourceHelper diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index b3bf7d47dd..7ac458589a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -8,39 +8,22 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAFragment import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAFragment import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment +import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment @Module abstract class FragmentsModule { - @ContributesAndroidInjector - abstract fun contributesPreferencesFragment(): MyPreferenceFragment - - @ContributesAndroidInjector - abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment - - @ContributesAndroidInjector - abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment - - @ContributesAndroidInjector - abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment - - @ContributesAndroidInjector - abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment - - @ContributesAndroidInjector - abstract fun contributesCalibrationDialog(): CalibrationDialog - - @ContributesAndroidInjector - abstract fun contributesCarbsDialog(): CarbsDialog - - @ContributesAndroidInjector - abstract fun contributesCareDialog(): CareDialog - - @ContributesAndroidInjector - abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog - - @ContributesAndroidInjector - abstract fun contributesFillDialog(): FillDialog + @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment + @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment + @ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment + @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment + @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment + @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog + @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog + @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog + @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog + @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 57aaad0736..22f80c7e73 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -30,6 +30,9 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { @Inject lateinit var profileFunction: ProfileFunction + @Inject + lateinit var treatmentsPlugin: TreatmentsPlugin + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) @@ -104,7 +107,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { - profileFunction.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) + treatmentsPlugin.doProfileSwitch(profileStore, profile, duration.toInt(), percent, timeShift, eventTime) }) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java index 43661b117a..917fa1ff66 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java @@ -1,19 +1,21 @@ package info.nightscout.androidaps.interfaces; +import org.jetbrains.annotations.NotNull; + import java.util.List; import info.nightscout.androidaps.data.DetailedBolusInfo; +import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.NonOverlappingIntervals; -import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.data.ProfileIntervals; +import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.data.Intervals; -import info.nightscout.androidaps.data.ProfileIntervals; /** * Created by mike on 14.06.2016. @@ -62,6 +64,8 @@ public interface TreatmentsInterface { ProfileSwitch getProfileSwitchFromHistory(long time); ProfileIntervals getProfileSwitchesFromHistory(); void addToHistoryProfileSwitch(ProfileSwitch profileSwitch); + void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date); + void doProfileSwitch(final int duration, final int percentage, final int timeShift); long oldestDataAvailable(); diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt index e3f74fdb10..e3bc5eafaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLogger.kt @@ -6,8 +6,12 @@ package info.nightscout.androidaps.logging interface AAPSLogger { + fun debug(message: String) + fun debug(enable: Boolean, tag: LTag, message: String) fun debug(tag: LTag, message: String) fun info(tag: LTag, message: String) fun error(tag: LTag, message: String) + fun error(message: String) + fun error(message: String, throwable: Throwable) fun error(tag: LTag, message: String, throwable: Throwable) } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt index d512725176..346f12f749 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt @@ -8,6 +8,14 @@ import android.util.Log class AAPSLoggerDebug : AAPSLogger { + override fun debug(message: String) { + Log.d(LTag.CORE.tag, message) + } + + override fun debug(enable: Boolean, tag: LTag, message: String) { + if (enable) Log.d(LTag.CORE.tag, message) + } + override fun debug(tag: LTag, message: String) { Log.d(tag.tag, message) } @@ -21,6 +29,14 @@ class AAPSLoggerDebug : AAPSLogger { } + override fun error(message: String) { + Log.e(LTag.CORE.tag, message) + } + + override fun error(message: String, throwable: Throwable) { + Log.e(LTag.CORE.tag, message, throwable) + } + override fun error(tag: LTag, message: String, throwable: Throwable) { Log.e(tag.tag, message, throwable) diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt index 414fad2859..bcc11634b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt +++ b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerProduction.kt @@ -8,10 +8,19 @@ import org.slf4j.LoggerFactory class AAPSLoggerProduction : AAPSLogger { + override fun debug(message: String) { + LoggerFactory.getLogger(LTag.CORE.tag).debug(message) + } + + override fun debug(enable: Boolean, tag: LTag, message: String) { + if (enable && L.isEnabled(tag.tag)) { + LoggerFactory.getLogger(tag.tag).debug(message) + } + } + override fun debug(tag: LTag, message: String) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).debug(message) - } } @@ -25,14 +34,20 @@ class AAPSLoggerProduction : AAPSLogger { override fun error(tag: LTag, message: String) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).error(message) - } } + override fun error(message: String) { + LoggerFactory.getLogger(LTag.CORE.tag).error(message) + } + + override fun error(message: String, throwable: Throwable) { + LoggerFactory.getLogger(LTag.CORE.tag).error(message, throwable) + } + override fun error(tag: LTag, message: String, throwable: Throwable) { if (L.isEnabled(tag.tag)) { LoggerFactory.getLogger(tag.tag).error(message, throwable) - } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt index 6faee1c38a..0ad24d8c09 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunction.kt @@ -14,6 +14,4 @@ interface ProfileFunction { fun getUnits(): String fun getProfile(time: Long): Profile? fun prepareProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long): ProfileSwitch - fun doProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long) - fun doProfileSwitch(duration: Int, percentage: Int, timeShift: Int) } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt index de43cf5519..1e7355e464 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -6,12 +6,11 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.Source -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.sharedPreferences.SP import java.security.spec.InvalidParameterSpecException -import javax.inject.Inject import javax.inject.Singleton +@Singleton class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFunction { override fun getProfileName(): String = @@ -34,7 +33,7 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun } override fun getProfile(time: Long): Profile? = - getProfile(System.currentTimeMillis()) + ProfileFunctions.getInstance().getProfile(System.currentTimeMillis()) override fun getUnits(): String = sp.getString(R.string.key_units, Constants.MGDL) @@ -54,27 +53,4 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun profileSwitch.percentage = percentage return profileSwitch } - - override fun doProfileSwitch(profileStore: ProfileStore, profileName: String, duration: Int, percentage: Int, timeShift: Int, date: Long) { - val profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date) - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch) - if (percentage == 90 && duration == 10) - sp.putBoolean(R.string.key_objectiveuseprofileswitch, true) - } - - override fun doProfileSwitch(duration: Int, percentage: Int, timeShift: Int) { - getProfile()?.let { - val profileSwitch = ProfileSwitch() - profileSwitch.date = System.currentTimeMillis() - profileSwitch.source = Source.USER - profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), customized = false, showRemainingTime = false) - profileSwitch.profileJson = it.data.toString() - profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().activeProfileInterface::class.java.name - profileSwitch.durationInMinutes = duration - profileSwitch.isCPP = percentage != 100 || timeShift != 0 - profileSwitch.timeshift = timeShift - profileSwitch.percentage = percentage - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch) - } - } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java index 126fc6c44d..fc58e29940 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -182,30 +182,4 @@ public class ProfileFunctions implements ProfileFunction { return profileSwitch; } - public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { - ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date); - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); - if (percentage == 90 && duration == 10) - SP.putBoolean(R.string.key_objectiveuseprofileswitch, true); - } - - public void doProfileSwitch(final int duration, final int percentage, final int timeShift) { - ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); - if (profileSwitch != null) { - profileSwitch = new ProfileSwitch(); - profileSwitch.date = System.currentTimeMillis(); - profileSwitch.source = Source.USER; - profileSwitch.profileName = getInstance().getProfileName(System.currentTimeMillis(), false, false); - profileSwitch.profileJson = getInstance().getProfile().getData().toString(); - profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); - profileSwitch.durationInMinutes = duration; - profileSwitch.isCPP = percentage != 100 || timeShift != 0; - profileSwitch.timeshift = timeShift; - profileSwitch.percentage = percentage; - TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); - } else { - log.error("No profile switch existing"); - } - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java index b3741b7271..cb82edf3fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName; import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement; import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.JsonHelper; @@ -33,7 +34,7 @@ public class ActionProfileSwitch extends Action { // Prevent action if active profile is already active // but we don't have a trigger IS_NOT_EQUAL // so check is in the doRun() - ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); + ProfileInterface profileInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface(); if (profileInterface != null) { ProfileStore profileStore = profileInterface.getProfile(); if (profileStore != null) { @@ -62,13 +63,13 @@ public class ActionProfileSwitch extends Action { String activeProfileName = ProfileFunctions.getInstance().getProfileName(); //Check for uninitialized profileName - if ( profileName.equals("")){ + if (profileName.equals("")) { log.error("Selected profile not initialized"); if (callback != null) callback.result(new PumpEnactResult().success(false).comment(R.string.error_field_must_not_be_empty)).run(); return; } - if ( ProfileFunctions.getInstance().getProfile() == null){ + if (ProfileFunctions.getInstance().getProfile() == null) { log.error("ProfileFunctions not initialized"); if (callback != null) callback.result(new PumpEnactResult().success(false).comment(R.string.noprofile)).run(); @@ -90,15 +91,15 @@ public class ActionProfileSwitch extends Action { } ProfileStore profileStore = activeProfile.getProfile(); if (profileStore == null) return; - if(profileStore.getSpecificProfile(profileName) == null) { + if (profileStore.getSpecificProfile(profileName) == null) { if (L.isEnabled(L.AUTOMATION)) - log.error("Selected profile does not exist! - "+ profileName); + log.error("Selected profile does not exist! - " + profileName); if (callback != null) callback.result(new PumpEnactResult().success(false).comment(R.string.notexists)).run(); return; } - ProfileFunctions.getInstance().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); + TreatmentsPlugin.getPlugin().doProfileSwitch(profileStore, profileName, 0, 100, 0, DateUtil.now()); if (callback != null) callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java index 71cbed7173..ba62667335 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java @@ -6,21 +6,21 @@ import com.google.common.base.Optional; import org.json.JSONException; import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.automation.elements.Comparator; import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration; import info.nightscout.androidaps.plugins.general.automation.elements.InputPercent; import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement; import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder; import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerProfilePercent; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.JsonHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ActionProfileSwitchPercent extends Action { private static final Logger log = LoggerFactory.getLogger(ActionProfileSwitchPercent.class); @@ -47,7 +47,7 @@ public class ActionProfileSwitchPercent extends Action { @Override public void doAction(Callback callback) { - ProfileFunctions.getInstance().doProfileSwitch((int) duration.getValue(), (int) pct.getValue(), 0); + TreatmentsPlugin.getPlugin().doProfileSwitch((int) duration.getValue(), (int) pct.getValue(), 0); if (callback != null) callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index 46f58a8d2c..dbdd3c52c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -54,6 +54,7 @@ import javax.inject.Singleton @Singleton class SmsCommunicatorPlugin @Inject constructor( val configBuilderPlugin: ConfigBuilderPlugin, + val treatmentsPlugin: TreatmentsPlugin, val resourceHelper: ResourceHelper, val constraintChecker: ConstraintChecker, val aapsLogger: AAPSLogger @@ -467,7 +468,7 @@ class SmsCommunicatorPlugin @Inject constructor( val finalPercentage = percentage messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) { override fun run() { - ProfileFunctions.getInstance().doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) + treatmentsPlugin.doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0, DateUtil.now()) sendSMS(Sms(receivedSms.phoneNumber, R.string.profileswitchcreated)) } }) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java index a137def1d4..3a4674938f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java @@ -679,8 +679,7 @@ public class ActionStringHandler { } //send profile to pumpe - new NewNSTreatmentDialog(); //init - ProfileFunctions.getInstance().doProfileSwitch(0, percentage, timeshift); + TreatmentsPlugin.getPlugin().doProfileSwitch(0, percentage, timeshift); } private static void generateTempTarget(int duration, double low, double high) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt index 5183007a64..c688e332fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt @@ -6,12 +6,13 @@ import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter -import androidx.fragment.app.Fragment +import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy @@ -21,8 +22,13 @@ import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.close.* import kotlinx.android.synthetic.main.nsprofile_fragment.* import kotlinx.android.synthetic.main.profileviewer_fragment.* +import javax.inject.Inject + +class NSProfileFragment : DaggerFragment() { + + @Inject + lateinit var treatmentsPlugin: TreatmentsPlugin -class NSProfileFragment : Fragment() { private var disposable: CompositeDisposable = CompositeDisposable() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, @@ -42,7 +48,7 @@ class NSProfileFragment : Fragment() { activity?.let { activity -> OKDialog.showConfirmation(activity, MainApp.gs(R.string.nsprofile), MainApp.gs(R.string.activate_profile) + ": " + name + " ?", Runnable { - ProfileFunctions.getInstance().doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) + treatmentsPlugin.doProfileSwitch(store, name, 0, 100, 0, DateUtil.now()) }) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 69589a126f..25d0a0e028 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -7,16 +7,18 @@ import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.jetbrains.annotations.NotNull; import java.util.ArrayList; -import java.util.Date; import java.util.List; +import javax.inject.Inject; +import javax.inject.Singleton; + import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.Iob; @@ -26,8 +28,10 @@ import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileIntervals; +import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventReloadProfileSwitchData; @@ -40,12 +44,12 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; @@ -59,26 +63,33 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import info.nightscout.androidaps.utils.resources.ResourceHelper; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; -/** - * Created by mike on 05.08.2016. - */ +@Singleton public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { - private Logger log = LoggerFactory.getLogger(L.DATATREATMENTS); + private final AAPSLogger aapsLogger; + private final MainApp mainApp; + private final ResourceHelper resourceHelper; + private final ProfileFunction profileFunction; + private final ConfigBuilderPlugin configBuilderPlugin; private CompositeDisposable disposable = new CompositeDisposable(); private static TreatmentsPlugin treatmentsPlugin; + /** + * @deprecated Use dagger to get an instance + */ + @Deprecated public static TreatmentsPlugin getPlugin() { if (treatmentsPlugin == null) - treatmentsPlugin = new TreatmentsPlugin(); + throw new IllegalStateException("Accessing TreatmentsPlugin before first instantiation"); return treatmentsPlugin; } - private TreatmentService service; + protected TreatmentService service; private IobTotal lastTreatmentCalculation; private IobTotal lastTempBasalsCalculation; @@ -89,7 +100,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final Intervals tempTargets = new OverlappingIntervals<>(); private final ProfileIntervals profiles = new ProfileIntervals<>(); - public TreatmentsPlugin() { + @Inject + public TreatmentsPlugin(AAPSLogger aapsLogger, + ResourceHelper resourceHelper, + MainApp mainApp, + ConfigBuilderPlugin configBuilderPlugin, + ProfileFunction profileFunction + ) { super(new PluginDescription() .mainType(PluginType.TREATMENT) .fragmentClass(TreatmentsFragment.class.getName()) @@ -98,19 +115,24 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .alwaysEnabled(true) .description(R.string.description_treatments) ); - this.service = new TreatmentService(); + this.aapsLogger = aapsLogger; + this.resourceHelper = resourceHelper; + this.mainApp = mainApp; + this.configBuilderPlugin = configBuilderPlugin; + this.profileFunction = profileFunction; + treatmentsPlugin = this; } @Override protected void onStart() { + this.service = new TreatmentService(); initializeData(range()); super.onStart(); disposable.add(RxBus.INSTANCE .toObservable(EventReloadTreatmentData.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("EventReloadTreatmentData"); + aapsLogger.debug(LTag.DATATREATMENTS, "EventReloadTreatmentData"); initializeTreatmentData(range()); initializeExtendedBolusData(range()); updateTotalIOBTreatments(); @@ -134,8 +156,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface .toObservable(EventReloadTempBasalData.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("EventReloadTempBasalData"); + aapsLogger.debug(LTag.DATATREATMENTS, "EventReloadTempBasalData"); initializeTempBasalData(range()); updateTotalIOBTempBasals(); }, @@ -155,9 +176,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private long range() { double dia = Constants.defaultDIA; - if (ConfigBuilderPlugin.getPlugin() != null && ProfileFunctions.getInstance().getProfile() != null) - dia = ProfileFunctions.getInstance().getProfile().getDia(); - return (long) (60 * 60 * 1000L * (24 + dia)); + if (profileFunction.getProfile() != null) + dia = profileFunction.getProfile().getDia(); + return (long) (60 * 60 * 1000L * (24 + dia)); } public void initializeData(long range) { @@ -169,8 +190,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTreatmentData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeTreatmentData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeTreatmentData"); synchronized (treatments) { treatments.clear(); treatments.addAll(getService().getTreatmentDataFromTime(DateUtil.now() - range, false)); @@ -178,8 +198,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTempBasalData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeTempBasalData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeTempBasalData"); synchronized (tempBasals) { tempBasals.reset().add(MainApp.getDbHelper().getTemporaryBasalsDataFromTime(DateUtil.now() - range, false)); } @@ -187,8 +206,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeExtendedBolusData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeExtendedBolusData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeExtendedBolusData"); synchronized (extendedBoluses) { extendedBoluses.reset().add(MainApp.getDbHelper().getExtendedBolusDataFromTime(DateUtil.now() - range, false)); } @@ -196,16 +214,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTempTargetData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeTempTargetData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeTempTargetData"); synchronized (tempTargets) { tempTargets.reset().add(MainApp.getDbHelper().getTemptargetsDataFromTime(DateUtil.now() - range, false)); } } private void initializeProfileSwitchData(long range) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("initializeProfileSwitchData"); + aapsLogger.debug(LTag.DATATREATMENTS, "initializeProfileSwitchData"); synchronized (profiles) { profiles.reset().add(MainApp.getDbHelper().getProfileSwitchData(DateUtil.now() - range, false)); } @@ -220,22 +236,22 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTreatments(long time) { IobTotal total = new IobTotal(time); - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = profileFunction.getProfile(); if (profile == null) return total; - InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); + InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); if (insulinInterface == null) return total; - PumpInterface pumpInterface = ConfigBuilderPlugin.getPlugin().getActivePump(); + PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); if (pumpInterface == null) return total; double dia = profile.getDia(); synchronized (treatments) { - for (Integer pos = 0; pos < treatments.size(); pos++) { + for (int pos = 0; pos < treatments.size(); pos++) { Treatment t = treatments.get(pos); if (!t.isValid) continue; if (t.date > time) continue; @@ -276,7 +292,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public MealData getMealData() { MealData result = new MealData(); - Profile profile = ProfileFunctions.getInstance().getProfile(); + Profile profile = profileFunction.getProfile(); if (profile == null) return result; long now = System.currentTimeMillis(); @@ -344,17 +360,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface long time = System.currentTimeMillis(); synchronized (treatments) { - if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: AllTreatmentsInDb: {}", MedtronicUtil.getGsonInstanceCore().toJson(treatments)); + aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + MedtronicUtil.getGsonInstanceCore().toJson(treatments)); for (Treatment t : treatments) { if (t.date <= time && t.date >= fromTimestamp) in5minback.add(t); } - - if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={}", fromTimestamp, MedtronicUtil.getGsonInstanceCore().toJson(in5minback)); - + aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + MedtronicUtil.getGsonInstanceCore().toJson(in5minback)); return in5minback; } } @@ -364,7 +376,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public List getTreatments5MinBackFromHistory(long time) { List in5minback = new ArrayList<>(); synchronized (treatments) { - for (Integer pos = 0; pos < treatments.size(); pos++) { + for (int pos = 0; pos < treatments.size(); pos++) { Treatment t = treatments.get(pos); if (!t.isValid) continue; @@ -383,12 +395,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface for (Treatment t : treatments) { if (!t.isValid) continue; - if (t.date > last && t.insulin > 0 && t.isValid && t.date <= now) + if (t.date > last && t.insulin > 0 && t.date <= now) last = t.date; } } - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Last bolus time: " + new Date(last).toLocaleString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Last bolus time: " + DateUtil.dateAndTimeString(last)); return last; } @@ -399,12 +410,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface for (Treatment t : treatments) { if (!t.isValid) continue; - if (t.date > last && t.insulin > 0 && t.isValid && t.date <= now && isSMB == t.isSMB) + if (t.date > last && t.insulin > 0 && t.date <= now && isSMB == t.isSMB) last = t.date; } } - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Last manual bolus time: " + new Date(last).toLocaleString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Last manual bolus time: " + DateUtil.dateAndTimeString(last)); return last; } @@ -443,16 +453,20 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTempBasals(long time, boolean truncate, long truncateTime) { IobTotal total = new IobTotal(time); - InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); + InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); if (insulinInterface == null) return total; + PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + if (pumpInterface == null) + return total; + synchronized (tempBasals) { for (Integer pos = 0; pos < tempBasals.size(); pos++) { TemporaryBasal t = tempBasals.get(pos); if (t.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(t.date); + Profile profile = profileFunction.getProfile(t.date); if (profile == null) continue; if (truncate && t.end() > truncateTime) { TemporaryBasal dummyTemp = new TemporaryBasal(); @@ -466,14 +480,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface total.plus(calc); } } - if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { + if (pumpInterface.isFakingTempsByExtendedBoluses()) { IobTotal totalExt = new IobTotal(time); synchronized (extendedBoluses) { - for (Integer pos = 0; pos < extendedBoluses.size(); pos++) { + for (int pos = 0; pos < extendedBoluses.size(); pos++) { ExtendedBolus e = extendedBoluses.get(pos); if (e.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(e.date); + Profile profile = profileFunction.getProfile(e.date); if (profile == null) continue; if (truncate && e.end() > truncateTime) { ExtendedBolus dummyExt = new ExtendedBolus(); @@ -499,16 +513,20 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTempBasals(long time, long truncateTime, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) { IobTotal total = new IobTotal(time); - InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin(); + InsulinInterface insulinInterface = configBuilderPlugin.getActiveInsulin(); if (insulinInterface == null) return total; + PumpInterface pumpInterface = configBuilderPlugin.getActivePump(); + if (pumpInterface == null) + return total; + synchronized (tempBasals) { for (int pos = 0; pos < tempBasals.size(); pos++) { TemporaryBasal t = tempBasals.get(pos); if (t.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(t.date); + Profile profile = profileFunction.getProfile(t.date); if (profile == null) continue; if (t.end() > truncateTime) { TemporaryBasal dummyTemp = new TemporaryBasal(); @@ -522,14 +540,14 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface total.plus(calc); } } - if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) { + if (pumpInterface.isFakingTempsByExtendedBoluses()) { IobTotal totalExt = new IobTotal(time); synchronized (extendedBoluses) { for (int pos = 0; pos < extendedBoluses.size(); pos++) { ExtendedBolus e = extendedBoluses.get(pos); if (e.date > time) continue; IobTotal calc; - Profile profile = ProfileFunctions.getInstance().getProfile(e.date); + Profile profile = profileFunction.getProfile(e.date); if (profile == null) continue; if (e.end() > truncateTime) { ExtendedBolus dummyExt = new ExtendedBolus(); @@ -564,7 +582,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (tb != null) return tb; ExtendedBolus eb = getExtendedBolusFromHistory(time); - if (eb != null && ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) + if (eb != null && configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) return new TemporaryBasal(eb); return null; } @@ -582,11 +600,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(extendedBolus); if (newRecordCreated) { if (extendedBolus.durationInMinutes == 0) { - if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) + if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); else NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); - } else if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) + } else if (configBuilderPlugin.getActivePump().isFakingTempsByExtendedBoluses()) NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); else NSUpload.uploadExtendedBolus(extendedBolus); @@ -628,8 +646,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) { boolean medtronicPump = MedtronicUtil.isMedtronicPump(); - if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={}", medtronicPump); + aapsLogger.debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={} " + medtronicPump); Treatment treatment = new Treatment(); treatment.date = detailedBolusInfo.date; @@ -640,13 +657,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface treatment.isSMB = detailedBolusInfo.isSMB; if (detailedBolusInfo.carbTime == 0) treatment.carbs = detailedBolusInfo.carbs; - treatment.source = detailedBolusInfo.source; treatment.mealBolus = treatment.carbs > 0; treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null; TreatmentService.UpdateReturn creatOrUpdateResult; - if (medtronicPump && MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: addToHistoryTreatment::treatment={}", treatment); + aapsLogger.debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: addToHistoryTreatment::treatment={} " + treatment); if (!medtronicPump) creatOrUpdateResult = getService().createOrUpdate(treatment); @@ -662,10 +677,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface carbsTreatment.pumpId = detailedBolusInfo.pumpId; // but this should never happen carbsTreatment.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records carbsTreatment.carbs = detailedBolusInfo.carbs; - carbsTreatment.source = detailedBolusInfo.source; - if (medtronicPump && MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}", carbsTreatment); + aapsLogger.debug(medtronicPump && MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}" + carbsTreatment); if (!medtronicPump) getService().createOrUpdate(carbsTreatment); @@ -677,16 +690,16 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface NSUpload.uploadTreatmentRecord(detailedBolusInfo); if (!allowUpdate && !creatOrUpdateResult.success) { - log.error("Treatment could not be added to DB", new Exception()); + aapsLogger.error("Treatment could not be added to DB", new Exception()); - String status = String.format(MainApp.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date)); + String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date)); - Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); + Intent i = new Intent(mainApp, ErrorHelperActivity.class); i.putExtra("soundid", R.raw.error); - i.putExtra("title", MainApp.gs(R.string.error_adding_treatment_title)); + i.putExtra("title", resourceHelper.gs(R.string.error_adding_treatment_title)); i.putExtra("status", status); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); + mainApp.startActivity(i); Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "TreatmentClash"); @@ -769,5 +782,32 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface NSUpload.uploadProfileSwitch(profileSwitch); } + @Override + public void doProfileSwitch(@NotNull final ProfileStore profileStore, @NotNull final String profileName, final int duration, final int percentage, final int timeShift, final long date) { + ProfileSwitch profileSwitch = profileFunction.prepareProfileSwitch(profileStore, profileName, duration, percentage, timeShift, date); + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); + if (percentage == 90 && duration == 10) + SP.putBoolean(R.string.key_objectiveuseprofileswitch, true); + } + + @Override + public void doProfileSwitch(final int duration, final int percentage, final int timeShift) { + ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis()); + if (profileSwitch != null) { + profileSwitch = new ProfileSwitch(); + profileSwitch.date = System.currentTimeMillis(); + profileSwitch.source = Source.USER; + profileSwitch.profileName = profileFunction.getProfileName(System.currentTimeMillis(), false, false); + profileSwitch.profileJson = profileFunction.getProfile().getData().toString(); + profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName(); + profileSwitch.durationInMinutes = duration; + profileSwitch.isCPP = percentage != 100 || timeShift != 0; + profileSwitch.timeshift = timeShift; + profileSwitch.percentage = percentage; + TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); + } else { + aapsLogger.error(LTag.PROFILE, "No profile switch exists"); + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt index 0210247eb3..e86e78c5af 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/TddCalculator.kt @@ -5,13 +5,26 @@ import android.util.LongSparseArray import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.TDD -import info.nightscout.androidaps.logging.L -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import org.slf4j.LoggerFactory +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject -object TddCalculator : TreatmentsPlugin() { - private val log = LoggerFactory.getLogger(L.DATATREATMENTS) +class TddCalculator @Inject constructor( + val aapsLogger: AAPSLogger, + val resourceHelper: ResourceHelper, + val mainApp: MainApp, + val configBuilderPlugin: ConfigBuilderPlugin, + val profileFunction: ProfileFunction +) : TreatmentsPlugin(aapsLogger, resourceHelper, mainApp, configBuilderPlugin, profileFunction) { + + init { + service = TreatmentService() // plugin is not started + } fun calculate(days: Long): LongSparseArray { val range = T.days(days + 1).msecs() @@ -33,7 +46,7 @@ object TddCalculator : TreatmentsPlugin() { val midnight = MidnightTime.calc(t) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) val tbr = getTempBasalFromHistory(t) - val profile = ProfileFunctions.getInstance().getProfile(t) ?: continue + val profile = profileFunction.getProfile(t) ?: continue val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t) tdd.basal += absoluteRate / 60.0 * 5.0 result.put(midnight, tdd) @@ -42,11 +55,11 @@ object TddCalculator : TreatmentsPlugin() { val tdd = result.valueAt(i) tdd.total = tdd.bolus + tdd.basal } - log.debug(result.toString()) + aapsLogger.debug(LTag.CORE, result.toString()) return result } - fun averageTDD(tdds: LongSparseArray): TDD { + private fun averageTDD(tdds: LongSparseArray): TDD { val totalTdd = TDD() for (i in 0 until tdds.size()) { val tdd = tdds.valueAt(i) @@ -71,7 +84,7 @@ object TddCalculator : TreatmentsPlugin() { ) } - fun toText(tdds: LongSparseArray): String { + private fun toText(tdds: LongSparseArray): String { var t = "" for (i in 0 until tdds.size()) { t += "${tdds.valueAt(i).toText()}
" From f0fcd21bb9db6c53476d5e11eaeb245fc7907635 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sun, 29 Dec 2019 00:07:30 +0100 Subject: [PATCH 050/316] TreatmentsFragment -> dagger --- .../dependencyInjection/FragmentsModule.kt | 50 +++---- .../treatments/TreatmentsFragment.java | 135 ------------------ .../plugins/treatments/TreatmentsFragment.kt | 107 ++++++++++++++ .../plugins/treatments/TreatmentsPlugin.java | 3 + 4 files changed, 130 insertions(+), 165 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index 7ac458589a..718b299979 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -9,40 +9,30 @@ import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAFragment import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment +import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment @Module abstract class FragmentsModule { - @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment - @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment - @ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment - @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment - @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment - @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment - @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog - @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog - @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog - @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog - @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment - @ContributesAndroidInjector - abstract fun contributesInsulinDialog(): InsulinDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment - @ContributesAndroidInjector - abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog - - @ContributesAndroidInjector - abstract fun contributesProfileViewerDialog(): ProfileViewerDialog - - @ContributesAndroidInjector - abstract fun contributesTempBasalDialog(): TempBasalDialog - - @ContributesAndroidInjector - abstract fun contributesTempTargetDialog(): TempTargetDialog - - @ContributesAndroidInjector - abstract fun contributesTreatmentDialog(): TreatmentDialog - - @ContributesAndroidInjector - abstract fun contributesWizardDialog(): WizardDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog + @Suppress("unused") @ContributesAndroidInjector abstract fun contributesWizardDialog(): WizardDialog } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java deleted file mode 100644 index 731042c237..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java +++ /dev/null @@ -1,135 +0,0 @@ -package info.nightscout.androidaps.plugins.treatments; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment; -import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment; -import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsExtendedBolusesFragment; -import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment; -import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment; -import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment; -import info.nightscout.androidaps.utils.FabricPrivacy; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; - -public class TreatmentsFragment extends Fragment implements View.OnClickListener { - private CompositeDisposable disposable = new CompositeDisposable(); - - TextView treatmentsTab; - TextView extendedBolusesTab; - TextView tempBasalsTab; - TextView tempTargetTab; - TextView profileSwitchTab; - TextView careportalTab; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.treatments_fragment, container, false); - - treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments); - extendedBolusesTab = (TextView) view.findViewById(R.id.treatments_extendedboluses); - tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals); - tempTargetTab = (TextView) view.findViewById(R.id.treatments_temptargets); - profileSwitchTab = (TextView) view.findViewById(R.id.treatments_profileswitches); - careportalTab = (TextView) view.findViewById(R.id.treatments_careportal); - treatmentsTab.setOnClickListener(this); - extendedBolusesTab.setOnClickListener(this); - tempBasalsTab.setOnClickListener(this); - tempTargetTab.setOnClickListener(this); - profileSwitchTab.setOnClickListener(this); - careportalTab.setOnClickListener(this); - - setFragment(new TreatmentsBolusFragment()); - setBackgroundColorOnSelected(treatmentsTab); - - return view; - } - - @Override - public synchronized void onResume() { - super.onResume(); - disposable.add(RxBus.INSTANCE - .toObservable(EventExtendedBolusChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> updateGui(), FabricPrivacy::logException) - ); - updateGui(); - } - - @Override - public synchronized void onPause() { - super.onPause(); - disposable.clear(); - } - - @Override - public void onClick(View v) { - - switch (v.getId()) { - case R.id.treatments_treatments: - setFragment(new TreatmentsBolusFragment()); - setBackgroundColorOnSelected(treatmentsTab); - break; - case R.id.treatments_extendedboluses: - setFragment(new TreatmentsExtendedBolusesFragment()); - setBackgroundColorOnSelected(extendedBolusesTab); - break; - case R.id.treatments_tempbasals: - setFragment(new TreatmentsTemporaryBasalsFragment()); - setBackgroundColorOnSelected(tempBasalsTab); - break; - case R.id.treatments_temptargets: - setFragment(new TreatmentsTempTargetFragment()); - setBackgroundColorOnSelected(tempTargetTab); - break; - case R.id.treatments_profileswitches: - setFragment(new TreatmentsProfileSwitchFragment()); - setBackgroundColorOnSelected(profileSwitchTab); - break; - case R.id.treatments_careportal: - setFragment(new TreatmentsCareportalFragment()); - setBackgroundColorOnSelected(careportalTab); - break; - } - } - - private void setFragment(Fragment selectedFragment) { - FragmentTransaction ft = getChildFragmentManager().beginTransaction(); - ft.replace(R.id.treatments_fragment_container, selectedFragment); // f2_container is your FrameLayout container - ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); - ft.addToBackStack(null); - ft.commit(); - } - - private void setBackgroundColorOnSelected(TextView selected) { - treatmentsTab.setBackgroundColor(MainApp.gc(R.color.defaultbackground)); - extendedBolusesTab.setBackgroundColor(MainApp.gc(R.color.defaultbackground)); - tempBasalsTab.setBackgroundColor(MainApp.gc(R.color.defaultbackground)); - tempTargetTab.setBackgroundColor(MainApp.gc(R.color.defaultbackground)); - profileSwitchTab.setBackgroundColor(MainApp.gc(R.color.defaultbackground)); - careportalTab.setBackgroundColor(MainApp.gc(R.color.defaultbackground)); - selected.setBackgroundColor(MainApp.gc(R.color.tabBgColorSelected)); - } - - private void updateGui() { - if (ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().isExtendedBolusCapable - || TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory().size() > 0) { - extendedBolusesTab.setVisibility(View.VISIBLE); - } else { - extendedBolusesTab.setVisibility(View.GONE); - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt new file mode 100644 index 0000000000..268b1e1985 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.kt @@ -0,0 +1,107 @@ +package info.nightscout.androidaps.plugins.treatments + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentTransaction +import dagger.android.support.DaggerFragment +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventExtendedBolusChange +import info.nightscout.androidaps.plugins.bus.RxBus.toObservable +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin +import info.nightscout.androidaps.plugins.treatments.fragments.* +import info.nightscout.androidaps.utils.FabricPrivacy +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import kotlinx.android.synthetic.main.treatments_fragment.* +import javax.inject.Inject + +class TreatmentsFragment : DaggerFragment() { + private val disposable = CompositeDisposable() + + @Inject + lateinit var configBuilderPlugin: ConfigBuilderPlugin + @Inject + lateinit var treatmentsPlugin: TreatmentsPlugin + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.treatments_fragment, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + treatments_treatments.setOnClickListener { + setFragment(TreatmentsBolusFragment()) + setBackgroundColorOnSelected(it) + } + treatments_extendedboluses.setOnClickListener { + setFragment(TreatmentsExtendedBolusesFragment()) + setBackgroundColorOnSelected(it) + } + treatments_tempbasals.setOnClickListener { + setFragment(TreatmentsTemporaryBasalsFragment()) + setBackgroundColorOnSelected(it) + } + treatments_temptargets.setOnClickListener { + setFragment(TreatmentsTempTargetFragment()) + setBackgroundColorOnSelected(it) + } + treatments_profileswitches.setOnClickListener { + setFragment(TreatmentsProfileSwitchFragment()) + setBackgroundColorOnSelected(it) + } + treatments_careportal.setOnClickListener { + setFragment(TreatmentsCareportalFragment()) + setBackgroundColorOnSelected(it) + } + setFragment(TreatmentsBolusFragment()) + setBackgroundColorOnSelected(treatments_treatments) + } + + @Synchronized + override fun onResume() { + super.onResume() + disposable.add(toObservable(EventExtendedBolusChange::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGui() }) { FabricPrivacy.logException(it) } + ) + updateGui() + } + + @Synchronized + override fun onPause() { + super.onPause() + disposable.clear() + } + + private fun setFragment(selectedFragment: Fragment) { + val ft = childFragmentManager.beginTransaction() + ft.replace(R.id.treatments_fragment_container, selectedFragment) // f2_container is your FrameLayout container + ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) + ft.addToBackStack(null) + ft.commit() + } + + private fun setBackgroundColorOnSelected(selected: View) { + treatments_treatments.setBackgroundColor(MainApp.gc(R.color.defaultbackground)) + treatments_extendedboluses.setBackgroundColor(MainApp.gc(R.color.defaultbackground)) + treatments_tempbasals.setBackgroundColor(MainApp.gc(R.color.defaultbackground)) + treatments_temptargets.setBackgroundColor(MainApp.gc(R.color.defaultbackground)) + treatments_profileswitches.setBackgroundColor(MainApp.gc(R.color.defaultbackground)) + treatments_careportal.setBackgroundColor(MainApp.gc(R.color.defaultbackground)) + selected.setBackgroundColor(MainApp.gc(R.color.tabBgColorSelected)) + } + + private fun updateGui() { + if (configBuilderPlugin.activePump?.pumpDescription?.isExtendedBolusCapable == true + || treatmentsPlugin.extendedBolusesFromHistory.size() > 0) + treatments_extendedboluses?.visibility = View.VISIBLE + else + treatments_extendedboluses?.visibility = View.GONE + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 25d0a0e028..2334476bfb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.treatments; import android.content.Intent; import android.os.Bundle; +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; @@ -613,6 +614,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } @Override + @NonNull public Intervals getExtendedBolusesFromHistory() { synchronized (extendedBoluses) { return new NonOverlappingIntervals<>(extendedBoluses); @@ -620,6 +622,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } @Override + @NonNull public NonOverlappingIntervals getTemporaryBasalsFromHistory() { synchronized (tempBasals) { return new NonOverlappingIntervals<>(tempBasals); From fef74726b234e3650fffb9952261206f1ded17ca Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 30 Dec 2019 00:53:44 +0100 Subject: [PATCH 051/316] daggerize --- .idea/codeStyles/Project.xml | 6 + .../nightscout/androidaps/MainActivity.java | 6 +- .../info/nightscout/androidaps/MainApp.java | 45 +- .../activities/ErrorHelperActivity.kt | 6 +- .../activities/HistoryBrowseActivity.java | 4 +- .../activities/MyPreferenceFragment.java | 48 +- .../activities/PreferencesActivity.java | 6 +- .../androidaps/activities/StatsActivity.kt | 9 +- .../androidaps/activities/SurveyActivity.kt | 20 +- .../activities/TDDStatsActivity.java | 4 +- .../nightscout/androidaps/data/Profile.java | 6 +- .../androidaps/db/DatabaseHelper.java | 34 +- .../androidaps/db/ProfileSwitch.java | 4 +- .../dependencyInjection/ActivitiesModule.kt | 1 + .../dependencyInjection/AppComponent.kt | 14 +- .../dependencyInjection/AppModule.kt | 42 +- .../dependencyInjection/FragmentsModule.kt | 81 ++- .../dependencyInjection/ReceiversModule.kt | 12 + .../dependencyInjection/ServicesModule.kt | 12 + .../androidaps/dialogs/BolusProgressDialog.kt | 56 +- .../androidaps/dialogs/CarbsDialog.kt | 87 +-- .../androidaps/dialogs/CareDialog.kt | 11 +- .../dialogs/DialogFragmentWithDate.kt | 13 +- .../androidaps/dialogs/ErrorDialog.kt | 23 +- .../androidaps/dialogs/ExtendedBolusDialog.kt | 17 +- .../androidaps/dialogs/FillDialog.kt | 27 +- .../androidaps/dialogs/InsulinDialog.kt | 40 +- .../androidaps/dialogs/TempTargetDialog.kt | 21 +- .../androidaps/dialogs/WizardDialog.kt | 46 +- .../androidaps/interfaces/PluginBase.kt | 15 +- .../androidaps/interfaces/PumpInterface.java | 3 + .../androidaps/logging/AAPSLogger.kt | 1 + .../androidaps/logging/AAPSLoggerDebug.kt | 4 + .../logging/AAPSLoggerProduction.kt | 6 + .../plugins/aps/loop/LoopFragment.kt | 4 +- .../plugins/aps/loop/LoopPlugin.java | 29 +- .../aps/openAPSAMA/OpenAPSAMAFragment.kt | 17 +- .../aps/openAPSAMA/OpenAPSAMAPlugin.java | 12 +- .../aps/openAPSMA/OpenAPSMAFragment.kt | 12 +- .../aps/openAPSMA/OpenAPSMAPlugin.java | 10 +- .../aps/openAPSSMB/OpenAPSSMBFragment.kt | 16 +- .../aps/openAPSSMB/OpenAPSSMBPlugin.java | 12 +- .../androidaps/plugins/bus/RxBus.kt | 9 +- .../androidaps/plugins/bus/RxBusWrapper.kt | 21 + .../configBuilder/ConfigBuilderFragment.kt | 26 +- .../configBuilder/ConfigBuilderPlugin.java | 72 +-- .../plugins/configBuilder/PluginViewHolder.kt | 2 +- .../ProfileFunctionImplementation.kt | 8 +- .../configBuilder/ProfileFunctions.java | 5 +- .../dstHelper/DstHelperPlugin.java | 3 +- .../objectives/ObjectivesFragment.kt | 107 ++-- .../objectives/ObjectivesPlugin.kt | 115 ++-- .../activities/ObjectivesExamDialog.kt | 27 +- .../objectives/dialogs/NtpProgressDialog.kt | 65 ++- .../objectives/objectives/Objective0.java | 25 +- .../objectives/objectives/Objective1.java | 24 +- .../objectives/objectives/Objective2.java | 2 + .../objectives/objectives/Objective3.java | 22 +- .../objectives/objectives/Objective5.java | 4 +- .../objectives/objectives/Objective6.java | 7 +- .../constraints/safety/SafetyPlugin.java | 2 +- .../SignatureVerifierPlugin.java | 3 +- .../storage/StorageConstraintPlugin.java | 5 +- .../versionChecker/VersionCheckerPlugin.kt | 34 +- .../versionChecker/VersionCheckerUtils.kt | 2 +- .../general/actions/ActionsFragment.kt | 121 +++-- .../plugins/general/actions/ActionsPlugin.kt | 5 +- .../general/automation/AutomationFragment.kt | 55 +- .../general/automation/AutomationPlugin.kt | 206 +++---- .../general/automation/EventListAdapter.java | 10 +- .../automation/actions/ActionLoopDisable.java | 2 +- .../automation/actions/ActionLoopEnable.java | 2 +- .../automation/actions/ActionLoopResume.java | 2 +- .../automation/actions/ActionLoopSuspend.java | 2 +- .../actions/ActionNotification.java | 4 +- .../automation/dialogs/ActionListAdapter.kt | 5 +- .../automation/dialogs/ChooseActionDialog.kt | 11 +- .../automation/dialogs/ChooseTriggerDialog.kt | 4 +- .../automation/dialogs/EditActionDialog.kt | 7 +- .../automation/dialogs/EditEventDialog.kt | 99 ++-- .../automation/dialogs/EditTriggerDialog.kt | 8 +- .../careportal/CareportalFragment.java | 2 +- .../general/careportal/CareportalPlugin.java | 36 -- .../general/careportal/CareportalPlugin.kt | 25 + .../plugins/general/food/FoodFragment.java | 2 +- .../plugins/general/food/FoodPlugin.java | 1 + .../plugins/general/food/FoodService.java | 4 +- .../maintenance/ImportExportPrefs.java | 2 +- .../maintenance/MaintenancePlugin.java | 1 + .../general/nsclient/NSClientFragment.java | 6 +- .../general/nsclient/NSClientPlugin.java | 21 +- .../nsclient/NsClientReceiverDelegate.java | 10 +- .../general/nsclient/acks/NSAddAck.java | 4 +- .../general/nsclient/acks/NSAuthAck.java | 2 +- .../general/nsclient/acks/NSUpdateAck.java | 2 +- .../nsclient/data/NSSettingsStatus.java | 10 +- .../nsclient/services/NSClientService.java | 132 ++--- .../general/overview/OverviewFragment.java | 38 +- .../general/overview/OverviewPlugin.kt | 78 +-- .../activities/QuickWizardListActivity.kt | 29 +- .../overview/dialogs/EditQuickWizardDialog.kt | 23 +- .../DismissNotificationService.java | 2 +- .../NotificationRecyclerViewAdapter.java | 15 +- .../notifications/NotificationStore.java | 188 ------- .../notifications/NotificationStore.kt | 172 ++++++ .../persistentNotification/DummyService.java | 2 +- .../PersistentNotificationPlugin.java | 17 +- .../SmsCommunicatorFragment.kt | 24 +- .../smsCommunicator/SmsCommunicatorPlugin.kt | 71 ++- .../general/tidepool/TidepoolFragment.kt | 47 +- .../general/tidepool/TidepoolPlugin.kt | 183 ++++--- .../general/tidepool/comm/TidepoolCallback.kt | 4 +- .../general/tidepool/comm/TidepoolUploader.kt | 186 +++---- .../general/tidepool/comm/UploadChunk.kt | 59 +- .../tidepool/elements/ProfileElement.kt | 2 +- .../messages/OpenDatasetRequestMessage.kt | 6 +- .../general/wear/ActionStringHandler.java | 2 +- .../plugins/general/wear/WearPlugin.java | 23 +- .../xdripStatusline/StatusLinePlugin.kt | 49 +- .../plugins/insulin/InsulinOrefBasePlugin.kt | 19 +- .../insulin/InsulinOrefFreePeakPlugin.kt | 6 +- .../insulin/InsulinOrefRapidActingPlugin.kt | 14 +- .../InsulinOrefUltraRapidActingPlugin.kt | 11 +- .../IobCobCalculatorPlugin.java | 13 +- .../iobCobCalculator/IobCobOref1Thread.java | 10 +- .../iob/iobCobCalculator/IobCobThread.java | 10 +- .../profile/local/LocalProfileFragment.kt | 132 ++--- .../profile/local/LocalProfilePlugin.kt | 166 +++--- .../plugins/profile/ns/NSProfileFragment.kt | 21 +- .../plugins/profile/ns/NSProfilePlugin.java | 6 +- .../plugins/pump/combo/ComboFragment.java | 4 +- .../plugins/pump/combo/ComboPlugin.java | 69 +-- .../pump/common/PumpPluginAbstract.java | 13 +- .../dialog/RileyLinkBLEScanActivity.java | 2 +- .../common/hw/rileylink/RileyLinkUtil.java | 2 +- .../ResetRileyLinkConfigurationTask.java | 4 +- .../service/tasks/WakeAndTuneTask.java | 4 +- .../pump/danaR/AbstractDanaRPlugin.java | 14 +- .../plugins/pump/danaR/DanaRFragment.kt | 85 +-- .../plugins/pump/danaR/DanaRPlugin.java | 171 +++--- .../danaR/activities/DanaRHistoryActivity.kt | 60 +- .../danaR/activities/DanaRNSHistorySync.java | 4 +- .../activities/DanaRUserOptionsActivity.kt | 64 ++- .../pump/danaR/comm/MsgBolusProgress.java | 2 +- .../plugins/pump/danaR/comm/MsgBolusStop.java | 2 +- .../plugins/pump/danaR/comm/MsgError.java | 2 +- .../pump/danaR/comm/MsgHistoryAll.java | 2 +- .../danaR/comm/MsgInitConnStatusBolus.java | 4 +- .../danaR/comm/MsgInitConnStatusOption.java | 4 +- .../danaR/comm/MsgInitConnStatusTime.java | 4 +- .../pump/danaR/comm/MsgSetBasalProfile.java | 4 +- .../danaR/comm/MsgSetSingleBasalProfile.java | 4 +- .../pump/danaR/comm/MsgSettingMeal.java | 8 +- .../AbstractDanaRExecutionService.java | 6 +- .../danaR/services/DanaRExecutionService.java | 56 +- .../pump/danaRKorean/DanaRKoreanPlugin.java | 172 +++--- .../comm/MsgInitConnStatusBasic_k.java | 8 +- .../comm/MsgInitConnStatusBolus_k.java | 4 +- .../comm/MsgInitConnStatusTime_k.java | 4 +- .../services/DanaRKoreanExecutionService.java | 54 +- .../plugins/pump/danaRS/DanaRSPlugin.java | 283 +++++----- .../danaRS/activities/BLEScanActivity.java | 2 +- .../DanaRS_Packet_APS_History_Events.java | 2 +- .../DanaRS_Packet_Basal_Get_Basal_Rate.java | 4 +- .../DanaRS_Packet_Bolus_Get_Bolus_Option.java | 4 +- ...naRS_Packet_Bolus_Set_Step_Bolus_Stop.java | 2 +- .../DanaRS_Packet_General_Get_Pump_Check.java | 2 +- .../danaRS/comm/DanaRS_Packet_History_.java | 2 +- ...anaRS_Packet_Notify_Delivery_Complete.java | 2 +- ...S_Packet_Notify_Delivery_Rate_Display.java | 2 +- .../danaRS/dialogs/PairingProgressDialog.java | 2 +- .../plugins/pump/danaRS/services/BLEComm.java | 18 +- .../pump/danaRS/services/DanaRSService.java | 76 +-- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 159 +++--- .../pump/danaRv2/comm/MsgCheckValue_v2.java | 8 +- .../danaRv2/comm/MsgHistoryEvents_v2.java | 2 +- .../services/DanaRv2ExecutionService.java | 78 +-- .../pump/insight/LocalInsightFragment.java | 2 +- .../pump/insight/LocalInsightPlugin.java | 37 +- .../plugins/pump/mdi/MDIPlugin.java | 1 + .../pump/medtronic/MedtronicFragment.kt | 182 ++++--- .../pump/medtronic/MedtronicPumpPlugin.java | 12 +- .../medtronic/comm/ui/MedtronicUITask.java | 6 +- .../pump/medtronic/util/MedtronicUtil.java | 10 +- .../pump/virtual/VirtualPumpFragment.kt | 65 +-- .../pump/virtual/VirtualPumpPlugin.java | 512 ------------------ .../plugins/pump/virtual/VirtualPumpPlugin.kt | 410 ++++++++++++++ .../sensitivity/SensitivityAAPSPlugin.java | 1 + .../sensitivity/SensitivityOref0Plugin.java | 1 + .../sensitivity/SensitivityOref1Plugin.java | 1 + .../SensitivityWeightedAveragePlugin.java | 1 + .../plugins/source/BGSourceFragment.java | 18 +- .../plugins/source/SourceEversensePlugin.java | 1 + .../plugins/source/SourceGlimpPlugin.java | 1 + .../plugins/source/SourceMM640gPlugin.java | 1 + .../plugins/source/SourceNSClientPlugin.java | 1 + .../plugins/source/SourcePoctechPlugin.java | 1 + .../plugins/source/SourceTomatoPlugin.java | 1 + .../plugins/source/SourceXdripPlugin.java | 1 + .../plugins/treatments/TreatmentService.java | 6 +- .../plugins/treatments/TreatmentsFragment.kt | 26 +- .../plugins/treatments/TreatmentsPlugin.java | 12 +- .../fragments/TreatmentsBolusFragment.java | 6 +- .../TreatmentsCareportalFragment.java | 4 +- .../TreatmentsExtendedBolusesFragment.java | 4 +- .../TreatmentsProfileSwitchFragment.kt | 45 +- .../TreatmentsTempTargetFragment.java | 4 +- .../TreatmentsTemporaryBasalsFragment.java | 4 +- .../androidaps/queue/CommandQueue.java | 10 +- .../androidaps/queue/QueueThread.java | 28 +- .../queue/commands/CommandBolus.java | 2 +- .../receivers/ChargingStateReceiver.java | 2 +- .../androidaps/receivers/KeepAliveReceiver.kt | 62 ++- .../androidaps/receivers/NSAlarmReceiver.java | 6 +- .../receivers/NetworkChangeReceiver.java | 2 +- .../androidaps/services/DataService.java | 29 +- .../androidaps/services/LocationService.java | 4 +- .../androidaps/setupwizard/SWDefinition.java | 495 ----------------- .../androidaps/setupwizard/SWDefinition.kt | 452 ++++++++++++++++ .../setupwizard/SWEventListener.java | 2 +- .../setupwizard/SetupWizardActivity.java | 40 +- .../setupwizard/elements/SWEditUrl.java | 2 +- .../setupwizard/elements/SWFragment.java | 34 -- .../setupwizard/elements/SWFragment.kt | 18 + .../setupwizard/elements/SWItem.java | 4 +- .../setupwizard/elements/SWPlugin.java | 4 +- .../androidaps/utils/AndroidPermission.java | 20 +- .../androidaps/utils/BolusWizard.kt | 2 +- .../androidaps/utils/LocalAlertUtils.java | 6 +- .../info/nightscout/androidaps/utils/SP.java | 26 + .../androidaps/utils/ToastUtils.java | 2 +- .../utils/resources/ResourceHelper.kt | 2 +- 232 files changed, 4133 insertions(+), 3845 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBusWrapper.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java create mode 100644 app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWFragment.java create mode 100644 app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWFragment.kt diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 48bbf82e58..d64a7056fc 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -10,6 +10,10 @@