diff --git a/app/build.gradle b/app/build.gradle index fe4517d78e..9077e2f9e3 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -63,7 +63,7 @@ android { targetSdkVersion 25 multiDexEnabled true versionCode 1500 - version "2.0a-dev" + version "2.0b-dev" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", generateGitBuild() testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 74f78532fd..bbe042213a 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -40,17 +40,17 @@ - + - + - + @@ -66,7 +66,7 @@ - + - + \ No newline at end of file diff --git a/app/src/main/java/com/squareup/otto/LoggingBus.java b/app/src/main/java/com/squareup/otto/LoggingBus.java index 3417e7dd41..f75cd5b8d3 100644 --- a/app/src/main/java/com/squareup/otto/LoggingBus.java +++ b/app/src/main/java/com/squareup/otto/LoggingBus.java @@ -11,6 +11,7 @@ import java.util.Map; import java.util.Set; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.logging.L; /** Logs events has they're being posted to and dispatched from the event bus. * @@ -18,7 +19,7 @@ import info.nightscout.androidaps.events.Event; * after 10s (after startup) and then again every 60s. * */ public class LoggingBus extends Bus { - private static Logger log = LoggerFactory.getLogger(LoggingBus.class); + private static Logger log = LoggerFactory.getLogger(L.EVENTS); private static long everyMinute = System.currentTimeMillis() + 10 * 1000; private Map> event2Receiver = new HashMap<>(); diff --git a/app/src/main/java/info/nightscout/androidaps/Config.java b/app/src/main/java/info/nightscout/androidaps/Config.java index a12e0a9ea0..ab94b1ddac 100644 --- a/app/src/main/java/info/nightscout/androidaps/Config.java +++ b/app/src/main/java/info/nightscout/androidaps/Config.java @@ -23,22 +23,4 @@ public class Config { public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER; - public static final boolean detailedLog = true; - public static final boolean logFunctionCalls = true; - public static final boolean logIncommingData = true; - public static final boolean logAPSResult = true; - public static final boolean logPumpComm = true; - public static final boolean logPrefsChange = true; - public static final boolean logConfigBuilder = true; - public static final boolean logNSUpload = true; - public static final boolean logPumpActions = true; - public static final boolean logCongigBuilderActions = true; - public static final boolean logAutosensData = false; - public static final boolean logEvents = false; - public static final boolean logProfile = false; - - // DanaR specific - public static final boolean logDanaBTComm = true; - public static boolean logDanaMessageDetail = true; - public static final boolean logDanaSerialEngine = true; } diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java index a66d4e77f1..ffe227dc1b 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -67,4 +67,5 @@ public class Constants { //SMS Communicator public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); + } diff --git a/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java b/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java deleted file mode 100644 index 636db14086..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/HistoryBrowseActivity.java +++ /dev/null @@ -1,410 +0,0 @@ -package info.nightscout.androidaps; - -import android.app.Activity; -import android.os.Bundle; -import android.support.v4.content.res.ResourcesCompat; -import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.PopupMenu; -import android.text.SpannableString; -import android.text.style.ForegroundColorSpan; -import android.view.Menu; -import android.view.MenuItem; -import android.view.View; -import android.widget.Button; -import android.widget.ImageButton; -import android.widget.SeekBar; -import android.widget.TextView; - -import com.jjoe64.graphview.GraphView; -import com.squareup.otto.Subscribe; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Calendar; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.OnClick; -import butterknife.OnLongClick; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.events.EventCustomCalculationFinished; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; -import info.nightscout.androidaps.plugins.Overview.OverviewFragment; -import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; -import info.nightscout.androidaps.plugins.Overview.graphData.GraphData; -import info.nightscout.utils.DateUtil; -import info.nightscout.utils.SP; - -public class HistoryBrowseActivity extends AppCompatActivity { - private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); - - - ImageButton chartButton; - - boolean showBasal = true; - boolean showIob, showCob, showDev, showRat, showDevslope; - - - @BindView(R.id.historybrowse_date) - Button buttonDate; - @BindView(R.id.historybrowse_zoom) - Button buttonZoom; - @BindView(R.id.historyybrowse_bggraph) - GraphView bgGraph; - @BindView(R.id.historybrowse_iobgraph) - GraphView iobGraph; - @BindView(R.id.historybrowse_seekBar) - SeekBar seekBar; - @BindView(R.id.historybrowse_noprofile) - TextView noProfile; - - private int rangeToDisplay = 24; // for graph - private long start; - - IobCobCalculatorPlugin iobCobCalculatorPlugin; - - EventCustomCalculationFinished eventCustomCalculationFinished = new EventCustomCalculationFinished(); - - public HistoryBrowseActivity() { - iobCobCalculatorPlugin = new IobCobCalculatorPlugin(); - } - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_historybrowse); - - ButterKnife.bind(this); - - bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); - bgGraph.getGridLabelRenderer().reloadStyles(); - iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); - iobGraph.getGridLabelRenderer().reloadStyles(); - iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false); - bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50); - iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50); - iobGraph.getGridLabelRenderer().setNumVerticalLabels(5); - - setupChartMenu(); - - // set start of current day - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(System.currentTimeMillis()); - calendar.set(Calendar.MILLISECOND, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.HOUR_OF_DAY, 0); - start = calendar.getTimeInMillis(); - } - - @Override - protected void onResume() { - super.onResume(); - updateGUI("onResume"); - } - - - @OnClick(R.id.historybrowse_start) - void onClickStart() { - } - - @OnClick(R.id.historybrowse_left) - void onClickLeft() { - start -= rangeToDisplay * 60 * 60 * 1000L; - updateGUI("left"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onClickLeft", start, true, eventCustomCalculationFinished); - } - - @OnClick(R.id.historybrowse_right) - void onClickRight() { - start += rangeToDisplay * 60 * 60 * 1000L; - updateGUI("right"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onClickRight", start, true, eventCustomCalculationFinished); - } - - @OnClick(R.id.historybrowse_end) - void onClickEnd() { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(System.currentTimeMillis()); - calendar.set(Calendar.MILLISECOND, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.HOUR_OF_DAY, 0); - start = calendar.getTimeInMillis(); - updateGUI("resetToMidnight"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onClickEnd", start, true, eventCustomCalculationFinished); - } - - @OnClick(R.id.historybrowse_zoom) - void onClickZoom() { - rangeToDisplay += 6; - rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; - updateGUI("rangeChange"); - } - - @OnLongClick(R.id.historybrowse_zoom) - boolean onLongClickZoom() { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(start); - calendar.set(Calendar.MILLISECOND, 0); - calendar.set(Calendar.SECOND, 0); - calendar.set(Calendar.MINUTE, 0); - calendar.set(Calendar.HOUR_OF_DAY, 0); - start = calendar.getTimeInMillis(); - updateGUI("resetToMidnight"); - iobCobCalculatorPlugin.clearCache(); - iobCobCalculatorPlugin.runCalculation("onLongClickZoom", start, true, eventCustomCalculationFinished); - return true; - } - - @OnClick(R.id.historybrowse_date) - void onClickDate() { - } - - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished e) { - Activity activity = this; - if (activity != null && e.cause == eventCustomCalculationFinished) { - log.debug("EventAutosensCalculationFinished"); - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - synchronized (HistoryBrowseActivity.this) { - updateGUI("EventAutosensCalculationFinished"); - } - } - }); - } - } - - void updateGUI(String from) { - - if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null) - return; - - final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); - final Profile profile = MainApp.getConfigBuilder().getProfile(); - - if (profile == null) { - noProfile.setVisibility(View.VISIBLE); - return; - } else { - noProfile.setVisibility(View.GONE); - } - - final String units = profile.getUnits(); - - double lowLineSetting = SP.getDouble("low_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units)); - double highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units)); - - if (lowLineSetting < 1) - lowLineSetting = Profile.fromMgdlToUnits(76d, units); - if (highLineSetting < 1) - highLineSetting = Profile.fromMgdlToUnits(180d, units); - - final double lowLine = lowLineSetting; - final double highLine = highLineSetting; - - final boolean showPrediction = false; - - int hoursToFetch; - final long toTime; - final long fromTime; - //if (showPrediction) { - //int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000)); - //predHours = Math.min(2, predHours); - //predHours = Math.max(0, predHours); - //hoursToFetch = rangeToDisplay - predHours; - //toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific - //fromTime = toTime - hoursToFetch * 60 * 60 * 1000L; - //endTime = toTime + predHours * 60 * 60 * 1000L; - //} else { - fromTime = start + 100000; - toTime = start + rangeToDisplay * 60 * 60 * 1000L; - //} - - buttonDate.setText(DateUtil.dateAndTimeString(start)); - buttonZoom.setText(String.valueOf(rangeToDisplay)); - - log.debug("Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime)); - - final long pointer = System.currentTimeMillis(); - - // ------------------ 1st graph - - final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin()); - - // **** In range Area **** - graphData.addInRangeArea(fromTime, toTime, lowLine, highLine); - - // **** BG **** - if (showPrediction) -//graphData.addBgReadings(fromTime, toTime, lowLine, highLine, (DetermineBasalResultAMA) finalLastRun.constraintsProcessed); - ; - else - graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null); - - // set manual x bounds to have nice steps - graphData.formatAxis(fromTime, toTime); - - // Treatments - graphData.addTreatments(fromTime, toTime); - - // add basal data - if (pump.getPumpDescription().isTempBasalCapable && showBasal) { - graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2d); - } - - // **** NOW line **** - graphData.addNowLine(pointer); - - // ------------------ 2nd graph - - final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin); - - boolean useIobForScale = false; - boolean useCobForScale = false; - boolean useDevForScale = false; - boolean useRatioForScale = false; - boolean useDevSlopeForScale = false; - - if (showIob) { - useIobForScale = true; - } else if (showCob) { - useCobForScale = true; - } else if (showDev) { - useDevForScale = true; - } else if (showRat) { - useRatioForScale = true; - } else if (showDevslope) { - useDevSlopeForScale = true; - } - - if (showIob) - secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d); - if (showCob) - secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d); - if (showDev) - secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d); - if (showRat) - secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d); - if (showDevslope) - secondGraphData.addDeviationSlope(fromTime, toTime, useDevSlopeForScale, 1d); - - // **** NOW line **** - // set manual x bounds to have nice steps - secondGraphData.formatAxis(fromTime, toTime); - secondGraphData.addNowLine(pointer); - - // do GUI update - if (showIob || showCob || showDev || showRat || showDevslope) { - iobGraph.setVisibility(View.VISIBLE); - } else { - iobGraph.setVisibility(View.GONE); - } - // finally enforce drawing of graphs - graphData.performUpdate(); - secondGraphData.performUpdate(); - } - - private void setupChartMenu() { - chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton); - chartButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - MenuItem item; - CharSequence title; - SpannableString s; - PopupMenu popup = new PopupMenu(v.getContext(), v); - - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showBasal); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showIob); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showCob); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showDev); - - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity)); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showRat); - - if (MainApp.devBranch) { - item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope"); - title = item.getTitle(); - s = new SpannableString(title); - s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0); - item.setTitle(s); - item.setCheckable(true); - item.setChecked(showDevslope); - } - - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - @Override - public boolean onMenuItemClick(MenuItem item) { - if (item.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) { - showBasal = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) { - showIob = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) { - showCob = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) { - showDev = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) { - showRat = !item.isChecked(); - } else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) { - showDevslope = !item.isChecked(); - } - updateGUI("onGraphCheckboxesCheckedChanged"); - return true; - } - }); - chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp); - popup.setOnDismissListener(new PopupMenu.OnDismissListener() { - @Override - public void onDismiss(PopupMenu menu) { - chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp); - } - }); - popup.show(); - } - }); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index c863f9f2b8..10839fbdef 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -4,16 +4,13 @@ import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Rect; -import android.net.Uri; import android.os.Bundle; -import android.os.Environment; import android.os.PersistableBundle; import android.os.PowerManager; import android.support.annotation.Nullable; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.app.ActivityCompat; -import android.support.v4.content.FileProvider; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; @@ -41,32 +38,31 @@ import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; -import java.io.IOException; -import java.util.List; - +import info.nightscout.androidaps.activities.AgreementActivity; +import info.nightscout.androidaps.activities.HistoryBrowseActivity; +import info.nightscout.androidaps.activities.PreferencesActivity; +import info.nightscout.androidaps.activities.SingleFragmentActivity; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventFeatureRunning; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.Food.FoodPlugin; -import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LogSettingActivity; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.setupwizard.SetupWizardActivity; import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.utils.AndroidPermission; -import info.nightscout.utils.ImportExportPrefs; import info.nightscout.utils.LocaleHelper; import info.nightscout.utils.LogDialog; -import info.nightscout.utils.LoggerUtils; import info.nightscout.utils.OKDialog; import info.nightscout.utils.PasswordProtection; import info.nightscout.utils.SP; public class MainActivity extends AppCompatActivity { - private static Logger log = LoggerFactory.getLogger(MainActivity.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); protected PowerManager.WakeLock mWakeLock; @@ -78,7 +74,7 @@ public class MainActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if (Config.logFunctionCalls) + if (L.isEnabled(L.CORE)) log.debug("onCreate"); Iconify.with(new FontAwesomeModule()); @@ -138,6 +134,9 @@ public class MainActivity extends AppCompatActivity { protected void onResume() { super.onResume(); + if (L.isEnabled(L.CORE)) + log.debug("onResume"); + if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) { Intent intent = new Intent(this, SetupWizardActivity.class); startActivity(intent); @@ -157,6 +156,8 @@ public class MainActivity extends AppCompatActivity { @Override public void onDestroy() { + if (L.isEnabled(L.CORE)) + log.debug("onDestroy"); if (mWakeLock != null) if (mWakeLock.isHeld()) mWakeLock.release(); @@ -289,7 +290,7 @@ public class MainActivity extends AppCompatActivity { private void checkUpgradeToProfileTarget() { // TODO: can be removed in the future boolean oldKeyExists = SP.contains("openapsma_min_bg"); if (oldKeyExists) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); String oldRange = SP.getDouble("openapsma_min_bg", 0d) + " - " + SP.getDouble("openapsma_max_bg", 0d); String newRange = ""; if (profile != null) { @@ -352,7 +353,6 @@ public class MainActivity extends AppCompatActivity { public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); pluginPreferencesMenuItem = menu.findItem(R.id.nav_plugin_preferences); - menu.findItem(R.id.nav_historybrowser).setVisible(MainApp.devBranch); checkPluginPreferences(findViewById(R.id.pager)); return true; } @@ -377,6 +377,9 @@ public class MainActivity extends AppCompatActivity { case R.id.nav_show_logcat: LogDialog.showLogcat(this); return true; + case R.id.nav_logsettings: + startActivity(new Intent(this, LogSettingActivity.class)); + return true; case R.id.nav_about: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION); @@ -386,7 +389,7 @@ public class MainActivity extends AppCompatActivity { builder.setIcon(R.mipmap.blueowl); String message = "Build: " + BuildConfig.BUILDVERSION + "\n"; message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n"; - message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + ConfigBuilderPlugin.nightscoutVersionName; + message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName; if (MainApp.engineeringMode) message += "\n" + MainApp.gs(R.string.engineering_mode_enabled); message += MainApp.gs(R.string.about_link_urls); diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index dd96be6866..b16f3bc570 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -23,12 +23,12 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; -import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Actions.ActionsFragment; import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; @@ -42,6 +42,7 @@ import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugi import info.nightscout.androidaps.plugins.Maintenance.MaintenancePlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; @@ -76,14 +77,14 @@ import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.LoggerUtils; -import info.nightscout.utils.NSUpload; import io.fabric.sdk.android.Fabric; public class MainApp extends Application { - private static Logger log = LoggerFactory.getLogger(MainApp.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); private static KeepAliveReceiver keepAliveReceiver; private static Bus sBus; @@ -107,6 +108,7 @@ public class MainApp extends Application { @Override public void onCreate() { super.onCreate(); + log.debug("onCreate"); sInstance = this; sResources = getResources(); sConstraintsChecker = new ConstraintChecker(this); @@ -119,7 +121,7 @@ public class MainApp extends Application { Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION); } } catch (Exception e) { - android.util.Log.e("ANDROIDAPS", "Error with Fabric init! " + e); + log.error("Error with Fabric init! " + e); } JodaTimeAndroid.init(this); @@ -133,7 +135,7 @@ public class MainApp extends Application { engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile(); devBranch = BuildConfig.VERSION.contains("dev"); - sBus = Config.logEvents ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY); + sBus = L.isEnabled(L.EVENTS) ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY); registerLocalBroadcastReceiver(); @@ -391,6 +393,8 @@ public class MainApp extends Application { @Override public void onTerminate() { + if (L.isEnabled(L.CORE)) + log.debug("onTerminate"); super.onTerminate(); if (sDatabaseHelper != null) { sDatabaseHelper.close(); diff --git a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java b/app/src/main/java/info/nightscout/androidaps/Services/DataService.java deleted file mode 100644 index ca7d760cc4..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/Services/DataService.java +++ /dev/null @@ -1,616 +0,0 @@ -package info.nightscout.androidaps.Services; - -import android.app.IntentService; -import android.content.Intent; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.provider.Telephony; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.events.EventNsFood; -import info.nightscout.androidaps.events.EventNsTreatment; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; -import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; -import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; -import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; -import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; -import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI; -import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; -import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; -import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; -import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin; -import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin; -import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin; -import info.nightscout.androidaps.plugins.Source.SourcePoctechPlugin; -import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin; -import info.nightscout.androidaps.receivers.DataReceiver; -import info.nightscout.utils.BundleLogger; -import info.nightscout.utils.JsonHelper; -import info.nightscout.utils.NSUpload; -import info.nightscout.utils.SP; - - -public class DataService extends IntentService { - private static Logger log = LoggerFactory.getLogger(DataService.class); - - boolean xDripEnabled = false; - boolean nsClientEnabled = true; - boolean mm640gEnabled = false; - boolean glimpEnabled = false; - boolean dexcomG5Enabled = false; - boolean poctechEnabled = false; - - public DataService() { - super("DataService"); - registerBus(); - } - - @Override - protected void onHandleIntent(final Intent intent) { - if (Config.logFunctionCalls) - log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras())); - if (ConfigBuilderPlugin.getPlugin().getActiveBgSource() == null) { - xDripEnabled = true; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) { - xDripEnabled = true; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = true; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = true; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = true; - dexcomG5Enabled = false; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = true; - poctechEnabled = false; - } else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) { - xDripEnabled = false; - nsClientEnabled = false; - mm640gEnabled = false; - glimpEnabled = false; - dexcomG5Enabled = false; - poctechEnabled = true; - } - - boolean isNSProfile = MainApp.getConfigBuilder().getActiveProfileInterface() != null && MainApp.getConfigBuilder().getActiveProfileInterface().getClass().equals(NSProfilePlugin.class); - - boolean acceptNSData = !SP.getBoolean(R.string.key_ns_upload_only, false); - Bundle bundles = intent.getExtras(); - if (bundles != null && bundles.containsKey("islocal")) { - acceptNSData = acceptNSData || bundles.getBoolean("islocal"); - } - - - if (intent != null) { - final String action = intent.getAction(); - if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { - if (xDripEnabled) { - handleNewDataFromXDrip(intent); - } - } else if (Intents.NS_EMULATOR.equals(action)) { - if (mm640gEnabled) { - handleNewDataFromMM640g(intent); - } - } else if (Intents.GLIMP_BG.equals(action)) { - if (glimpEnabled) { - handleNewDataFromGlimp(intent); - } - } else if (Intents.DEXCOMG5_BG.equals(action)) { - if (dexcomG5Enabled) { - handleNewDataFromDexcomG5(intent); - } - } else if (Intents.POCTECH_BG.equals(action)) { - if (poctechEnabled) { - handleNewDataFromPoctech(intent); - } - } else if (Intents.ACTION_NEW_SGV.equals(action)) { - if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true)) - handleNewDataFromNSClient(intent); - // Objectives 0 - ObjectivesPlugin.bgIsAvailableInNS = true; - ObjectivesPlugin.saveProgress(); - } else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) { - // always handle Profile if NSProfile is enabled without looking at nsUploadOnly - handleNewDataFromNSClient(intent); - } else if (acceptNSData && - (Intents.ACTION_NEW_TREATMENT.equals(action) || - Intents.ACTION_CHANGED_TREATMENT.equals(action) || - Intents.ACTION_REMOVED_TREATMENT.equals(action) || - Intents.ACTION_NEW_STATUS.equals(action) || - Intents.ACTION_NEW_DEVICESTATUS.equals(action) || - Intents.ACTION_NEW_FOOD.equals(action) || - Intents.ACTION_CHANGED_FOOD.equals(action) || - Intents.ACTION_REMOVED_FOOD.equals(action) || - Intents.ACTION_NEW_CAL.equals(action) || - Intents.ACTION_NEW_MBG.equals(action)) - ) { - handleNewDataFromNSClient(intent); - } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { - handleNewSMS(intent); - } - } - if (Config.logFunctionCalls) - log.debug("onHandleIntent exit " + intent); - DataReceiver.completeWakefulIntent(intent); - } - -/* - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - super.onStartCommand(intent, flags, startId); - - if (Config.logFunctionCalls) - log.debug("onStartCommand"); - - return START_STICKY; - } -*/ - - @Override - public void onDestroy() { - super.onDestroy(); - MainApp.bus().unregister(this); - } - - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); - } - - private void handleNewDataFromXDrip(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE); - bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME); - bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP); - bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); - String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified"); - SourceXdripPlugin.getPlugin().setSource(source); - MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP"); - } - - private void handleNewDataFromGlimp(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - bgReading.value = bundle.getDouble("mySGV"); - bgReading.direction = bundle.getString("myTrend"); - bgReading.date = bundle.getLong("myTimestamp"); - bgReading.raw = 0; - - MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP"); - } - - private void handleNewDataFromDexcomG5(Intent intent) { - // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle - - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - String data = bundle.getString("data"); - log.debug("Received Dexcom Data", data); - - try { - JSONArray jsonArray = new JSONArray(data); - log.debug("Received Dexcom Data size:" + jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - bgReading.value = json.getInt("m_value"); - bgReading.direction = json.getString("m_trend"); - bgReading.date = json.getLong("m_time") * 1000L; - bgReading.raw = 0; - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5"); - if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading); - } - if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading); - } - } - - } catch (JSONException e) { - e.printStackTrace(); - } - } - - private void handleNewDataFromPoctech(Intent intent) { - - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - BgReading bgReading = new BgReading(); - - String data = bundle.getString("data"); - log.debug("Received Poctech Data", data); - - try { - JSONArray jsonArray = new JSONArray(data); - log.debug("Received Poctech Data size:" + jsonArray.length()); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - bgReading.value = json.getDouble("current"); - bgReading.direction = json.getString("direction"); - bgReading.date = json.getLong("date"); - bgReading.raw = json.getDouble("raw"); - if (JsonHelper.safeGetString(json, "units", Constants.MGDL).equals("mmol/L")) - bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL; - boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech"); - if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading); - } - if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading); - } - } - - } catch (JSONException e) { - e.printStackTrace(); - } - } - - private void handleNewDataFromMM640g(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - - final String collection = bundle.getString("collection"); - if (collection == null) return; - - if (collection.equals("entries")) { - final String data = bundle.getString("data"); - - if ((data != null) && (data.length() > 0)) { - try { - final JSONArray json_array = new JSONArray(data); - for (int i = 0; i < json_array.length(); i++) { - final JSONObject json_object = json_array.getJSONObject(i); - final String type = json_object.getString("type"); - switch (type) { - case "sgv": - BgReading bgReading = new BgReading(); - - bgReading.value = json_object.getDouble("sgv"); - bgReading.direction = json_object.getString("direction"); - bgReading.date = json_object.getLong("date"); - bgReading.raw = json_object.getDouble("sgv"); - - MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g"); - break; - default: - log.debug("Unknown entries type: " + type); - } - } - } catch (JSONException e) { - log.error("Got JSON exception: " + e); - } - } - } - } - - private void handleNewDataFromNSClient(Intent intent) { - Bundle bundles = intent.getExtras(); - if (bundles == null) return; - if (Config.logIncommingData) - log.debug("Got intent: " + intent.getAction()); - - - if (intent.getAction().equals(Intents.ACTION_NEW_STATUS)) { - if (bundles.containsKey("nsclientversioncode")) { - ConfigBuilderPlugin.nightscoutVersionCode = bundles.getInt("nightscoutversioncode"); // for ver 1.2.3 contains 10203 - ConfigBuilderPlugin.nightscoutVersionName = bundles.getString("nightscoutversionname"); - ConfigBuilderPlugin.nsClientVersionCode = bundles.getInt("nsclientversioncode"); // for ver 1.17 contains 117 - ConfigBuilderPlugin.nsClientVersionName = bundles.getString("nsclientversionname"); - log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName); - try { - if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) { - Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT); - MainApp.bus().post(new EventNewNotification(notification)); - } else { - MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT)); - } - } catch (PackageManager.NameNotFoundException e) { - log.error("Unhandled exception", e); - } - if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) { - Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL); - MainApp.bus().post(new EventNewNotification(notification)); - } else { - MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS)); - } - } else { - Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT); - MainApp.bus().post(new EventNewNotification(notification)); - } - if (bundles.containsKey("status")) { - try { - JSONObject statusJson = new JSONObject(bundles.getString("status")); - NSSettingsStatus.getInstance().setData(statusJson); - if (Config.logIncommingData) - log.debug("Received status: " + statusJson.toString()); - Double targetHigh = NSSettingsStatus.getInstance().getThreshold("bgTargetTop"); - Double targetlow = NSSettingsStatus.getInstance().getThreshold("bgTargetBottom"); - if (targetHigh != null) - OverviewPlugin.bgTargetHigh = targetHigh; - if (targetlow != null) - OverviewPlugin.bgTargetLow = targetlow; - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } - } - if (intent.getAction().equals(Intents.ACTION_NEW_DEVICESTATUS)) { - try { - if (bundles.containsKey("devicestatus")) { - JSONObject devicestatusJson = new JSONObject(bundles.getString("devicestatus")); - NSDeviceStatus.getInstance().setData(devicestatusJson); - if (devicestatusJson.has("pump")) { - // Objectives 0 - ObjectivesPlugin.pumpStatusIsAvailableInNS = true; - ObjectivesPlugin.saveProgress(); - } - } - if (bundles.containsKey("devicestatuses")) { - String devicestatusesstring = bundles.getString("devicestatuses"); - JSONArray jsonArray = new JSONArray(devicestatusesstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject devicestatusJson = jsonArray.getJSONObject(i); - NSDeviceStatus.getInstance().setData(devicestatusJson); - if (devicestatusJson.has("pump")) { - // Objectives 0 - ObjectivesPlugin.pumpStatusIsAvailableInNS = true; - ObjectivesPlugin.saveProgress(); - } - } - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - } - // Handle profile - if (intent.getAction().equals(Intents.ACTION_NEW_PROFILE)) { - try { - String activeProfile = bundles.getString("activeprofile"); - String profile = bundles.getString("profile"); - ProfileStore profileStore = new ProfileStore(new JSONObject(profile)); - NSProfilePlugin.getPlugin().storeNewProfile(profileStore); - MainApp.bus().post(new EventNSProfileUpdateGUI()); - if (Config.logIncommingData) - log.debug("Received profileStore: " + activeProfile + " " + profile); - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } - - if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { - try { - if (bundles.containsKey("treatment")) { - JSONObject json = new JSONObject(bundles.getString("treatment")); - handleTreatmentFromNS(json, intent); - } - if (bundles.containsKey("treatments")) { - String trstring = bundles.getString("treatments"); - JSONArray jsonArray = new JSONArray(trstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - handleTreatmentFromNS(json, intent); - } - } - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } - - if (intent.getAction().equals(Intents.ACTION_REMOVED_TREATMENT)) { - try { - if (bundles.containsKey("treatment")) { - String trstring = bundles.getString("treatment"); - JSONObject json = new JSONObject(trstring); - handleTreatmentFromNS(json); - } - - if (bundles.containsKey("treatments")) { - String trstring = bundles.getString("treatments"); - JSONArray jsonArray = new JSONArray(trstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject json = jsonArray.getJSONObject(i); - handleTreatmentFromNS(json); - } - } - } catch (JSONException e) { - log.error("Unhandled exception", e); - } - } - - if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) { - try { - if (bundles.containsKey("sgv")) { - String sgvstring = bundles.getString("sgv"); - JSONObject sgvJson = new JSONObject(sgvstring); - storeSgv(sgvJson); - } - - if (bundles.containsKey("sgvs")) { - String sgvstring = bundles.getString("sgvs"); - JSONArray jsonArray = new JSONArray(sgvstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject sgvJson = jsonArray.getJSONObject(i); - storeSgv(sgvJson); - } - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - } - - if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) { - try { - if (bundles.containsKey("mbg")) { - String mbgstring = bundles.getString("mbg"); - JSONObject mbgJson = new JSONObject(mbgstring); - storeMbg(mbgJson); - } - - if (bundles.containsKey("mbgs")) { - String sgvstring = bundles.getString("mbgs"); - JSONArray jsonArray = new JSONArray(sgvstring); - for (int i = 0; i < jsonArray.length(); i++) { - JSONObject mbgJson = jsonArray.getJSONObject(i); - storeMbg(mbgJson); - } - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - } - - if (intent.getAction().equals(Intents.ACTION_NEW_FOOD) - || intent.getAction().equals(Intents.ACTION_CHANGED_FOOD)) { - int mode = Intents.ACTION_NEW_FOOD.equals(intent.getAction()) ? EventNsFood.ADD : EventNsFood.UPDATE; - EventNsFood evt = new EventNsFood(mode, bundles); - MainApp.bus().post(evt); - } - - if (intent.getAction().equals(Intents.ACTION_REMOVED_FOOD)) { - EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles); - MainApp.bus().post(evt); - } - } - - private void handleTreatmentFromNS(JSONObject json) { - // new DB model - EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json); - MainApp.bus().post(evtTreatment); - // old DB model - String _id = JsonHelper.safeGetString(json, "_id"); - MainApp.getDbHelper().deleteTempTargetById(_id); - MainApp.getDbHelper().deleteTempBasalById(_id); - MainApp.getDbHelper().deleteExtendedBolusById(_id); - MainApp.getDbHelper().deleteCareportalEventById(_id); - MainApp.getDbHelper().deleteProfileSwitchById(_id); - } - - private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException { - // new DB model - int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE; - double insulin = JsonHelper.safeGetDouble(json, "insulin"); - double carbs = JsonHelper.safeGetDouble(json, "carbs"); - String eventType = JsonHelper.safeGetString(json, "eventType"); - if (insulin > 0 || carbs > 0) { - EventNsTreatment evtTreatment = new EventNsTreatment(mode, json); - MainApp.bus().post(evtTreatment); - } else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) { - // old DB model - MainApp.getDbHelper().updateDanaRHistoryRecordId(json); - } else if (eventType.equals(CareportalEvent.TEMPORARYTARGET)) { - MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(json); - } else if (eventType.equals(CareportalEvent.TEMPBASAL)) { - MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json); - } else if (eventType.equals(CareportalEvent.COMBOBOLUS)) { - MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); - } else if (eventType.equals(CareportalEvent.PROFILESWITCH)) { - MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(json); - } else if (eventType.equals(CareportalEvent.SITECHANGE) || - eventType.equals(CareportalEvent.INSULINCHANGE) || - eventType.equals(CareportalEvent.SENSORCHANGE) || - eventType.equals(CareportalEvent.BGCHECK) || - eventType.equals(CareportalEvent.NOTE) || - eventType.equals(CareportalEvent.NONE) || - eventType.equals(CareportalEvent.ANNOUNCEMENT) || - eventType.equals(CareportalEvent.QUESTION) || - eventType.equals(CareportalEvent.EXERCISE) || - eventType.equals(CareportalEvent.OPENAPSOFFLINE) || - eventType.equals(CareportalEvent.PUMPBATTERYCHANGE)) { - MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json); - } - - if (eventType.equals(CareportalEvent.ANNOUNCEMENT)) { - long date = JsonHelper.safeGetLong(json,"mills"); - long now = System.currentTimeMillis(); - 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"))) { - Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60); - MainApp.bus().post(new EventNewNotification(announcement)); - } - } - } - - private void storeMbg(JSONObject mbgJson) { - NSMbg nsMbg = new NSMbg(mbgJson); - CareportalEvent careportalEvent = new CareportalEvent(nsMbg); - MainApp.getDbHelper().createOrUpdate(careportalEvent); - if (Config.logIncommingData) - log.debug("Adding/Updating new MBG: " + careportalEvent.log()); - } - - private void storeSgv(JSONObject sgvJson) { - NSSgv nsSgv = new NSSgv(sgvJson); - BgReading bgReading = new BgReading(nsSgv); - MainApp.getDbHelper().createIfNotExists(bgReading, "NS"); - SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills")); - } - - private void handleNewSMS(Intent intent) { - Bundle bundle = intent.getExtras(); - if (bundle == null) return; - MainApp.bus().post(new EventNewSMS(bundle)); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/AgreementActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java similarity index 91% rename from app/src/main/java/info/nightscout/androidaps/AgreementActivity.java rename to app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java index 3a30659884..582b10d57d 100644 --- a/app/src/main/java/info/nightscout/androidaps/AgreementActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps; +package info.nightscout.androidaps.activities; import android.app.Activity; import android.content.Intent; @@ -9,6 +9,8 @@ import android.view.View; import android.widget.Button; import android.widget.CheckBox; +import info.nightscout.androidaps.MainActivity; +import info.nightscout.androidaps.R; import info.nightscout.utils.SP; public class AgreementActivity extends Activity { diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java new file mode 100644 index 0000000000..0e4535a778 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java @@ -0,0 +1,435 @@ +package info.nightscout.androidaps.activities; + +import android.os.Bundle; +import android.os.SystemClock; +import android.support.v4.content.res.ResourcesCompat; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.PopupMenu; +import android.text.SpannableString; +import android.text.style.ForegroundColorSpan; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.ImageButton; +import android.widget.SeekBar; +import android.widget.TextView; + +import com.jjoe64.graphview.GraphView; +import com.squareup.otto.Subscribe; +import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Calendar; +import java.util.Date; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; +import butterknife.OnLongClick; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.events.EventCustomCalculationFinished; +import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; +import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; +import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; +import info.nightscout.androidaps.plugins.Overview.OverviewFragment; +import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; +import info.nightscout.androidaps.plugins.Overview.graphData.GraphData; +import info.nightscout.utils.DateUtil; +import info.nightscout.utils.T; + +public class HistoryBrowseActivity extends AppCompatActivity { + private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); + + + ImageButton chartButton; + + boolean showBasal = true; + boolean showIob, showCob, showDev, showRat, showDevslope; + + + @BindView(R.id.historybrowse_date) + Button buttonDate; + @BindView(R.id.historybrowse_zoom) + Button buttonZoom; + @BindView(R.id.historyybrowse_bggraph) + GraphView bgGraph; + @BindView(R.id.historybrowse_iobgraph) + GraphView iobGraph; + @BindView(R.id.historybrowse_seekBar) + SeekBar seekBar; + @BindView(R.id.historybrowse_noprofile) + TextView noProfile; + @BindView(R.id.overview_iobcalculationprogess) + TextView iobCalculationProgressView; + + private int rangeToDisplay = 24; // for graph + private long start = 0; + + IobCobCalculatorPlugin iobCobCalculatorPlugin; + + EventCustomCalculationFinished eventCustomCalculationFinished = new EventCustomCalculationFinished(); + + public HistoryBrowseActivity() { + iobCobCalculatorPlugin = new IobCobCalculatorPlugin(); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_historybrowse); + + ButterKnife.bind(this); + + bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); + bgGraph.getGridLabelRenderer().reloadStyles(); + iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); + iobGraph.getGridLabelRenderer().reloadStyles(); + iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false); + bgGraph.getGridLabelRenderer().setLabelVerticalWidth(50); + iobGraph.getGridLabelRenderer().setLabelVerticalWidth(50); + iobGraph.getGridLabelRenderer().setNumVerticalLabels(5); + + setupChartMenu(); + } + + @Override + public void onPause() { + super.onPause(); + MainApp.bus().unregister(this); + iobCobCalculatorPlugin.stopCalculation("onPause"); + } + + @Override + public void onResume() { + super.onResume(); + MainApp.bus().register(this); + // set start of current day + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + calendar.set(Calendar.MILLISECOND, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.HOUR_OF_DAY, 0); + start = calendar.getTimeInMillis(); + runCalculation("onResume"); + SystemClock.sleep(1000); + updateGUI("onResume"); + } + + @OnClick(R.id.historybrowse_left) + void onClickLeft() { + start -= T.hours(rangeToDisplay).msecs(); + updateGUI("onClickLeft"); + runCalculation("onClickLeft"); + } + + @OnClick(R.id.historybrowse_right) + void onClickRight() { + start += T.hours(rangeToDisplay).msecs(); + updateGUI("onClickRight"); + runCalculation("onClickRight"); + } + + @OnClick(R.id.historybrowse_end) + void onClickEnd() { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(System.currentTimeMillis()); + calendar.set(Calendar.MILLISECOND, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.HOUR_OF_DAY, 0); + start = calendar.getTimeInMillis(); + updateGUI("onClickEnd"); + runCalculation("onClickEnd"); + } + + @OnClick(R.id.historybrowse_zoom) + void onClickZoom() { + rangeToDisplay += 6; + rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; + updateGUI("rangeChange"); + } + + @OnLongClick(R.id.historybrowse_zoom) + boolean onLongClickZoom() { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(start); + calendar.set(Calendar.MILLISECOND, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.HOUR_OF_DAY, 0); + start = calendar.getTimeInMillis(); + updateGUI("resetToMidnight"); + runCalculation("onLongClickZoom"); + return true; + } + + @OnClick(R.id.historybrowse_date) + void onClickDate() { + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date(start)); + DatePickerDialog dpd = DatePickerDialog.newInstance( + (view, year, monthOfYear, dayOfMonth) -> { + Date date = new Date(0); + date.setYear(year - 1900); + date.setMonth(monthOfYear); + date.setDate(dayOfMonth); + date.setHours(0); + start = date.getTime(); + updateGUI("onClickDate"); + runCalculation("onClickDate"); + }, + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH), + calendar.get(Calendar.DAY_OF_MONTH) + ); + dpd.setThemeDark(true); + dpd.dismissOnPause(true); + dpd.show(getFragmentManager(), "Datepickerdialog"); + } + + private void runCalculation(String from) { + long end = start + T.hours(rangeToDisplay).msecs(); + iobCobCalculatorPlugin.stopCalculation(from); + iobCobCalculatorPlugin.clearCache(); + iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished); + } + + @Subscribe + public void onStatusEvent(final EventAutosensCalculationFinished e) { + if (e.cause == eventCustomCalculationFinished) { + log.debug("EventAutosensCalculationFinished"); + runOnUiThread(() -> { + synchronized (HistoryBrowseActivity.this) { + updateGUI("EventAutosensCalculationFinished"); + } + }); + } + } + + @Subscribe + public void onStatusEvent(final EventIobCalculationProgress e) { + runOnUiThread(() -> { + if (iobCalculationProgressView != null) + iobCalculationProgressView.setText(e.progress); + }); + } + + void updateGUI(String from) { + log.debug("updateGUI from: " + from); + + if (noProfile == null || buttonDate == null || buttonZoom == null || bgGraph == null || iobGraph == null || seekBar == null) + return; + + final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); + + if (profile == null) { + noProfile.setVisibility(View.VISIBLE); + return; + } else { + noProfile.setVisibility(View.GONE); + } + + final String units = profile.getUnits(); + final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units); + final double highLine = OverviewPlugin.getPlugin().determineHighLine(units); + + buttonDate.setText(DateUtil.dateAndTimeString(start)); + buttonZoom.setText(String.valueOf(rangeToDisplay)); + + final boolean showPrediction = false; + + int hoursToFetch; + final long toTime; + final long fromTime; + //if (showPrediction) { + //int predHours = (int) (Math.ceil(((DetermineBasalResultAMA) finalLastRun.constraintsProcessed).getLatestPredictionsTime() - System.currentTimeMillis()) / (60 * 60 * 1000)); + //predHours = Math.min(2, predHours); + //predHours = Math.max(0, predHours); + //hoursToFetch = rangeToDisplay - predHours; + //toTime = calendar.getTimeInMillis() + 100000; // little bit more to avoid wrong rounding - Graphview specific + //fromTime = toTime - hoursToFetch * 60 * 60 * 1000L; + //endTime = toTime + predHours * 60 * 60 * 1000L; + //} else { + fromTime = start + T.secs(100).msecs(); + toTime = start + T.hours(rangeToDisplay).msecs(); + //} + + log.debug("Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime)); + + final long pointer = System.currentTimeMillis(); + + // ------------------ 1st graph + + final GraphData graphData = new GraphData(bgGraph, iobCobCalculatorPlugin); + + // **** In range Area **** + graphData.addInRangeArea(fromTime, toTime, lowLine, highLine); + + // **** BG **** + if (showPrediction) +//graphData.addBgReadings(fromTime, toTime, lowLine, highLine, (DetermineBasalResultAMA) finalLastRun.constraintsProcessed); + ; + else + graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null); + + // set manual x bounds to have nice steps + graphData.formatAxis(fromTime, toTime); + + // Treatments + graphData.addTreatments(fromTime, toTime); + + // add basal data + if (pump.getPumpDescription().isTempBasalCapable && showBasal) { + graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2d); + } + + // **** NOW line **** + graphData.addNowLine(pointer); + + // ------------------ 2nd graph + + new Thread(() -> { + final GraphData secondGraphData = new GraphData(iobGraph, iobCobCalculatorPlugin); + + boolean useIobForScale = false; + boolean useCobForScale = false; + boolean useDevForScale = false; + boolean useRatioForScale = false; + boolean useDSForScale = false; + + if (showIob) { + useIobForScale = true; + } else if (showCob) { + useCobForScale = true; + } else if (showDev) { + useDevForScale = true; + } else if (showRat) { + useRatioForScale = true; + } else if (showDevslope) { + useDSForScale = true; + } + + if (showIob) + secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d); + if (showCob) + secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d); + if (showDev) + secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d); + if (showRat) + secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d); + if (showDevslope) + secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1d); + + // **** NOW line **** + // set manual x bounds to have nice steps + secondGraphData.formatAxis(fromTime, toTime); + secondGraphData.addNowLine(pointer); + + // do GUI update + runOnUiThread(() -> { + if (showIob || showCob || showDev || showRat || showDevslope) { + iobGraph.setVisibility(View.VISIBLE); + } else { + iobGraph.setVisibility(View.GONE); + } + // finally enforce drawing of graphs + graphData.performUpdate(); + if (showIob || showCob || showDev || showRat || showDevslope) + secondGraphData.performUpdate(); + }); + }).start(); + } + + private void setupChartMenu() { + chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton); + chartButton.setOnClickListener(v -> { + MenuItem item; + CharSequence title; + SpannableString s; + PopupMenu popup = new PopupMenu(v.getContext(), v); + + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showBasal); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showIob); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showCob); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showDev); + + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity)); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showRat); + + if (MainApp.devBranch) { + item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope"); + title = item.getTitle(); + s = new SpannableString(title); + s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0); + item.setTitle(s); + item.setCheckable(true); + item.setChecked(showDevslope); + } + + popup.setOnMenuItemClickListener(item1 -> { + if (item1.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) { + showBasal = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) { + showIob = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) { + showCob = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) { + showDev = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) { + showRat = !item1.isChecked(); + } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) { + showDevslope = !item1.isChecked(); + } + updateGUI("onGraphCheckboxesCheckedChanged"); + return true; + }); + chartButton.setImageResource(R.drawable.ic_arrow_drop_up_white_24dp); + popup.setOnDismissListener(menu -> chartButton.setImageResource(R.drawable.ic_arrow_drop_down_white_24dp)); + popup.show(); + }); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java similarity index 97% rename from app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java rename to app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java index a8def0ebf9..8876737be3 100644 --- a/app/src/main/java/info/nightscout/androidaps/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps; +package info.nightscout.androidaps.activities; import android.content.SharedPreferences; import android.os.Bundle; @@ -11,6 +11,9 @@ import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.text.TextUtils; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginBase; @@ -86,7 +89,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre pref.setSummary("******"); } else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) { pref.setSummary(SP.getString(R.string.key_danars_name, "")); - } else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) { + } else if (editTextPref.getText() != null ) { ((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage()); pref.setSummary(editTextPref.getText()); } else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) { diff --git a/app/src/main/java/info/nightscout/androidaps/SingleFragmentActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java similarity index 91% rename from app/src/main/java/info/nightscout/androidaps/SingleFragmentActivity.java rename to app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java index 567799fe5e..04fd7a6be7 100644 --- a/app/src/main/java/info/nightscout/androidaps/SingleFragmentActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java @@ -1,16 +1,17 @@ -package info.nightscout.androidaps; +package info.nightscout.androidaps.activities; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; -import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.activities.PreferencesActivity; import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.utils.PasswordProtection; public class SingleFragmentActivity extends AppCompatActivity { diff --git a/app/src/main/java/info/nightscout/androidaps/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java similarity index 98% rename from app/src/main/java/info/nightscout/androidaps/TDDStatsActivity.java rename to app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index 7bc3ee31c5..e18e2552eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps; +package info.nightscout.androidaps.activities; import android.app.Activity; import android.graphics.Color; @@ -33,14 +33,15 @@ import java.util.Date; import java.util.LinkedList; import java.util.List; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; -import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; @@ -121,7 +122,7 @@ public class TDDStatsActivity extends Activity { TBB = SP.getString("TBB", "10.00"); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile != null) { double cppTBB = profile.baseBasalSum(); TBB = decimalFormat.format(cppTBB); diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index 7412f8ce4c..748710f17a 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -52,6 +52,14 @@ public class Profile { protected Profile() { } + @Override + public String toString() { + if (json != null) + return json.toString(); + else + return "Profile has no JSON"; + } + // Constructor from profileStore JSON public Profile(JSONObject json, String units) { init(json, 100, 0); @@ -295,8 +303,6 @@ public class Profile { Integer getShitfTimeSecs(Integer originalTime) { Integer shiftedTime = originalTime + timeshift * 60 * 60; shiftedTime = (shiftedTime + 24 * 60 * 60) % (24 * 60 * 60); - if (timeshift != 0 && Config.logProfile) - log.debug("(Sec) Original time: " + originalTime + " ShiftedTime: " + shiftedTime); return shiftedTime; } diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java index eebd42f5d2..e25e6085c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java +++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java @@ -10,11 +10,12 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.Round; public class PumpEnactResult { - private static Logger log = LoggerFactory.getLogger(PumpEnactResult.class); + private static Logger log = LoggerFactory.getLogger(L.APS); public boolean success = false; // request was processed successfully (but possible no change was needed) public boolean enacted = false; // request was processed successfully and change has been made diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java index 5ddb7a80b2..83b4e62cf0 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -15,6 +15,8 @@ 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.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; @@ -24,7 +26,7 @@ import info.nightscout.utils.SP; @DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS) public class BgReading implements DataPointWithLabelInterface { - private static Logger log = LoggerFactory.getLogger(BgReading.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; @@ -142,7 +144,7 @@ public class BgReading implements DataPointWithLabelInterface { return false; if (raw != other.raw) return false; - if (!direction.equals(other.direction)) + if (!Objects.equals(direction, other.direction)) return false; if (!Objects.equals(_id, other._id)) return false; @@ -168,7 +170,7 @@ public class BgReading implements DataPointWithLabelInterface { @Override public double getY() { - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); return valueToUnits(units); } @@ -202,7 +204,7 @@ public class BgReading implements DataPointWithLabelInterface { @Override public int getColor() { - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); Double lowLine = SP.getDouble("low_mark", 0d); Double highLine = SP.getDouble("high_mark", 0d); if (lowLine < 1) { diff --git a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java index 6cda2ab4ce..e7fd6c99e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java +++ b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java @@ -25,6 +25,8 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.Interval; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg; import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; @@ -35,7 +37,7 @@ import info.nightscout.utils.Translator; @DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS) public class CareportalEvent implements DataPointWithLabelInterface, Interval { - private static Logger log = LoggerFactory.getLogger(CareportalEvent.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; @@ -153,7 +155,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval { @Override public double getY() { - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); if (eventType.equals(MBG)) { double mbg = 0d; try { diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 5095195872..5ef716bad9 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -27,8 +27,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.Profile; @@ -43,12 +41,14 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.utils.JsonHelper; -import info.nightscout.utils.NSUpload; import info.nightscout.utils.PercentageSplitter; import info.nightscout.utils.ToastUtils; @@ -61,7 +61,7 @@ import info.nightscout.utils.ToastUtils; * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { - private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_BGREADINGS = "BgReadings"; @@ -108,7 +108,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { - log.info("onCreate"); + if (L.isEnabled(L.DATABASE)) + log.info("onCreate"); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); @@ -326,15 +327,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { BgReading old = getDaoBgReadings().queryForId(bgReading.date); if (old == null) { getDaoBgReadings().create(bgReading); - log.debug("BG: New record from: " + from + " " + bgReading.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("BG: New record from: " + from + " " + bgReading.toString()); scheduleBgChange(bgReading); return true; } if (!old.isEqual(bgReading)) { - log.debug("BG: Similiar found: " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("BG: Similiar found: " + old.toString()); old.copyFrom(bgReading); getDaoBgReadings().update(old); - log.debug("BG: Updating record from: " + from + " New data: " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("BG: Updating record from: " + from + " New data: " + old.toString()); scheduleBgChange(bgReading); return false; } @@ -356,7 +360,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleBgChange(@Nullable final BgReading bgReading) { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventNewBg"); + if (L.isEnabled(L.DATABASE)) + log.debug("Firing EventNewBg"); MainApp.bus().post(new EventNewBG(bgReading)); scheduledBgPost = null; } @@ -388,7 +393,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgList = daoBgReadings.query(preparedQuery); } catch (SQLException e) { - log.debug(e.getMessage(), e); + log.error("Unhandled exception", e); } if (bgList != null && bgList.size() > 0) return bgList.get(0); @@ -431,6 +436,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } + public List getBgreadingsDataFromTime(long start, long end, boolean ascending) { + try { + Dao daoBgreadings = getDaoBgReadings(); + List bgReadings; + QueryBuilder queryBuilder = daoBgreadings.queryBuilder(); + queryBuilder.orderBy("date", ascending); + Where where = queryBuilder.where(); + where.between("date", start, end).and().gt("value", 38).and().eq("isValid", true); + PreparedQuery preparedQuery = queryBuilder.prepare(); + bgReadings = daoBgreadings.query(preparedQuery); + return bgReadings; + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + return new ArrayList(); + } + public List getAllBgreadingsDataFromTime(long mills, boolean ascending) { try { Dao daoBgreadings = getDaoBgReadings(); @@ -579,7 +601,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(old); // need to delete/create because date may change too old.copyFrom(tempTarget); getDaoTempTargets().create(old); - log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; } @@ -598,20 +621,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(old); // need to delete/create because date may change too old.copyFrom(tempTarget); getDaoTempTargets().create(old); - log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; } } } getDaoTempTargets().create(tempTarget); - log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } if (tempTarget.source == Source.USER) { getDaoTempTargets().create(tempTarget); - log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } @@ -633,7 +659,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleTemporaryTargetChange() { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventTempTargetChange"); + if (L.isEnabled(L.DATABASE)) + log.debug("Firing EventTempTargetChange"); MainApp.bus().post(new EventTempTargetChange()); scheduledTemTargetPost = null; } @@ -665,7 +692,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTemptargetFromJsonIfNotExists(JSONObject trJson) { try { - String units = JsonHelper.safeGetString(trJson, "units", MainApp.getConfigBuilder().getProfileUnits()); + String units = JsonHelper.safeGetString(trJson, "units", ProfileFunctions.getInstance().getProfileUnits()); TempTarget tempTarget = new TempTarget() .date(trJson.getLong("mills")) .duration(trJson.getInt("duration")) @@ -676,7 +703,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .source(Source.NIGHTSCOUT); createOrUpdate(tempTarget); } catch (JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } @@ -753,7 +780,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } else if (list.size() == 1) { DanaRHistoryRecord record = list.get(0); if (record._id == null || !record._id.equals(trJson.getString("_id"))) { - if (Config.logIncommingData) + if (L.isEnabled(L.DATABASE)) log.debug("Updating _id in DanaR history database: " + trJson.getString("_id")); record._id = trJson.getString("_id"); getDaoDanaRHistory().update(record); @@ -762,7 +789,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } } catch (SQLException | JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } @@ -783,11 +810,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List trList = getDaoTemporaryBasal().query(preparedQuery); if (trList.size() > 0) { // do nothing, pump history record cannot be changed - log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); return false; } getDaoTemporaryBasal().create(tempBasal); - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; @@ -804,7 +833,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too old.copyFrom(tempBasal); getDaoTemporaryBasal().create(old); - log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleTemporaryBasalChange(); @@ -826,7 +856,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too old.copyFrom(tempBasal); getDaoTemporaryBasal().create(old); - log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleTemporaryBasalChange(); @@ -835,14 +866,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoTemporaryBasal().create(tempBasal); - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; } if (tempBasal.source == Source.USER) { getDaoTemporaryBasal().create(tempBasal); - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; @@ -882,7 +915,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleTemporaryBasalChange() { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventTempBasalChange"); + if (L.isEnabled(L.DATABASE)) + log.debug("Firing EventTempBasalChange"); MainApp.bus().post(new EventReloadTempBasalData()); MainApp.bus().post(new EventTempBasalChange()); if (earliestDataChange != null) @@ -967,14 +1001,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { createOrUpdate(tempBasal); } } catch (JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteTempBasalById(String _id) { TemporaryBasal stored = findTempBasalById(_id); if (stored != null) { - log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); scheduleTemporaryBasalChange(); @@ -1020,7 +1055,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return false; } getDaoExtendedBolus().create(extendedBolus); - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; @@ -1033,7 +1069,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(old); // need to delete/create because date may change too old.copyFrom(extendedBolus); getDaoExtendedBolus().create(old); - log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleExtendedBolusChange(); @@ -1055,7 +1092,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(old); // need to delete/create because date may change too old.copyFrom(extendedBolus); getDaoExtendedBolus().create(old); - log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleExtendedBolusChange(); @@ -1064,14 +1102,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoExtendedBolus().create(extendedBolus); - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; } if (extendedBolus.source == Source.USER) { getDaoExtendedBolus().create(extendedBolus); - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; @@ -1111,7 +1151,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void deleteExtendedBolusById(String _id) { ExtendedBolus stored = findExtendedBolusById(_id); if (stored != null) { - log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); scheduleExtendedBolusChange(); @@ -1164,7 +1205,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleExtendedBolusChange() { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventExtendedBolusChange"); + if (L.isEnabled(L.DATABASE)) + log.debug("Firing EventExtendedBolusChange"); MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange())); if (earliestDataChange != null) MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); @@ -1304,11 +1346,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (list.size() == 1) { CareportalEvent record = list.get(0); - if (Config.logIncommingData) + if (L.isEnabled(L.DATABASE)) log.debug("Removing CareportalEvent record from database: " + record.log()); delete(record); } else { - if (Config.logIncommingData) + if (L.isEnabled(L.DATABASE)) log.debug("CareportalEvent not found database: " + _id); } } catch (SQLException e) { @@ -1328,12 +1370,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (list.size() == 0) { careportalEvent = new CareportalEvent(); careportalEvent.source = Source.NIGHTSCOUT; - if (Config.logIncommingData) + if (L.isEnabled(L.DATABASE)) log.debug("Adding CareportalEvent record to database: " + trJson.toString()); // Record does not exists. add } else if (list.size() == 1) { careportalEvent = list.get(0); - if (Config.logIncommingData) + if (L.isEnabled(L.DATABASE)) log.debug("Updating CareportalEvent record in database: " + trJson.toString()); } else { log.error("Something went wrong"); @@ -1345,14 +1387,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvent._id = trJson.getString("_id"); createOrUpdate(careportalEvent); } catch (SQLException | JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } private static void scheduleCareportalEventChange() { class PostRunnable implements Runnable { public void run() { - log.debug("Firing scheduleCareportalEventChange"); + if (L.isEnabled(L.DATABASE)) + log.debug("Firing scheduleCareportalEventChange"); MainApp.bus().post(new EventCareportalEventChange()); scheduledCareportalEventPost = null; } @@ -1398,7 +1441,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().create(profileSwitch); - log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; } @@ -1417,7 +1461,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoProfileSwitch().delete(old); // need to delete/create because date may change too old.copyFrom(profileSwitch); getDaoProfileSwitch().create(old); - log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; } @@ -1426,13 +1471,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // look for already added percentage from NS profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName); getDaoProfileSwitch().create(profileSwitch); - log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } if (profileSwitch.source == Source.USER) { getDaoProfileSwitch().create(profileSwitch); - log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } @@ -1454,7 +1501,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleProfileSwitchChange() { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventProfileSwitchChange"); + if (L.isEnabled(L.DATABASE)) + log.debug("Firing EventProfileSwitchChange"); MainApp.bus().post(new EventReloadProfileSwitchData()); MainApp.bus().post(new EventProfileSwitchChange()); scheduledProfileSwitchEventPost = null; @@ -1504,15 +1552,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Profile profile = store.getSpecificProfile(profileSwitch.profileName); if (profile != null) { profileSwitch.profileJson = profile.getData().toString(); - log.debug("Profile switch prefilled with JSON from local store"); + if (L.isEnabled(L.DATABASE)) + log.debug("Profile switch prefilled with JSON from local store"); // Update data in NS NSUpload.updateProfileSwitch(profileSwitch); } else { - log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } else { - log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } @@ -1520,14 +1571,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profilePlugin = trJson.getString("profilePlugin"); createOrUpdate(profileSwitch); } catch (JSONException e) { - log.error("Unhandled exception", e); + log.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteProfileSwitchById(String _id) { ProfileSwitch stored = findProfileSwitchById(_id); if (stored != null) { - log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); + if (L.isEnabled(L.DATABASE)) + log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); delete(stored); scheduleTemporaryTargetChange(); } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java b/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java index fcda5c9c04..f287e169ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DbRequest.java @@ -10,6 +10,8 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 27.02.2016. *

@@ -17,7 +19,7 @@ import org.slf4j.LoggerFactory; */ @DatabaseTable(tableName = DatabaseHelper.DATABASE_DBREQUESTS) public class DbRequest { - private static Logger log = LoggerFactory.getLogger(DbRequest.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public String nsClientID = null; diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java index ea97f4ddca..4fa2ebb7b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java @@ -21,6 +21,7 @@ import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; @@ -36,7 +37,7 @@ import info.nightscout.utils.Round; @DatabaseTable(tableName = DatabaseHelper.DATABASE_EXTENDEDBOLUSES) public class ExtendedBolus implements Interval, DataPointWithLabelInterface { - private static Logger log = LoggerFactory.getLogger(ExtendedBolus.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java index 40c8e50c6d..f003976d8f 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.Interval; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; @@ -27,7 +28,7 @@ import info.nightscout.utils.DecimalFormatter; @DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES) public class ProfileSwitch implements Interval, DataPointWithLabelInterface { - private static Logger log = LoggerFactory.getLogger(ProfileSwitch.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; diff --git a/app/src/main/java/info/nightscout/androidaps/db/TDD.java b/app/src/main/java/info/nightscout/androidaps/db/TDD.java index f34c79ff1a..9ca849b7b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TDD.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TDD.java @@ -8,6 +8,8 @@ import org.slf4j.LoggerFactory; import java.util.Objects; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.09.2017. */ @@ -15,7 +17,7 @@ import java.util.Objects; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS) public class TDD { - private static Logger log = LoggerFactory.getLogger(TDD.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java index ae016a0f29..15692cbdfe 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java @@ -11,12 +11,13 @@ import java.util.Objects; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.interfaces.Interval; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS) public class TempTarget implements Interval { - private static Logger log = LoggerFactory.getLogger(TempTarget.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java index 733027b188..7fdc7ac117 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java @@ -15,7 +15,9 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; @@ -27,7 +29,7 @@ import info.nightscout.utils.SP; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS) public class TemporaryBasal implements Interval { - private static Logger log = LoggerFactory.getLogger(TemporaryBasal.class); + private static Logger log = LoggerFactory.getLogger(L.DATABASE); @DatabaseField(id = true) public long date; @@ -93,7 +95,7 @@ public class TemporaryBasal implements Interval { } public TemporaryBasal(ExtendedBolus extendedBolus) { - double basal = MainApp.getConfigBuilder().getProfile(extendedBolus.date).getBasal(extendedBolus.date); + double basal = ProfileFunctions.getInstance().getProfile(extendedBolus.date).getBasal(extendedBolus.date); this.date = extendedBolus.date; this.isValid = extendedBolus.isValid; this.source = extendedBolus.source; @@ -318,7 +320,7 @@ public class TemporaryBasal implements Interval { public String toStringFull() { if(isFakeExtended){ - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); Double currentBasalRate = profile.getBasal(); double rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); return getCalcuatedPercentageIfNeeded() + DecimalFormatter.to2Decimal(rate) + "U/h ("+DecimalFormatter.to2Decimal(netExtendedRate)+"E) @" + @@ -340,7 +342,7 @@ public class TemporaryBasal implements Interval { double rate = 0d; if (isFakeExtended) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); Double currentBasalRate = profile.getBasal(); rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); } else if (isAbsolute){ @@ -348,7 +350,7 @@ public class TemporaryBasal implements Interval { } if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){ - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if(profile != null) { double basal = profile.getBasal(); if(basal != 0){ @@ -367,7 +369,7 @@ public class TemporaryBasal implements Interval { double rate = 0d; if (isFakeExtended) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); Double currentBasalRate = profile.getBasal(); rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); } else if (isAbsolute){ @@ -375,7 +377,7 @@ public class TemporaryBasal implements Interval { } if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){ - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if(profile != null) { double basal = profile.getBasal(); if(basal != 0){ @@ -392,7 +394,7 @@ public class TemporaryBasal implements Interval { double rate = 0d; if (isFakeExtended) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); Double currentBasalRate = profile.getBasal(); rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate); } else if (isAbsolute){ diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java index a45ab083e7..d42ead7950 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/BgSourceInterface.java @@ -1,8 +1,12 @@ package info.nightscout.androidaps.interfaces; +import android.content.Intent; + /** * Created by mike on 20.06.2016. */ public interface BgSourceInterface { boolean advancedFilteringSupported(); + + void handleNewData(Intent intent); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java b/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java index 58e6045bd1..26c58ed89e 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/Constraint.java @@ -6,12 +6,14 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 19.03.2018. */ public class Constraint { - private static Logger log = LoggerFactory.getLogger(Constraint.class); + private static Logger log = LoggerFactory.getLogger(L.APS); T value; T originalValue; @@ -57,7 +59,7 @@ public class Constraint { return this; } - public Constraint setIfGreater(T value, String reason, Object from) { + public Constraint setIfGreater(T value, String reason, Object from) { if (value.compareTo(this.value) > 0) { this.value = value; mostLimiting.clear(); @@ -74,7 +76,7 @@ public class Constraint { return this; } - public Constraint addMostLimingReason(String reason, Object from) { + public Constraint addMostLimingReason(String reason, Object from) { mostLimiting.add(from.getClass().getSimpleName().replace("Plugin", "") + ": " + reason); return this; } @@ -86,7 +88,8 @@ public class Constraint { if (count++ != 0) sb.append("\n"); sb.append(r); } - log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); + if (L.isEnabled(L.APS)) + log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString()); return sb.toString(); } @@ -110,7 +113,7 @@ public class Constraint { } public void copyReasons(Constraint another) { - for (String s: another.getReasonList()) { + for (String s : another.getReasonList()) { reasons.add(s); } } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java index 9f3e4fe5c0..b9df338821 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java @@ -7,6 +7,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; @@ -14,7 +15,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; * Created by mike on 09.06.2016. */ public abstract class PluginBase { - private static Logger log = LoggerFactory.getLogger(PluginBase.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); public enum State { NOT_INITIALIZED, @@ -113,7 +114,8 @@ public abstract class PluginBase { if (state != State.ENABLED) { onStateChange(type, state, State.ENABLED); state = State.ENABLED; - log.debug("Starting: " + getName()); + if (L.isEnabled(L.CORE)) + log.debug("Starting: " + getName()); onStart(); } } else { // disabling plugin @@ -121,7 +123,8 @@ public abstract class PluginBase { onStateChange(type, state, State.ENABLED); state = State.DISABLED; onStop(); - log.debug("Stopping: " + getName()); + if (L.isEnabled(L.CORE)) + log.debug("Stopping: " + getName()); } } } else if (type == PluginType.PROFILE) { diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java index 81af28eaa4..f4514ad572 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java @@ -1,6 +1,7 @@ package info.nightscout.androidaps.interfaces; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; +import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; /** * Created by mike on 24.06.2017. @@ -11,6 +12,6 @@ public interface SensitivityInterface { double MIN_HOURS = 1; double MIN_HOURS_FULL_AUTOSENS = 4; - AutosensResult detectSensitivity(long fromTime, long toTime); + AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime); } diff --git a/app/src/main/java/info/nightscout/utils/BundleLogger.java b/app/src/main/java/info/nightscout/androidaps/logging/BundleLogger.java similarity index 90% rename from app/src/main/java/info/nightscout/utils/BundleLogger.java rename to app/src/main/java/info/nightscout/androidaps/logging/BundleLogger.java index ba6ffff869..b559c7af7e 100644 --- a/app/src/main/java/info/nightscout/utils/BundleLogger.java +++ b/app/src/main/java/info/nightscout/androidaps/logging/BundleLogger.java @@ -1,4 +1,4 @@ -package info.nightscout.utils; +package info.nightscout.androidaps.logging; import android.os.Bundle; diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.java b/app/src/main/java/info/nightscout/androidaps/logging/L.java new file mode 100644 index 0000000000..60d6ff4602 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/logging/L.java @@ -0,0 +1,123 @@ +package info.nightscout.androidaps.logging; + +import java.util.ArrayList; +import java.util.List; + +import info.nightscout.utils.SP; + +public class L { + + public static class LogElement { + String name; + boolean defaultValue; + 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 EVENTS = "EVENTS"; + public static final String BGSOURCE = "BGSOURCE"; + public static final String OVERVIEW = "OVERVIEW"; + public static final String NOTIFICATION = "NOTIFICATION"; + public static final String ALARM = "ALARM"; + 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 OBJECTIVES = "OBJECTIVES"; + 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"; + + private static void initialize() { + logElements = new ArrayList<>(); + logElements.add(new LogElement(ALARM, false)); + logElements.add(new LogElement(APS, true)); + logElements.add(new LogElement(AUTOSENS, false)); + logElements.add(new LogElement(BGSOURCE, true)); + logElements.add(new LogElement(CONFIGBUILDER, true)); + logElements.add(new LogElement(CORE, true)); + logElements.add(new LogElement(DATABASE, true)); + logElements.add(new LogElement(DATAFOOD, true)); + logElements.add(new LogElement(DATASERVICE, true)); + logElements.add(new LogElement(DATATREATMENTS, true)); + logElements.add(new LogElement(EVENTS, false, true)); + logElements.add(new LogElement(NOTIFICATION, true)); + logElements.add(new LogElement(NSCLIENT, true)); + logElements.add(new LogElement(OBJECTIVES, false)); + 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)); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/logging/LogSettingActivity.java b/app/src/main/java/info/nightscout/androidaps/logging/LogSettingActivity.java new file mode 100644 index 0000000000..d941e359a9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/logging/LogSettingActivity.java @@ -0,0 +1,79 @@ +package info.nightscout.androidaps.logging; + +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.view.View; +import android.widget.CheckBox; +import android.widget.LinearLayout; +import android.widget.TextView; + +import java.util.List; + +import butterknife.BindView; +import butterknife.ButterKnife; +import butterknife.OnClick; +import butterknife.Unbinder; +import info.nightscout.androidaps.R; + +public class LogSettingActivity extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_logsetting); + ButterKnife.bind(this); + + createViewsForSettings(L.getLogElements()); + } + + private void createViewsForSettings(List elements) { + if (elements.size() == 0) return; + LinearLayout container = (LinearLayout) findViewById(R.id.logsettings_placeholder); + container.removeAllViews(); + for (L.LogElement element : elements) { + PluginViewHolder pluginViewHolder = new PluginViewHolder(element); + container.addView(pluginViewHolder.getBaseView()); + } + } + + @OnClick(R.id.logsettings_reset) + public void onResetClick() { + L.resetToDefaults(); + createViewsForSettings(L.getLogElements()); + } + + public class PluginViewHolder { + + private Unbinder unbinder; + private L.LogElement element; + + LinearLayout baseView; + @BindView(R.id.logsettings_description) + TextView description; + @BindView(R.id.logsettings_visibility) + CheckBox enabled; + + public PluginViewHolder(L.LogElement element) { + this.element = element; + baseView = (LinearLayout) getLayoutInflater().inflate(R.layout.logsettings_item, null); + unbinder = ButterKnife.bind(this, baseView); + + description.setText(element.name); + enabled.setChecked(element.enabled); + } + + public View getBaseView() { + return baseView; + } + + @OnClick(R.id.logsettings_visibility) + void onEnagledChanged() { + element.setEnabled(enabled.isChecked()); + } + + public void unbind() { + unbinder.unbind(); + } + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java index d45fb10b4e..ea17a30218 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java @@ -14,10 +14,10 @@ import com.crashlytics.android.answers.CustomEvent; import com.squareup.otto.Subscribe; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.HistoryBrowseActivity; +import info.nightscout.androidaps.activities.HistoryBrowseActivity; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.TDDStatsActivity; +import info.nightscout.androidaps.activities.TDDStatsActivity; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventExtendedBolusChange; @@ -33,6 +33,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.SingleClickButton; @@ -87,7 +88,6 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL tempBasalCancel.setOnClickListener(this); fill.setOnClickListener(this); history.setOnClickListener(this); - history.setVisibility(MainApp.devBranch ? View.VISIBLE : View.GONE); tddStats.setOnClickListener(this); updateGUI(); @@ -132,7 +132,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL profileSwitch.setVisibility(View.GONE); } - if (MainApp.getConfigBuilder().getProfile() == null) { + if (ProfileFunctions.getInstance().getProfile() == null) { tempTarget.setVisibility(View.GONE); extendedBolus.setVisibility(View.GONE); extendedBolusCancel.setVisibility(View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java index 558a7c381c..cd649d30cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/FillDialog.java @@ -39,7 +39,7 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.NumberPicker; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java index 7a03887cf6..32f1271d82 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/dialogs/NewTempBasalDialog.java @@ -25,6 +25,7 @@ import info.nightscout.androidaps.data.Profile; 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.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.FabricPrivacy; @@ -70,7 +71,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi double tempPercentStep = pumpDescription.tempPercentStep; basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); Double currentBasal = profile != null ? profile.getBasal() : 0d; basalAbsolute = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalabsoluteinput); basalAbsolute.setParams(currentBasal, 0d, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, new DecimalFormat("0.00"), true); @@ -118,7 +119,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi final boolean setAsPercent = percentRadio.isChecked(); int durationInMinutes = SafeParse.stringToInt(duration.getText()); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java index 46c1e3666d..b4ca897f8e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Careportal/Dialogs/NewNSTreatmentDialog.java @@ -49,13 +49,14 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DefaultValueHelper; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.HardLimits; import info.nightscout.utils.JsonHelper; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.NumberPicker; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; @@ -171,7 +172,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick view.findViewById(R.id.cancel).setOnClickListener(this); // profile - profile = MainApp.getConfigBuilder().getProfile(); + profile = ProfileFunctions.getInstance().getProfile(); profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile(); if (profileStore == null) { if (options.eventType == R.id.careportal_profileswitch) { @@ -186,7 +187,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick profileSpinner.setAdapter(adapter); // set selected to actual profile for (int p = 0; p < profileList.size(); p++) { - if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName(false))) + if (profileList.get(p).equals(ProfileFunctions.getInstance().getProfileName(false))) profileSpinner.setSelection(p); } } @@ -206,12 +207,15 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick public void onItemSelected(AdapterView parent, View view, int position, long id) { double defaultDuration; double defaultTarget = 0; - if (profile != null) { + if (profile != null && editTemptarget.getValue() == bg) { defaultTarget = bg; + } else { + //prevent changes on screen rotate + defaultTarget = editTemptarget.getValue(); } boolean erase = false; - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); DefaultValueHelper helper = new DefaultValueHelper(); if (MainApp.gs(R.string.eatingsoon).equals(reasonList.get(position))) { defaultDuration = helper.determineEatingSoonTTDuration(); @@ -222,6 +226,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } else if (MainApp.gs(R.string.hypo).equals(reasonList.get(position))) { defaultDuration = helper.determineHypoTTDuration(); defaultTarget = helper.determineHypoTT(units); + } else if (editDuration.getValue() != 0) { + defaultDuration = editDuration.getValue(); } else { defaultDuration = 0; erase = true; @@ -258,7 +264,6 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true); } }; - editBg = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_bginput); editTemptarget = (NumberPicker) view.findViewById(R.id.careportal_newnstreatment_temptarget); if (profile == null) { @@ -271,9 +276,14 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, bgTextWatcher); editTemptarget.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false); } + sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { Double bg1 = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, profile.getUnits()); - editBg.setValue(bg1); + if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) { + editBg.setValue(savedInstanceState.getDouble("editBg")); + } else { + editBg.setValue(bg1); + } }); Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value(); @@ -378,6 +388,25 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick setCancelable(true); getDialog().setCanceledOnTouchOutside(false); + //recovering state if there is something + // only numberPickers and editTexts + if (savedInstanceState != null) { + editBg.setValue(savedInstanceState.getDouble("editBg")); + editTemptarget.setValue(savedInstanceState.getDouble("editTemptarget")); + notesEdit.setText(savedInstanceState.getString("notesEdit")); + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editInsulin.setValue(savedInstanceState.getDouble("editInsulin")); + editDuration.setValue(savedInstanceState.getDouble("editDuration")); + editPercent.setValue(savedInstanceState.getDouble("editPercent")); + editAbsolute.setValue(savedInstanceState.getDouble("editAbsolute")); + editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime")); + editPercentage.setValue(savedInstanceState.getDouble("editPercentage")); + editTimeshift.setValue(savedInstanceState.getDouble("editTimeshift")); + // time and date + dateButton.setText(savedInstanceState.getString("dateButton")); + timeButton.setText(savedInstanceState.getString("timeButton")); + } return view; } @@ -758,8 +787,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick profileSwitch = new ProfileSwitch(); profileSwitch.date = System.currentTimeMillis(); profileSwitch.source = Source.USER; - profileSwitch.profileName = MainApp.getConfigBuilder().getProfileName(System.currentTimeMillis(), false); - profileSwitch.profileJson = MainApp.getConfigBuilder().getProfile().getData().toString(); + profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), false); + profileSwitch.profileJson = ProfileFunctions.getInstance().getProfile().getData().toString(); profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName(); profileSwitch.durationInMinutes = duration; profileSwitch.isCPP = percentage != 100 || timeshift != 0; @@ -772,4 +801,22 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick } } + @Override + public void onSaveInstanceState(Bundle savedInstanceState) { + savedInstanceState.putString("notesEdit", notesEdit.getText().toString()); + savedInstanceState.putString("dateButton", dateButton.getText().toString()); + savedInstanceState.putString("timeButton", timeButton.getText().toString()); + savedInstanceState.putDouble("editBg", editBg.getValue()); + savedInstanceState.putDouble("editCarbs", editCarbs.getValue()); + savedInstanceState.putDouble("editInsulin", editInsulin.getValue()); + savedInstanceState.putDouble("editDuration", editDuration.getValue()); + savedInstanceState.putDouble("editPercent", editPercent.getValue()); + savedInstanceState.putDouble("editAbsolute", editAbsolute.getValue()); + savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue()); + savedInstanceState.putDouble("editTemptarget", editTemptarget.getValue()); + savedInstanceState.putDouble("editPercentage", editPercentage.getValue()); + savedInstanceState.putDouble("editTimeshift", editTimeshift.getValue()); + super.onSaveInstanceState(savedInstanceState); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java index 3e60ca2b77..3df78c9a28 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java @@ -26,7 +26,7 @@ import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.PreferencesActivity; +import info.nightscout.androidaps.activities.PreferencesActivity; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventRefreshGui; 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 886eeb3db7..d57c2346f0 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 @@ -1,35 +1,17 @@ package info.nightscout.androidaps.plugins.ConfigBuilder; -import android.content.Intent; import android.support.annotation.Nullable; -import com.crashlytics.android.answers.CustomEvent; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; -import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Config; -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; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppInitialized; -import info.nightscout.androidaps.events.EventNewBasalProfile; -import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.BgSourceInterface; -import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; @@ -38,24 +20,18 @@ import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; -import info.nightscout.androidaps.plugins.Loop.APSResult; -import info.nightscout.androidaps.plugins.Loop.LoopPlugin; -import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin; -import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.CommandQueue; -import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; -import info.nightscout.utils.ToastUtils; /** * Created by mike on 05.08.2016. */ public class ConfigBuilderPlugin extends PluginBase { - private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class); + private Logger log = LoggerFactory.getLogger(L.CONFIGBUILDER); private static ConfigBuilderPlugin configBuilderPlugin; @@ -70,15 +46,9 @@ public class ConfigBuilderPlugin extends PluginBase { private static ProfileInterface activeProfile; private static TreatmentsInterface activeTreatments; private static APSInterface activeAPS; - private static LoopPlugin activeLoop; private static InsulinInterface activeInsulin; private static SensitivityInterface activeSensitivity; - static public String nightscoutVersionName = ""; - static public Integer nightscoutVersionCode = 0; - static public String nsClientVersionName = ""; - static public Integer nsClientVersionCode = 0; - private static ArrayList pluginList; private static CommandQueue commandQueue = new CommandQueue(); @@ -119,14 +89,15 @@ public class ConfigBuilderPlugin extends PluginBase { private void setAlwaysEnabledPluginsEnabled() { for (PluginBase plugin : pluginList) { - if (plugin.pluginDescription.alwaysEnabled) plugin.setPluginEnabled(plugin.getType(), true); + if (plugin.pluginDescription.alwaysEnabled) + plugin.setPluginEnabled(plugin.getType(), true); } storeSettings("setAlwaysEnabledPluginsEnabled"); } public void storeSettings(String from) { if (pluginList != null) { - if (Config.logPrefsChange) + if (L.isEnabled(L.CONFIGBUILDER)) log.debug("Storing settings from: " + from); for (PluginBase p : pluginList) { @@ -149,16 +120,18 @@ 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)); - log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type)); + if (L.isEnabled(L.CONFIGBUILDER)) + log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type)); if (storeVisible) { String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible"; SP.putBoolean(settingVisible, p.isFragmentVisible()); - log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible()); + if (L.isEnabled(L.CONFIGBUILDER)) + log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible()); } } private void loadSettings() { - if (Config.logPrefsChange) + if (L.isEnabled(L.CONFIGBUILDER)) log.debug("Loading stored settings"); for (PluginBase p : pluginList) { PluginType type = p.getType(); @@ -179,7 +152,8 @@ public class ConfigBuilderPlugin extends PluginBase { else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) { p.setPluginEnabled(type, true); } - log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type)); + if (L.isEnabled(L.CONFIGBUILDER)) + log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type)); if (loadVisible) { String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible"; if (SP.contains(settingVisible)) @@ -187,7 +161,8 @@ public class ConfigBuilderPlugin extends PluginBase { else if (p.getType() == type && p.pluginDescription.visibleByDefault) { p.setFragmentVisible(type, true); } - log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible()); + if (L.isEnabled(L.CONFIGBUILDER)) + log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible()); } } @@ -195,10 +170,11 @@ public class ConfigBuilderPlugin extends PluginBase { private void upgradeSettings() { if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled")) return; - if (Config.logPrefsChange) + if (L.isEnabled(L.CONFIGBUILDER)) log.debug("Upgrading stored settings"); for (PluginBase p : pluginList) { - log.debug("Processing " + p.getName()); + if (L.isEnabled(L.CONFIGBUILDER)) + log.debug("Processing " + p.getName()); for (int type = 1; type < 11; type++) { PluginType newType; switch (type) { @@ -282,20 +258,21 @@ public class ConfigBuilderPlugin extends PluginBase { } void logPluginStatus() { - 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" : "") - ); - } + 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" : "") + ); + } } private void verifySelectionInCategories() { @@ -337,9 +314,6 @@ public class ConfigBuilderPlugin extends PluginBase { } this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP); - // PluginType.LOOP - activeLoop = this.determineActivePlugin(PluginType.LOOP); - // PluginType.TREATMENT activeTreatments = this.determineActivePlugin(PluginType.TREATMENT); } @@ -395,7 +369,7 @@ public class ConfigBuilderPlugin extends PluginBase { private void setFragmentVisiblities(String activePluginName, ArrayList pluginsInCategory, PluginType pluginType) { - if (Config.logConfigBuilder) + if (L.isEnabled(L.CONFIGBUILDER)) log.debug("Selected interface: " + activePluginName); for (PluginBase p : pluginsInCategory) { if (!p.getName().equals(activePluginName)) { @@ -421,247 +395,4 @@ public class ConfigBuilderPlugin extends PluginBase { return found; } - /** - * expect absolute request and allow both absolute and percent response based on pump capabilities - */ - public void applyTBRRequest(APSResult request, Profile profile, Callback callback) { - if (!request.tempBasalRequested) { - if (callback != null) { - callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run(); - } - return; - } - - PumpInterface pump = getActivePump(); - - request.rateConstraint = new Constraint<>(request.rate); - request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value(); - - if (!pump.isInitialized()) { - log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized)); - if (callback != null) { - callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); - } - return; - } - - if (pump.isSuspended()) { - log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended)); - if (callback != null) { - callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); - } - return; - } - - if (Config.logCongigBuilderActions) - log.debug("applyAPSRequest: " + request.toString()); - - long now = System.currentTimeMillis(); - TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now); - if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) { - if (activeTemp != null) { - if (Config.logCongigBuilderActions) - log.debug("applyAPSRequest: cancelTempBasal()"); - getCommandQueue().cancelTempBasal(false, callback); - } else { - if (Config.logCongigBuilderActions) - log.debug("applyAPSRequest: Basal set correctly"); - if (callback != null) { - callback.result(new PumpEnactResult().absolute(request.rate).duration(0) - .enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run(); - } - } - } else if (activeTemp != null - && activeTemp.getPlannedRemainingMinutes() > 5 - && request.duration - activeTemp.getPlannedRemainingMinutes() < 30 - && Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) { - if (Config.logCongigBuilderActions) - log.debug("applyAPSRequest: Temp basal set correctly"); - if (callback != null) { - callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile)) - .enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes()) - .comment(MainApp.gs(R.string.let_temp_basal_run))).run(); - } - } else { - if (Config.logCongigBuilderActions) - log.debug("applyAPSRequest: setTempBasalAbsolute()"); - getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback); - } - } - - public void applySMBRequest(APSResult request, Callback callback) { - if (!request.bolusRequested) { - return; - } - - long lastBolusTime = activeTreatments.getLastBolusTime(); - if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { - log.debug("SMB requested but still in 3 min interval"); - if (callback != null) { - callback.result(new PumpEnactResult() - .comment(MainApp.gs(R.string.smb_frequency_exceeded)) - .enacted(false).success(false)).run(); - } - return; - } - - PumpInterface pump = getActivePump(); - - if (!pump.isInitialized()) { - log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized)); - if (callback != null) { - callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); - } - return; - } - - if (pump.isSuspended()) { - log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended)); - if (callback != null) { - callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); - } - return; - } - - if (Config.logCongigBuilderActions) - log.debug("applySMBRequest: " + request.toString()); - - // deliver SMB - DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); - detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime(); - detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS; - detailedBolusInfo.insulin = request.smb; - detailedBolusInfo.isSMB = true; - detailedBolusInfo.source = Source.USER; - detailedBolusInfo.deliverAt = request.deliverAt; - if (Config.logCongigBuilderActions) - log.debug("applyAPSRequest: bolus()"); - getCommandQueue().bolus(detailedBolusInfo, callback); - } - - @Subscribe - public void onProfileSwitch(EventProfileSwitchChange ignored) { - getCommandQueue().setProfile(getProfile(), new Callback() { - @Override - public void run() { - if (!result.success) { - Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); - i.putExtra("soundid", R.raw.boluserror); - i.putExtra("status", result.comment); - i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile)); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); - } - MainApp.bus().post(new EventNewBasalProfile()); - } - }); - } - - public String getProfileName() { - return getProfileName(System.currentTimeMillis()); - } - - public String getProfileName(boolean customized) { - return getProfileName(System.currentTimeMillis(), customized); - } - - public String getProfileName(long time) { - return getProfileName(time, true); - } - - public String getProfileName(long time, boolean customized) { - ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); - if (profileSwitch != null) { - if (profileSwitch.profileJson != null) { - return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName; - } else { - ProfileStore profileStore = activeProfile.getProfile(); - if (profileStore != null) { - Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName); - if (profile != null) - return profileSwitch.profileName; - } - } - } - return MainApp.gs(R.string.noprofileselected); - } - - public boolean isProfileValid(String from) { - return getProfile() != null && getProfile().isValid(from); - } - - @Nullable - public Profile getProfile() { - return getProfile(System.currentTimeMillis()); - } - - public String getProfileUnits() { - Profile profile = getProfile(); - return profile != null ? profile.getUnits() : Constants.MGDL; - } - - @Nullable - public Profile getProfile(long time) { - if (activeTreatments == null) { - log.debug("getProfile activeTreatments == null: returning null"); - return null; //app not initialized - } - //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time)); - ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); - if (profileSwitch != null) { - if (profileSwitch.profileJson != null) { - return profileSwitch.getProfileObject(); - } else if (activeProfile.getProfile() != null) { - Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName); - if (profile != null) - return profile; - } - } - if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) { - FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError") - .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) - .putCustomAttribute("version", BuildConfig.VERSION) - .putCustomAttribute("time", time) - .putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString()) - ); - } - log.debug("getProfile at the end: returning null"); - return null; - } - - public void disconnectPump(int durationInMinutes, Profile profile) { - LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L); - getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() { - @Override - public void run() { - if (!result.success) { - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror)); - } - } - }); - if (getActivePump().getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) { - getCommandQueue().cancelExtended(new Callback() { - @Override - public void run() { - if (!result.success) { - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror)); - } - } - }); - } - NSUpload.uploadOpenAPSOffline(durationInMinutes); - } - - public void suspendLoop(int durationInMinutes) { - LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000); - getCommandQueue().cancelTempBasal(true, new Callback() { - @Override - public void run() { - if (!result.success) { - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror)); - } - } - }); - NSUpload.uploadOpenAPSOffline(durationInMinutes); - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java index 7a4e99b584..35effd4249 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java @@ -6,17 +6,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; -import java.util.Date; import java.util.List; import info.nightscout.androidaps.data.DetailedBolusInfo; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 08.08.2017. */ public class DetailedBolusInfoStorage { - private static Logger log = LoggerFactory.getLogger(DetailedBolusInfoStorage.class); + private static Logger log = LoggerFactory.getLogger(L.PUMP); private static List store = new ArrayList<>(); public static synchronized void add(DetailedBolusInfo detailedBolusInfo) { @@ -29,7 +29,8 @@ public class DetailedBolusInfoStorage { DetailedBolusInfo found = null; for (int i = 0; i < store.size(); i++) { long infoTime = store.get(i).date; - log.debug("Existing bolus info: " + store.get(i)); + if (L.isEnabled(L.PUMP)) + log.debug("Existing bolus info: " + store.get(i)); if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { found = store.get(i); break; @@ -42,7 +43,8 @@ public class DetailedBolusInfoStorage { for (int i = 0; i < store.size(); i++) { long infoTime = store.get(i).date; if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { - log.debug("Removing bolus info: " + store.get(i)); + if (L.isEnabled(L.PUMP)) + log.debug("Removing bolus info: " + store.get(i)); store.remove(i); break; } 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 new file mode 100644 index 0000000000..8eff3c525f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ProfileFunctions.java @@ -0,0 +1,142 @@ +package info.nightscout.androidaps.plugins.ConfigBuilder; + +import android.content.Intent; +import android.support.annotation.Nullable; + +import com.crashlytics.android.answers.CustomEvent; +import com.squareup.otto.Subscribe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.BuildConfig; +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.data.ProfileStore; +import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.events.EventNewBasalProfile; +import info.nightscout.androidaps.events.EventProfileSwitchChange; +import info.nightscout.androidaps.interfaces.ProfileInterface; +import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; +import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; +import info.nightscout.androidaps.queue.Callback; +import info.nightscout.utils.FabricPrivacy; + +public class ProfileFunctions { + private static Logger log = LoggerFactory.getLogger(L.PROFILE); + + private static ProfileFunctions profileFunctions = null; + + public static ProfileFunctions getInstance() { + if (profileFunctions == null) + profileFunctions = new ProfileFunctions(); + return profileFunctions; + } + + static { + ProfileFunctions.getInstance(); // register to bus at start + } + + ProfileFunctions() { + MainApp.bus().register(this); + } + + @Subscribe + public void onProfileSwitch(EventProfileSwitchChange ignored) { + if (L.isEnabled(L.PROFILE)) + log.debug("onProfileSwitch"); + MainApp.getConfigBuilder().getCommandQueue().setProfile(getProfile(), new Callback() { + @Override + public void run() { + if (!result.success) { + Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); + i.putExtra("soundid", R.raw.boluserror); + i.putExtra("status", result.comment); + i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile)); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + MainApp.instance().startActivity(i); + } + MainApp.bus().post(new EventNewBasalProfile()); + } + }); + } + + public String getProfileName() { + return getProfileName(System.currentTimeMillis()); + } + + public String getProfileName(boolean customized) { + return getProfileName(System.currentTimeMillis(), customized); + } + + public String getProfileName(long time) { + return getProfileName(time, true); + } + + public String getProfileName(long time, boolean customized) { + TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); + ProfileInterface activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface(); + + ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); + if (profileSwitch != null) { + if (profileSwitch.profileJson != null) { + return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName; + } else { + ProfileStore profileStore = activeProfile.getProfile(); + if (profileStore != null) { + Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName); + if (profile != null) + return profileSwitch.profileName; + } + } + } + return MainApp.gs(R.string.noprofileselected); + } + + public boolean isProfileValid(String from) { + return getProfile() != null && getProfile().isValid(from); + } + + @Nullable + public Profile getProfile() { + return getProfile(System.currentTimeMillis()); + } + + public String getProfileUnits() { + Profile profile = getProfile(); + return profile != null ? profile.getUnits() : Constants.MGDL; + } + + @Nullable + public Profile getProfile(long time) { + TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); + ProfileInterface activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface(); + + //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time)); + ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time); + if (profileSwitch != null) { + if (profileSwitch.profileJson != null) { + return profileSwitch.getProfileObject(); + } else if (activeProfile.getProfile() != null) { + Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName); + if (profile != null) + return profile; + } + } + if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) { + FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError") + .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) + .putCustomAttribute("version", BuildConfig.VERSION) + .putCustomAttribute("time", time) + .putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString()) + ); + } + log.error("getProfile at the end: returning null"); + return null; + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java index 2f896ba91b..3e33b9e926 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java @@ -1,18 +1,15 @@ package info.nightscout.androidaps.plugins.ConstraintsObjectives; -import android.animation.LayoutTransition; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.NonNull; -import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.RecyclerView; import android.text.Html; -import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -21,28 +18,15 @@ import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.TextView; - -import com.squareup.otto.Subscribe; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.Date; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventConfigBuilderChange; -import info.nightscout.androidaps.events.EventNewBG; -import info.nightscout.androidaps.events.EventProfileSwitchChange; -import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; -import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved; import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.utils.FabricPrivacy; public class ObjectivesFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class); - RecyclerView recyclerView; CheckBox enableFake; TextView reset; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java index a67f694eb8..df62fd3eb9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java @@ -15,6 +15,7 @@ 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.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved; import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; @@ -32,7 +33,7 @@ import info.nightscout.utils.SP; * Created by mike on 05.08.2016. */ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface { - private static Logger log = LoggerFactory.getLogger(ObjectivesPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.OBJECTIVES); private static ObjectivesPlugin objectivesPlugin; @@ -94,7 +95,7 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface SP.putBoolean("Objectives" + "bgIsAvailableInNS", bgIsAvailableInNS); SP.putBoolean("Objectives" + "pumpStatusIsAvailableInNS", pumpStatusIsAvailableInNS); SP.putString("Objectives" + "manualEnacts", Integer.toString(manualEnacts)); - if (Config.logPrefsChange) + if (L.isEnabled(L.OBJECTIVES)) log.debug("Objectives stored"); MainApp.bus().post(new EventObjectivesSaved()); } @@ -107,7 +108,7 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface } catch (Exception e) { log.error("Unhandled exception", e); } - if (Config.logPrefsChange) + if (L.isEnabled(L.OBJECTIVES)) log.debug("Objectives loaded"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodFragment.java index 1acf6ea083..677fac5fb2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodFragment.java @@ -33,7 +33,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SpinnerHelper; /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java index 44b96850ae..c864c623db 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Food/FoodService.java @@ -33,13 +33,14 @@ import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventNsFood; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 24.09.2017. */ public class FoodService extends OrmLiteBaseService { - private static Logger log = LoggerFactory.getLogger(FoodService.class); + private Logger log = LoggerFactory.getLogger(L.DATAFOOD); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledFoodEventPost = null; @@ -110,7 +111,8 @@ public class FoodService extends OrmLiteBaseService { public void onCreate() { super.onCreate(); try { - log.info("onCreate"); + if (L.isEnabled(L.DATAFOOD)) + log.info("onCreate"); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); } catch (SQLException e) { log.error("Can't create database", e); @@ -122,7 +124,8 @@ public class FoodService extends OrmLiteBaseService { if (oldVersion == 7 && newVersion == 8) { log.debug("Upgrading database from v7 to v8"); } else { - log.info("onUpgrade"); + if (L.isEnabled(L.DATAFOOD)) + log.info("onUpgrade"); // this.resetFood(); } } @@ -161,7 +164,8 @@ public class FoodService extends OrmLiteBaseService { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventFoodChange"); + if (L.isEnabled(L.DATAFOOD)) + log.debug("Firing EventFoodChange"); MainApp.bus().post(event); callback.setPost(null); } @@ -271,7 +275,8 @@ public class FoodService extends OrmLiteBaseService { public void deleteByNSId(String _id) throws SQLException { Food stored = this.findByNSId(_id); if (stored != null) { - log.debug("FOOD: Removing Food record from database: " + stored.toString()); + if (L.isEnabled(L.DATAFOOD)) + log.debug("Removing Food record from database: " + stored.toString()); this.delete(stored); } } @@ -324,7 +329,8 @@ public class FoodService extends OrmLiteBaseService { public void createOrUpdate(Food food) { try { this.getDao().createOrUpdate(food); - log.debug("FOOD: Created or Updated: " + food.toString()); + if (L.isEnabled(L.DATAFOOD)) + log.debug("Created or Updated: " + food.toString()); } catch (SQLException e) { log.error("Unable to createOrUpdate Food", e); } @@ -334,7 +340,8 @@ public class FoodService extends OrmLiteBaseService { public void create(Food food) { try { this.getDao().create(food); - log.debug("FOOD: New record: " + food.toString()); + if (L.isEnabled(L.DATAFOOD)) + log.debug("New record: " + food.toString()); } catch (SQLException e) { log.error("Unable to create Food", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java index 5d4d1187ac..a2d80efd68 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Insulin/InsulinOrefBasePlugin.java @@ -5,6 +5,7 @@ import com.squareup.otto.Bus; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.PluginBase; @@ -61,7 +62,7 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli } public double getUserDefinedDia() { - return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : MIN_DIA; + return ProfileFunctions.getInstance().getProfile() != null ? ProfileFunctions.getInstance().getProfile().getDia() : MIN_DIA; } public Iob iobCalcForTreatment(Treatment treatment, long time) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java index dd2c50d8c9..60a5851011 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensData.java @@ -12,6 +12,8 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; @@ -26,7 +28,7 @@ import info.nightscout.utils.SP; */ public class AutosensData implements DataPointWithLabelInterface { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); public void setChartTime(long chartTime) { this.chartTime = chartTime; @@ -44,11 +46,12 @@ public class AutosensData implements DataPointWithLabelInterface { remaining = t.carbs; if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME); - Profile profile = MainApp.getConfigBuilder().getProfile(t.date); + Profile profile = ProfileFunctions.getInstance().getProfile(t.date); double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits()); double ic = profile.getIc(t.date); min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; - log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); } else { min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); } @@ -107,7 +110,8 @@ public class AutosensData implements DataPointWithLabelInterface { activeCarbsList.remove(i--); if (c.remaining > 0) cob -= c.remaining; - log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString()); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java index c83095e620..7bd01fa7b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/AutosensResult.java @@ -5,11 +5,13 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 06.01.2017. */ public class AutosensResult { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); //default values to show when autosens algorithm is not called public double ratio = 1d; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java index 096668b996..07feacadff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobCalculatorPlugin.java @@ -15,7 +15,6 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -32,7 +31,9 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin; @@ -48,7 +49,7 @@ import static info.nightscout.utils.DateUtil.now; */ public class IobCobCalculatorPlugin extends PluginBase { - private Logger log = LoggerFactory.getLogger("AUTOSENS"); + private Logger log = LoggerFactory.getLogger(L.AUTOSENS); private static IobCobCalculatorPlugin plugin = null; @@ -98,6 +99,10 @@ public class IobCobCalculatorPlugin extends PluginBase { return autosensDataTable; } + public List getBgReadings() { + return bgReadings; + } + public List getBucketedData() { return bucketed_data; } @@ -107,13 +112,15 @@ public class IobCobCalculatorPlugin extends PluginBase { //log.debug("Locking getBucketedData"); synchronized (dataLock) { if (bucketed_data == null) { - log.debug("No bucketed data available"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No bucketed data available"); return null; } int index = indexNewerThan(fromTime); if (index > -1) { List part = bucketed_data.subList(0, index); - log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size()); return part; } } @@ -136,13 +143,11 @@ public class IobCobCalculatorPlugin extends PluginBase { return rounded; } - void loadBgData(long start) { - if (start < oldestDataAvailable()) { - start = oldestDataAvailable(); - log.debug("Limiting BG data to oldest data available: " + DateUtil.dateAndTimeString(start)); - } - bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (start - 60 * 60 * 1000L * (24 + dia)), false); - log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start)); + void loadBgData(long now) { + long start = (long) (now - 60 * 60 * 1000L * (24 + dia)); + bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false); + if (L.isEnabled(L.AUTOSENS)) + log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now)); } private boolean isAbout5minData() { @@ -158,13 +163,15 @@ public class IobCobCalculatorPlugin extends PluginBase { totalDiff += diff; if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30 log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false); - return false; + if (L.isEnabled(L.AUTOSENS)) + return false; } } double intervals = totalDiff / (5 * 60 * 1000d); double variability = Math.abs(intervals - Math.round(intervals)); boolean is5mindata = variability < 0.02; - log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata); return is5mindata; } } @@ -291,15 +298,24 @@ public class IobCobCalculatorPlugin extends PluginBase { //log.error("***** Average"); } } - log.debug("Bucketed data created. Size: " + bucketed_data.size()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Bucketed data created. Size: " + bucketed_data.size()); } - public long oldestDataAvailable() { - long now = System.currentTimeMillis(); + public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) { + Profile profile = ProfileFunctions.getInstance().getProfile(from); + double dia = Constants.defaultDIA; + if (profile != null) dia = profile.getDia(); long oldestDataAvailable = TreatmentsPlugin.getPlugin().oldestDataAvailable(); - long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - T.hours(1).msecs() * (24 + MainApp.getConfigBuilder().getProfile().getDia()))); - log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); + long getBGDataFrom; + if (limitDataToOldestAvailable) { + getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia))); + if (getBGDataFrom == oldestDataAvailable) + if (L.isEnabled(L.AUTOSENS)) + log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); + } else + getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia)); return getBGDataFrom; } @@ -403,13 +419,15 @@ public class IobCobCalculatorPlugin extends PluginBase { @Nullable public AutosensData getLastAutosensDataSynchronized(String reason) { - if (thread != null && thread.isAlive()) { - log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason); + if (thread != null && thread.isAlive()) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason); try { thread.join(5000); } catch (InterruptedException ignored) { } - log.debug("AUTOSENSDATA finished waiting for calculation thread: " + reason); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA finished waiting for calculation thread: " + reason); } synchronized (dataLock) { return getLastAutosensData(reason); @@ -447,7 +465,8 @@ public class IobCobCalculatorPlugin extends PluginBase { @Nullable public AutosensData getLastAutosensData(String reason) { if (autosensDataTable.size() < 1) { - log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")"); return null; } AutosensData data; @@ -461,10 +480,12 @@ public class IobCobCalculatorPlugin extends PluginBase { return null; } if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) { - log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time)); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time)); return null; } else { - log.debug("AUTOSENSDATA (" + reason + ") " + data.toString()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA (" + reason + ") " + data.toString()); return data; } } @@ -510,7 +531,7 @@ public class IobCobCalculatorPlugin extends PluginBase { public AutosensResult detectSensitivityWithLock(long fromTime, long toTime) { synchronized (dataLock) { - return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime); + return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(this, fromTime, toTime); } } @@ -526,41 +547,46 @@ public class IobCobCalculatorPlugin extends PluginBase { @SuppressWarnings("unused") public void onEventAppInitialized(EventAppInitialized ev) { if (this != getPlugin()) { - log.debug("Ignoring event for non default instance"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); return; } - runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, ev); + runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev); } @Subscribe @SuppressWarnings("unused") public void onEventNewBG(EventNewBG ev) { if (this != getPlugin()) { - log.debug("Ignoring event for non default instance"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); return; } stopCalculation("onEventNewBG"); - runCalculation("onEventNewBG", System.currentTimeMillis(), true, ev); + runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, ev); } - private void stopCalculation(String from) { + public void stopCalculation(String from) { if (thread != null && thread.getState() != Thread.State.TERMINATED) { stopCalculationTrigger = true; - log.debug("Stopping calculation thread: " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Stopping calculation thread: " + from); while (thread.getState() != Thread.State.TERMINATED) { SystemClock.sleep(100); } - log.debug("Calculation thread stopped: " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Calculation thread stopped: " + from); } } - public void runCalculation(String from, long start, boolean bgDataReload, Event cause) { - log.debug("Starting calculation thread: " + from); + public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end)); if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) - thread = new IobCobOref1Thread(this, from, start, bgDataReload, cause); + thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); else - thread = new IobCobThread(this, from, start, bgDataReload, cause); + thread = new IobCobThread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); thread.start(); } } @@ -568,12 +594,13 @@ public class IobCobCalculatorPlugin extends PluginBase { @Subscribe public void onNewProfile(EventNewBasalProfile ev) { if (this != getPlugin()) { - log.debug("Ignoring event for non default instance"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); return; } if (MainApp.getConfigBuilder() == null) return; // app still initializing - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return; // app still initializing dia = profile.getDia(); @@ -582,17 +609,19 @@ public class IobCobCalculatorPlugin extends PluginBase { } stopCalculation("onNewProfile"); synchronized (dataLock) { - log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } - runCalculation("onNewProfile", System.currentTimeMillis(), false, ev); + runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev); } @Subscribe public void onEventPreferenceChange(EventPreferenceChange ev) { if (this != getPlugin()) { - log.debug("Ignoring event for non default instance"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); return; } if (ev.isChanged(R.string.key_openapsama_autosens_period) || @@ -605,34 +634,38 @@ public class IobCobCalculatorPlugin extends PluginBase { ) { stopCalculation("onEventPreferenceChange"); synchronized (dataLock) { - log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } - runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, ev); + runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, ev); } } @Subscribe public void onEventConfigBuilderChange(EventConfigBuilderChange ev) { if (this != getPlugin()) { - log.debug("Ignoring event for non default instance"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); return; } stopCalculation("onEventConfigBuilderChange"); synchronized (dataLock) { - log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } - runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, ev); + runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, ev); } // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated @Subscribe public void onEventNewHistoryData(EventNewHistoryData ev) { if (this != getPlugin()) { - log.debug("Ignoring event for non default instance"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); return; } //log.debug("Locking onNewHistoryData"); @@ -640,10 +673,11 @@ public class IobCobCalculatorPlugin extends PluginBase { synchronized (dataLock) { // clear up 5 min back for proper COB calculation long time = ev.time - 5 * 60 * 1000L; - log.debug("Invalidating cached data to: " + new Date(time).toLocaleString()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data to: " + new Date(time).toLocaleString()); for (int index = iobTable.size() - 1; index >= 0; index--) { if (iobTable.keyAt(index) > time) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); iobTable.removeAt(index); } else { @@ -652,7 +686,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } for (int index = autosensDataTable.size() - 1; index >= 0; index--) { if (autosensDataTable.keyAt(index) > time) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString()); autosensDataTable.removeAt(index); } else { @@ -661,7 +695,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } for (int index = basalDataTable.size() - 1; index >= 0; index--) { if (basalDataTable.keyAt(index) > time) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString()); basalDataTable.removeAt(index); } else { @@ -669,13 +703,14 @@ public class IobCobCalculatorPlugin extends PluginBase { } } } - runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, ev); + runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, true, ev); //log.debug("Releasing onNewHistoryData"); } public void clearCache() { synchronized (dataLock) { - log.debug("Clearing cached data."); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Clearing cached data."); iobTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java index d10d0ebe29..3dbd518c24 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobOref1Thread.java @@ -17,7 +17,6 @@ import java.util.GregorianCalendar; import java.util.List; import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -26,6 +25,8 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; @@ -43,24 +44,26 @@ import static java.util.Calendar.MINUTE; */ public class IobCobOref1Thread extends Thread { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); private final Event cause; private IobCobCalculatorPlugin iobCobCalculatorPlugin; private boolean bgDataReload; + private boolean limitDataToOldestAvailable; private String from; - private long start; + private long end; private PowerManager.WakeLock mWakeLock; - public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long start, boolean bgDataReload, Event cause) { + public IobCobOref1Thread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); this.iobCobCalculatorPlugin = plugin; this.bgDataReload = bgDataReload; + this.limitDataToOldestAvailable = limitDataToOldestAvailable; this.from = from; this.cause = cause; - this.start = start; + this.end = end; PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); @@ -70,34 +73,39 @@ public class IobCobOref1Thread extends Thread { public final void run() { mWakeLock.acquire(); try { - log.debug("AUTOSENSDATA thread started: " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA thread started: " + from); if (MainApp.getConfigBuilder() == null) { - log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); return; // app still initializing } - if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) { - log.debug("Aborting calculation thread (No profile): " + from); + if (!ProfileFunctions.getInstance().isProfileValid("IobCobThread")) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (No profile): " + from); return; // app still initializing } //log.debug("Locking calculateSensitivityData"); - long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); + long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable); synchronized (iobCobCalculatorPlugin.dataLock) { if (bgDataReload) { - iobCobCalculatorPlugin.loadBgData(start); + iobCobCalculatorPlugin.loadBgData(end); iobCobCalculatorPlugin.createBucketedData(); } List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { - log.debug("Aborting calculation thread (No bucketed data available): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (No bucketed data available): " + from); return; } long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); AutosensData previous = autosensDataTable.get(prevDataTime); // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { @@ -106,7 +114,8 @@ public class IobCobOref1Thread extends Thread { if (iobCobCalculatorPlugin.stopCalculationTrigger) { iobCobCalculatorPlugin.stopCalculationTrigger = false; - log.debug("Aborting calculation thread (trigger): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (trigger): " + from); return; } // check if data already exists @@ -121,13 +130,14 @@ public class IobCobOref1Thread extends Thread { continue; } - Profile profile = MainApp.getConfigBuilder().getProfile(bgTime); + Profile profile = ProfileFunctions.getInstance().getProfile(bgTime); if (profile == null) { - log.debug("Aborting calculation thread (no profile): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (no profile): " + from); return; // profile not set yet } - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); @@ -166,10 +176,10 @@ public class IobCobOref1Thread extends Thread { // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; - AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); + AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); if (hourAgoData != null) { int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()); int past = 1; try { @@ -185,7 +195,7 @@ public class IobCobOref1Thread extends Thread { minDeviation = ad.avgDeviation; } - //if (Config.logAutosensData) + //if (Config.isEnabled(L.AUTOSENS)) // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); } } catch (Exception e) { @@ -338,13 +348,13 @@ public class IobCobOref1Thread extends Thread { previous = autosensData; if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); - if (Config.logAutosensData) - log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Sensitivity result: " + sensitivity.toString()); autosensData.autosensResult = sensitivity; - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(autosensData.toString()); } } @@ -355,7 +365,8 @@ public class IobCobOref1Thread extends Thread { } finally { mWakeLock.release(); MainApp.bus().post(new EventIobCalculationProgress("")); - log.debug("AUTOSENSDATA thread ended: " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA thread ended: " + from); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java index d60efb5bc6..5ec09301c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/IobCobThread.java @@ -15,7 +15,6 @@ import java.util.Date; import java.util.List; import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -24,6 +23,8 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; @@ -42,24 +43,26 @@ import static info.nightscout.utils.DateUtil.now; */ public class IobCobThread extends Thread { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); private final Event cause; private IobCobCalculatorPlugin iobCobCalculatorPlugin; private boolean bgDataReload; + private boolean limitDataToOldestAvailable; private String from; - private long start; + private long end; private PowerManager.WakeLock mWakeLock; - public IobCobThread(IobCobCalculatorPlugin plugin, String from, long start, boolean bgDataReload, Event cause) { + public IobCobThread(IobCobCalculatorPlugin plugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); this.iobCobCalculatorPlugin = plugin; this.bgDataReload = bgDataReload; + this.limitDataToOldestAvailable = limitDataToOldestAvailable; this.from = from; this.cause = cause; - this.start = start; + this.end = end; PowerManager powerManager = (PowerManager) MainApp.instance().getApplicationContext().getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "iobCobThread"); @@ -69,34 +72,39 @@ public class IobCobThread extends Thread { public final void run() { mWakeLock.acquire(); try { - log.debug("AUTOSENSDATA thread started: " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA thread started: " + from); if (MainApp.getConfigBuilder() == null) { - log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (ConfigBuilder not ready): " + from); return; // app still initializing } - if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) { - log.debug("Aborting calculation thread (No profile): " + from); + if (!ProfileFunctions.getInstance().isProfileValid("IobCobThread")) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (No profile): " + from); return; // app still initializing } //log.debug("Locking calculateSensitivityData"); - long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); + long oldestTimeWithData = iobCobCalculatorPlugin.calculateDetectionStart(end, limitDataToOldestAvailable); synchronized (iobCobCalculatorPlugin.dataLock) { if (bgDataReload) { - iobCobCalculatorPlugin.loadBgData(start); + iobCobCalculatorPlugin.loadBgData(end); iobCobCalculatorPlugin.createBucketedData(); } List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { - log.debug("Aborting calculation thread (No bucketed data available): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (No bucketed data available): " + from); return; } long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); AutosensData previous = autosensDataTable.get(prevDataTime); // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { @@ -105,7 +113,8 @@ public class IobCobThread extends Thread { if (iobCobCalculatorPlugin.stopCalculationTrigger) { iobCobCalculatorPlugin.stopCalculationTrigger = false; - log.debug("Aborting calculation thread (trigger): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (trigger): " + from); return; } // check if data already exists @@ -120,13 +129,14 @@ public class IobCobThread extends Thread { continue; } - Profile profile = MainApp.getConfigBuilder().getProfile(bgTime); + Profile profile = ProfileFunctions.getInstance().getProfile(bgTime); if (profile == null) { - log.debug("Aborting calculation thread (no profile): " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Aborting calculation thread (no profile): " + from); return; // profile not set yet } - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); @@ -165,10 +175,10 @@ public class IobCobThread extends Thread { // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; - AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago); + AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); if (hourAgoData != null) { int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString()); int past = 1; try { @@ -184,7 +194,7 @@ public class IobCobThread extends Thread { minDeviation = ad.avgDeviation; } - //if (Config.logAutosensData) + //if (Config.isEnabled(L.AUTOSENS)) // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation); } } catch (Exception e) { @@ -265,13 +275,13 @@ public class IobCobThread extends Thread { previous = autosensData; if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); - if (Config.logAutosensData) - log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Sensitivity result: " + sensitivity.toString()); autosensData.autosensResult = sensitivity; - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(autosensData.toString()); } } @@ -282,7 +292,8 @@ public class IobCobThread extends Thread { } finally { mWakeLock.release(); MainApp.bus().post(new EventIobCalculationProgress("")); - log.debug("AUTOSENSDATA thread ended: " + from); + if (L.isEnabled(L.AUTOSENS)) + log.debug("AUTOSENSDATA thread ended: " + from); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java index ce63ad67e5..8ea19fe8a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java @@ -18,6 +18,7 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.utils.DecimalFormatter; @@ -25,7 +26,7 @@ import info.nightscout.utils.DecimalFormatter; * Created by mike on 09.06.2016. */ public class APSResult { - private static Logger log = LoggerFactory.getLogger(APSResult.class); + private static Logger log = LoggerFactory.getLogger(L.APS); public long date = 0; public String reason; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java index acf59865d1..2c2bb1a2ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java @@ -1,17 +1,11 @@ package info.nightscout.androidaps.plugins.Loop; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; - 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.Services.Intents; -import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; +import info.nightscout.androidaps.logging.L; /* { @@ -371,7 +365,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; */ public class DeviceStatus { - private static Logger log = LoggerFactory.getLogger(DeviceStatus.class); + private static Logger log = LoggerFactory.getLogger(L.APS); public String device = null; public JSONObject pump = null; @@ -381,12 +375,12 @@ public class DeviceStatus { public int uploaderBattery = 0; public String created_at = null; - public JSONObject mongoRecord () { + public JSONObject mongoRecord() { JSONObject record = new JSONObject(); try { - if (device != null) record.put("device" , device); - if (pump != null) record.put("pump" , pump); + if (device != null) record.put("device", device); + if (pump != null) record.put("pump", pump); if (suggested != null) { JSONObject openaps = new JSONObject(); if (enacted != null) openaps.put("enacted", enacted); @@ -395,7 +389,7 @@ public class DeviceStatus { record.put("openaps", openaps); } if (uploaderBattery != 0) record.put("uploaderBattery", uploaderBattery); - if (created_at != null) record.put("created_at" , created_at); + if (created_at != null) record.put("created_at", created_at); } catch (JSONException e) { log.error("Unhandled exception", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java index 7fa810f8c0..0c0e31fb03 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java @@ -28,8 +28,6 @@ import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.utils.FabricPrivacy; public class LoopFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(LoopFragment.class); - @BindView(R.id.loop_run) Button runNowButton; @BindView(R.id.loop_lastrun) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java index 480646ccfc..d82b010450 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java @@ -21,47 +21,53 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; 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.PumpEnactResult; import info.nightscout.androidaps.db.BgReading; +import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.db.Source; +import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNewBG; -import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.interfaces.APSInterface; 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.interfaces.PumpInterface; +import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; import info.nightscout.utils.SP; +import info.nightscout.utils.ToastUtils; /** * Created by mike on 05.08.2016. */ public class LoopPlugin extends PluginBase { - private static Logger log = LoggerFactory.getLogger(LoopPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.APS); - public static final String CHANNEL_ID = "AndroidAPS-Openloop"; + private static final String CHANNEL_ID = "AndroidAPS-Openloop"; - long lastBgTriggeredRun = 0; + private long lastBgTriggeredRun = 0; - protected static LoopPlugin loopPlugin; + private static LoopPlugin loopPlugin; @NonNull public static LoopPlugin getPlugin() { @@ -132,15 +138,15 @@ public class LoopPlugin extends PluginBase { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); return pump == null || pump.getPumpDescription().isTempBasalCapable; } - + /** * This method is triggered once autosens calculation has completed, so the LoopPlugin * has current data to work with. However, autosens calculation can be triggered by multiple * sources and currently only a new BG should trigger a loop run. Hence we return early if * the event causing the calculation is not EventNewBg. - * - * Callers of {@link info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin#runCalculation(String, long, boolean, Event)} - * are sources triggering a calculation which triggers this method upon completion. + *

+ * Callers of {@link info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin#runCalculation(String, long, boolean, Event)} + * are sources triggering a calculation which triggers this method upon completion. */ @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { @@ -249,19 +255,20 @@ public class LoopPlugin extends PluginBase { return isDisconnected; } - public synchronized void invoke(String initiator, boolean allowNotification){ + public synchronized void invoke(String initiator, boolean allowNotification) { invoke(initiator, allowNotification, false); } public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) { try { - if (Config.logFunctionCalls) + if (L.isEnabled(L.APS)) log.debug("invoke from " + initiator); Constraint loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed(); if (!loopEnabled.value()) { String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); - log.debug(message); + if (L.isEnabled(L.APS)) + log.debug(message); MainApp.bus().post(new EventLoopSetLastRunGui(message)); return; } @@ -271,10 +278,11 @@ public class LoopPlugin extends PluginBase { if (!isEnabled(PluginType.LOOP)) return; - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); - if (!MainApp.getConfigBuilder().isProfileValid("Loop")) { - log.debug(MainApp.gs(R.string.noprofileselected)); + if (!ProfileFunctions.getInstance().isProfileValid("Loop")) { + if (L.isEnabled(L.APS)) + log.debug(MainApp.gs(R.string.noprofileselected)); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected))); return; } @@ -304,7 +312,8 @@ public class LoopPlugin extends PluginBase { // safety check for multiple SMBs long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { - log.debug("SMB requsted but still in 3 min interval"); + if (L.isEnabled(L.APS)) + log.debug("SMB requsted but still in 3 min interval"); resultAfterConstraints.smb = 0; } @@ -319,13 +328,15 @@ public class LoopPlugin extends PluginBase { NSUpload.uploadDeviceStatus(); if (isSuspended()) { - log.debug(MainApp.gs(R.string.loopsuspended)); + if (L.isEnabled(L.APS)) + log.debug(MainApp.gs(R.string.loopsuspended)); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended))); return; } if (pump.isSuspended()) { - log.debug(MainApp.gs(R.string.pumpsuspended)); + if (L.isEnabled(L.APS)) + log.debug(MainApp.gs(R.string.pumpsuspended)); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended))); return; } @@ -344,13 +355,13 @@ public class LoopPlugin extends PluginBase { lastRun.smbSetByPump = waiting; MainApp.bus().post(new EventLoopUpdateGui()); FabricPrivacy.getInstance().logCustom(new CustomEvent("APSRequest")); - MainApp.getConfigBuilder().applyTBRRequest(resultAfterConstraints, profile, new Callback() { + applyTBRRequest(resultAfterConstraints, profile, new Callback() { @Override public void run() { if (result.enacted || result.success) { lastRun.tbrSetByPump = result; lastRun.lastEnact = lastRun.lastAPSRun; - MainApp.getConfigBuilder().applySMBRequest(resultAfterConstraints, new Callback() { + applySMBRequest(resultAfterConstraints, new Callback() { @Override public void run() { //Callback is only called if a bolus was acutally requested @@ -412,9 +423,173 @@ public class LoopPlugin extends PluginBase { MainApp.bus().post(new EventLoopUpdateGui()); } finally { - if (Config.logFunctionCalls) + if (L.isEnabled(L.APS)) log.debug("invoke end"); } } + /** + * expect absolute request and allow both absolute and percent response based on pump capabilities + */ + public void applyTBRRequest(APSResult request, Profile profile, Callback callback) { + if (!request.tempBasalRequested) { + if (callback != null) { + callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run(); + } + return; + } + + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); + TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); + + request.rateConstraint = new Constraint<>(request.rate); + request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value(); + + if (!pump.isInitialized()) { + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized)); + if (callback != null) { + callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); + } + return; + } + + if (pump.isSuspended()) { + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended)); + if (callback != null) { + callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); + } + return; + } + + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: " + request.toString()); + + long now = System.currentTimeMillis(); + TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now); + if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) { + if (activeTemp != null) { + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: cancelTempBasal()"); + MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(false, callback); + } else { + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: Basal set correctly"); + if (callback != null) { + callback.result(new PumpEnactResult().absolute(request.rate).duration(0) + .enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run(); + } + } + } else if (activeTemp != null + && activeTemp.getPlannedRemainingMinutes() > 5 + && request.duration - activeTemp.getPlannedRemainingMinutes() < 30 + && Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) { + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: Temp basal set correctly"); + if (callback != null) { + callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile)) + .enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes()) + .comment(MainApp.gs(R.string.let_temp_basal_run))).run(); + } + } else { + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: setTempBasalAbsolute()"); + MainApp.getConfigBuilder().getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback); + } + } + + public void applySMBRequest(APSResult request, Callback callback) { + if (!request.bolusRequested) { + return; + } + + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); + TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); + + long lastBolusTime = activeTreatments.getLastBolusTime(); + if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { + if (L.isEnabled(L.APS)) + log.debug("SMB requested but still in 3 min interval"); + if (callback != null) { + callback.result(new PumpEnactResult() + .comment(MainApp.gs(R.string.smb_frequency_exceeded)) + .enacted(false).success(false)).run(); + } + return; + } + + if (!pump.isInitialized()) { + if (L.isEnabled(L.APS)) + log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized)); + if (callback != null) { + callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); + } + return; + } + + if (pump.isSuspended()) { + if (L.isEnabled(L.APS)) + log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended)); + if (callback != null) { + callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run(); + } + return; + } + + if (L.isEnabled(L.APS)) + log.debug("applySMBRequest: " + request.toString()); + + // deliver SMB + DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); + detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime(); + detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS; + detailedBolusInfo.insulin = request.smb; + detailedBolusInfo.isSMB = true; + detailedBolusInfo.source = Source.USER; + detailedBolusInfo.deliverAt = request.deliverAt; + if (L.isEnabled(L.APS)) + log.debug("applyAPSRequest: bolus()"); + MainApp.getConfigBuilder().getCommandQueue().bolus(detailedBolusInfo, callback); + } + + public void disconnectPump(int durationInMinutes, Profile profile) { + PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); + TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin(); + + LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L); + MainApp.getConfigBuilder().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() { + @Override + public void run() { + if (!result.success) { + ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror)); + } + } + }); + if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) { + MainApp.getConfigBuilder().getCommandQueue().cancelExtended(new Callback() { + @Override + public void run() { + if (!result.success) { + ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror)); + } + } + }); + } + NSUpload.uploadOpenAPSOffline(durationInMinutes); + } + + public void suspendLoop(int durationInMinutes) { + LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000); + MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(true, new Callback() { + @Override + public void run() { + if (!result.success) { + ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror)); + } + } + }); + NSUpload.uploadOpenAPSOffline(durationInMinutes); + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java index 3bff1c9be3..64e2091eb8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java @@ -34,8 +34,6 @@ import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.SP; public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { - private static Logger log = LoggerFactory.getLogger(NSClientFragment.class); - private TextView logTextView; private TextView queueTextView; private TextView urlTextView; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientPlugin.java index 6949cdc8b1..cc9d843368 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientPlugin.java @@ -29,6 +29,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; @@ -37,7 +38,7 @@ import info.nightscout.utils.SP; import info.nightscout.utils.ToastUtils; public class NSClientPlugin extends PluginBase { - private static Logger log = LoggerFactory.getLogger(NSClientPlugin.class); + private Logger log = LoggerFactory.getLogger(L.NSCLIENT); static NSClientPlugin nsClientPlugin; @@ -53,8 +54,8 @@ public class NSClientPlugin extends PluginBase { private final List listLog = new ArrayList<>(); Spanned textLog = Html.fromHtml(""); - public boolean paused = false; - boolean autoscroll = true; + public boolean paused; + boolean autoscroll; public String status = ""; @@ -132,12 +133,14 @@ public class NSClientPlugin extends PluginBase { private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { - log.debug("Service is disconnected"); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Service is disconnected"); nsClientService = null; } public void onServiceConnected(ComponentName name, IBinder service) { - log.debug("Service is connected"); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Service is connected"); NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service; if (mLocalBinder != null) // is null when running in roboelectric nsClientService = mLocalBinder.getServiceInstance(); @@ -155,7 +158,8 @@ public class NSClientPlugin extends PluginBase { @Subscribe public void onStatusEvent(final EventNSClientNewLog ev) { addToLog(ev); - log.debug(ev.action + " " + ev.logText); + if (L.isEnabled(L.NSCLIENT)) + log.debug(ev.action + " " + ev.logText); } @Subscribe @@ -165,30 +169,24 @@ public class NSClientPlugin extends PluginBase { } synchronized void clearLog() { - handler.post(new Runnable() { - @Override - public void run() { - synchronized (listLog) { - listLog.clear(); - } - MainApp.bus().post(new EventNSClientUpdateGUI()); + handler.post(() -> { + synchronized (listLog) { + listLog.clear(); } + MainApp.bus().post(new EventNSClientUpdateGUI()); }); } private synchronized void addToLog(final EventNSClientNewLog ev) { - handler.post(new Runnable() { - @Override - public void run() { - synchronized (listLog) { - listLog.add(ev); - // remove the first line if log is too large - if (listLog.size() >= Constants.MAX_LOG_LINES) { - listLog.remove(0); - } + handler.post(() -> { + synchronized (listLog) { + listLog.add(ev); + // remove the first line if log is too large + if (listLog.size() >= Constants.MAX_LOG_LINES) { + listLog.remove(0); } - MainApp.bus().post(new EventNSClientUpdateGUI()); } + MainApp.bus().post(new EventNSClientUpdateGUI()); }); } diff --git a/app/src/main/java/info/nightscout/utils/NSUpload.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSUpload.java similarity index 96% rename from app/src/main/java/info/nightscout/utils/NSUpload.java rename to app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSUpload.java index 00d5e39821..e1f9535caa 100644 --- a/app/src/main/java/info/nightscout/utils/NSUpload.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSUpload.java @@ -1,4 +1,4 @@ -package info.nightscout.utils; +package info.nightscout.androidaps.plugins.NSClientInternal; import android.content.Context; import android.content.Intent; @@ -23,7 +23,9 @@ import java.util.Locale; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; @@ -37,13 +39,16 @@ import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.DeviceStatus; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; +import info.nightscout.utils.BatteryLevel; +import info.nightscout.utils.DateUtil; +import info.nightscout.utils.SP; /** * Created by mike on 26.05.2017. */ public class NSUpload { - private static Logger log = LoggerFactory.getLogger(NSUpload.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public static void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) { try { @@ -79,7 +84,7 @@ public class NSUpload { if (useAbsolute) { TemporaryBasal t = temporaryBasal.clone(); t.isAbsolute = true; - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile != null) { t.absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d; uploadTempBasalStartAbsolute(t, null); @@ -191,8 +196,8 @@ public class NSUpload { } public static void uploadDeviceStatus() { - Profile profile = MainApp.getConfigBuilder().getProfile(); - String profileName = MainApp.getConfigBuilder().getProfileName(); + Profile profile = ProfileFunctions.getInstance().getProfile(); + String profileName = ProfileFunctions.getInstance().getProfileName(); if (profile == null || profileName == null) { log.error("Profile is null. Skipping upload"); @@ -232,7 +237,8 @@ public class NSUpload { deviceStatus.enacted.put("requested", requested); } } else { - log.debug("OpenAPS data too old to upload"); + if (L.isEnabled(L.NSCLIENT)) + log.debug("OpenAPS data too old to upload"); } deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL; JSONObject pumpstatus = ConfigBuilderPlugin.getActivePump().getJSONStatus(profile, profileName); @@ -298,7 +304,7 @@ public class NSUpload { public static void uploadTempTarget(TempTarget tempTarget) { try { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { log.error("Profile is null. Skipping upload"); @@ -490,7 +496,7 @@ public class NSUpload { try { data.put("eventType", "Note"); data.put("created_at", DateUtil.toISOString(new Date())); - data.put("notes", MainApp.gs(R.string.androidaps_start)+" - "+ Build.MANUFACTURER + " "+ Build.MODEL); + data.put("notes", MainApp.gs(R.string.androidaps_start) + " - " + Build.MANUFACTURER + " " + Build.MODEL); } catch (JSONException e) { log.error("Unhandled exception", e); } @@ -500,7 +506,7 @@ public class NSUpload { intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); context.sendBroadcast(intent); DbLogger.dbAdd(intent, data.toString()); - } + } } public static void uploadEvent(String careportalEvent, long time, @Nullable String notes) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java index 17cc1dced3..9c0284029c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/UploadQueue.java @@ -16,13 +16,14 @@ import java.sql.SQLException; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DbRequest; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; /** * Created by mike on 21.02.2016. */ public class UploadQueue { - private static Logger log = LoggerFactory.getLogger(UploadQueue.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public static String status() { return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); @@ -43,15 +44,13 @@ public class UploadQueue { public static void add(final DbRequest dbr) { startService(); if (NSClientService.handler != null) { - NSClientService.handler.post(new Runnable() { - @Override - public void run() { - log.debug("QUEUE adding: " + dbr.data); - MainApp.getDbHelper().create(dbr); - NSClientPlugin plugin = NSClientPlugin.getPlugin(); - if (plugin != null) { - plugin.resend("newdata"); - } + NSClientService.handler.post(() -> { + if (L.isEnabled(L.NSCLIENT)) + log.debug("Adding to queue: " + dbr.data); + MainApp.getDbHelper().create(dbr); + NSClientPlugin plugin = NSClientPlugin.getPlugin(); + if (plugin != null) { + plugin.resend("newdata"); } }); } @@ -60,13 +59,12 @@ public class UploadQueue { public static void clearQueue() { startService(); if (NSClientService.handler != null) { - NSClientService.handler.post(new Runnable() { - @Override - public void run() { - log.debug("QUEUE ClearQueue"); - MainApp.getDbHelper().deleteAllDbRequests(); + NSClientService.handler.post(() -> { + if (L.isEnabled(L.NSCLIENT)) + log.debug("ClearQueue"); + MainApp.getDbHelper().deleteAllDbRequests(); + if (L.isEnabled(L.NSCLIENT)) log.debug(status()); - } }); } } @@ -74,22 +72,20 @@ public class UploadQueue { public static void removeID(final JSONObject record) { startService(); if (NSClientService.handler != null) { - NSClientService.handler.post(new Runnable() { - @Override - public void run() { - try { - String id; - if (record.has("NSCLIENT_ID")) { - id = record.getString("NSCLIENT_ID"); - } else { - return; - } - if (MainApp.getDbHelper().deleteDbRequest(id) == 1) { - log.debug("Removed item from UploadQueue. " + UploadQueue.status()); - } - } catch (JSONException e) { - log.error("Unhandled exception", e); + NSClientService.handler.post(() -> { + try { + String id; + if (record.has("NSCLIENT_ID")) { + id = record.getString("NSCLIENT_ID"); + } else { + return; } + if (MainApp.getDbHelper().deleteDbRequest(id) == 1) { + if (L.isEnabled(L.NSCLIENT)) + log.debug("Removed item from UploadQueue. " + UploadQueue.status()); + } + } catch (JSONException e) { + log.error("Unhandled exception", e); } }); } @@ -100,18 +96,17 @@ public class UploadQueue { return; startService(); if (NSClientService.handler != null) { - NSClientService.handler.post(new Runnable() { - @Override - public void run() { - MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); - } + NSClientService.handler.post(() -> { + MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status()); }); } } public String textList() { String result = ""; - CloseableIterator iterator = null; + CloseableIterator iterator; try { iterator = MainApp.getDbHelper().getDbRequestInterator(); try { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java index e90dce3bec..ed9c4c3013 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSAddAck.java @@ -1,13 +1,13 @@ package info.nightscout.androidaps.plugins.NSClientInternal.acks; import org.json.JSONArray; -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.events.Event; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import io.socket.client.Ack; @@ -15,17 +15,18 @@ import io.socket.client.Ack; * Created by mike on 29.12.2015. */ public class NSAddAck extends Event implements Ack { - private static Logger log = LoggerFactory.getLogger(NSAddAck.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public String _id = null; public String nsClientID = null; public JSONObject json = null; - public void call(Object...args) { + + public void call(Object... args) { // Regular response try { JSONArray responsearray = (JSONArray) (args[0]); JSONObject response = null; - if (responsearray.length()>0) { - response = responsearray.getJSONObject(0); + if (responsearray.length() > 0) { + response = responsearray.getJSONObject(0); _id = response.getString("_id"); json = response; if (response.has("NSCLIENT_ID")) { @@ -35,6 +36,7 @@ public class NSAddAck extends Event implements Ack { MainApp.bus().post(this); return; } catch (Exception e) { + log.error("Unhandled exception", e); } // Check for not authorized try { @@ -45,7 +47,8 @@ public class NSAddAck extends Event implements Ack { MainApp.bus().post(new EventNSClientRestart()); return; } - log.debug("DBACCESS " + response.getString("result")); + if (L.isEnabled(L.NSCLIENT)) + log.debug("DBACCESS " + response.getString("result")); } return; } catch (Exception e) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java index 2bf520da64..42534387b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/acks/NSUpdateAck.java @@ -7,15 +7,16 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.logging.L; import io.socket.client.Ack; /** * Created by mike on 21.02.2016. */ public class NSUpdateAck extends Event implements Ack { - private static Logger log = LoggerFactory.getLogger(NSUpdateAck.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public boolean result = false; - public String _id = null; + public String _id; public String action; public void call(Object...args) { JSONObject response = (JSONObject)args[0]; @@ -29,6 +30,7 @@ public class NSUpdateAck extends Event implements Ack { } MainApp.bus().post(this); } catch (JSONException e) { + log.error("Unhandled exception", e); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAckAlarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAckAlarm.java index 216fa3d19a..b2db8d7ce3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAckAlarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAckAlarm.java @@ -2,18 +2,12 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSAlarm; import info.nightscout.utils.SP; @@ -22,7 +16,6 @@ import info.nightscout.utils.SP; */ public class BroadcastAckAlarm { - private static Logger log = LoggerFactory.getLogger(BroadcastAckAlarm.class); public static void handleClearAlarm(NSAlarm originalAlarm, Context context, long silenceTimeInMsec) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAlarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAlarm.java index 0fee6600bd..7146f1814f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAlarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAlarm.java @@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 26.06.2016. */ public class BroadcastAlarm { - private static Logger log = LoggerFactory.getLogger(BroadcastAlarm.class); - public static void handleAlarm(JSONObject alarm, Context context) { Bundle bundle = new Bundle(); bundle.putString("data", alarm.toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAnnouncement.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAnnouncement.java index 9b133c2551..f7cecf0445 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAnnouncement.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastAnnouncement.java @@ -2,28 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; -import org.json.JSONArray; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 26.06.2016. */ public class BroadcastAnnouncement { - private static Logger log = LoggerFactory.getLogger(BroadcastAnnouncement.class); - public static void handleAnnouncement(JSONObject announcement, Context context) { Bundle bundle = new Bundle(); bundle.putString("data", announcement.toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java index 7580a00088..6a1b9746e4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastCals.java @@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 26.06.2016. */ public class BroadcastCals { - private static Logger log = LoggerFactory.getLogger(BroadcastCals.class); - public static void handleNewCal(JSONArray cals, Context context, boolean isDelta) { Bundle bundle = new Bundle(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastClearAlarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastClearAlarm.java index 23406837a7..b63d2e5a60 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastClearAlarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastClearAlarm.java @@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 26.06.2016. */ public class BroadcastClearAlarm { - private static Logger log = LoggerFactory.getLogger(BroadcastClearAlarm.class); - public static void handleClearAlarm(JSONObject clearalarm, Context context) { Bundle bundle = new Bundle(); bundle.putString("data", clearalarm.toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java index 59f5ab136c..992ff00c81 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastDeviceStatus.java @@ -2,45 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; public class BroadcastDeviceStatus { - private static Logger log = LoggerFactory.getLogger(BroadcastDeviceStatus.class); - - public static void handleNewDeviceStatus(JSONObject status, Context context, boolean isDelta) { - Bundle bundle = new Bundle(); - bundle.putString("devicestatus", status.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { - bundle = new Bundle(); - bundle.putString("devicestatus", status.toString()); - bundle.putBoolean("delta", isDelta); - intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - } - } public static void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) { List splitted = BroadcastTreatment.splitArray(statuses); @@ -67,31 +42,4 @@ public class BroadcastDeviceStatus { } } } - - public static void handleNewFoods(JSONArray foods, Context context, boolean isDelta) { - - List splitted = BroadcastTreatment.splitArray(foods); - for (JSONArray part: splitted) { - Bundle bundle = new Bundle(); - bundle.putString("foods", part.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_NEW_FOOD); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - } - - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { - splitted = BroadcastTreatment.splitArray(foods); - for (JSONArray part : splitted) { - Bundle bundle = new Bundle(); - bundle.putString("foods", part.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_NEW_FOOD); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - } - } - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastFood.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastFood.java index dbb3385fbb..31a582ade2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastFood.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastFood.java @@ -6,26 +6,18 @@ import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; -import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 20.02.2016. */ public class BroadcastFood { - private static Logger log = LoggerFactory.getLogger(BroadcastFood.class); - public static void handleNewFood(JSONArray foods, Context context, boolean isDelta) { List splitted = BroadcastTreatment.splitArray(foods); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java index a715747791..2dc48eb9a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastMbgs.java @@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONArray; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 26.06.2016. */ public class BroadcastMbgs { - private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class); - public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) { Bundle bundle = new Bundle(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java index 3802b09657..ae76212105 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastProfile.java @@ -2,18 +2,12 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.utils.SP; @@ -22,8 +16,6 @@ import info.nightscout.utils.SP; * Created by mike on 20.02.2016. */ public class BroadcastProfile { - private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class); - public static void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) { Bundle bundle = new Bundle(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastQueueStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastQueueStatus.java deleted file mode 100644 index abc49be18a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastQueueStatus.java +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.PowerManager; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; -import info.nightscout.utils.SP; - -/** - * Created by mike on 28.02.2016. - */ -public class BroadcastQueueStatus { - public static void handleNewStatus(int size, Context context) { - - if(!SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) return; - - PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); - PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, - "sendQueue"); - wakeLock.acquire(); - try { - Bundle bundle = new Bundle(); - bundle.putInt("size", size); - Intent intent = new Intent(Intents.ACTION_QUEUE_STATUS); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - } finally { - wakeLock.release(); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java index 65a90f3b74..b15fe606fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastSgvs.java @@ -2,49 +2,22 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONArray; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 22.02.2016. */ public class BroadcastSgvs { - private static Logger log = LoggerFactory.getLogger(BroadcastSgvs.class); - - public static void handleNewSgv(JSONObject sgv, Context context, boolean isDelta) { - - Bundle bundle = new Bundle(); - bundle.putString("sgv", sgv.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_NEW_SGV); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - - if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { - bundle = new Bundle(); - bundle.putString("sgv", sgv.toString()); - bundle.putBoolean("delta", isDelta); - intent = new Intent(Intents.ACTION_NEW_SGV); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - context.sendBroadcast(intent); - } - } - public static void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) { List splitted = BroadcastTreatment.splitArray(sgvs); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java index a2b6e64aec..da28fe9881 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastStatus.java @@ -3,18 +3,16 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.List; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.utils.SP; @@ -23,7 +21,7 @@ import info.nightscout.utils.SP; * Created by mike on 24.02.2016. */ public class BroadcastStatus { - private static Logger log = LoggerFactory.getLogger(BroadcastStatus.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public static void handleNewStatus(NSSettingsStatus status, Context context, boolean isDelta) { LocalBroadcastManager.getInstance(MainApp.instance()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java index 94b83c56bd..dc834215a9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastTreatment.java @@ -15,14 +15,15 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 20.02.2016. */ public class BroadcastTreatment { - private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public static void handleNewTreatment(JSONObject treatment, boolean isDelta, boolean isLocalBypass) { @@ -73,28 +74,6 @@ public class BroadcastTreatment { } } - public void handleChangedTreatment(JSONObject treatment, boolean isDelta) { - - Bundle bundle = new Bundle(); - bundle.putString("treatment", treatment.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - - - if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { - bundle = new Bundle(); - bundle.putString("treatment", treatment.toString()); - bundle.putBoolean("delta", isDelta); - intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - MainApp.instance().getApplicationContext().sendBroadcast(intent); - } - } - public static void handleChangedTreatment(JSONArray treatments, boolean isDelta) { List splitted = splitArray(treatments); @@ -122,28 +101,6 @@ public class BroadcastTreatment { } } - public static void handleRemovedTreatment(JSONObject treatment, boolean isDelta) { - - Bundle bundle = new Bundle(); - bundle.putString("treatment", treatment.toString()); - bundle.putBoolean("delta", isDelta); - Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent); - - - if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) { - bundle = new Bundle(); - bundle.putString("treatment", treatment.toString()); - bundle.putBoolean("delta", isDelta); - intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); - intent.putExtras(bundle); - intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - MainApp.instance().getApplicationContext().sendBroadcast(intent); - } - } - public static void handleRemovedTreatment(JSONArray treatments, boolean isDelta) { Bundle bundle = new Bundle(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastUrgentAlarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastUrgentAlarm.java index c332be03af..76095453d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastUrgentAlarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/broadcasts/BroadcastUrgentAlarm.java @@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts; import android.content.Context; import android.content.Intent; -import android.content.pm.ResolveInfo; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.utils.SP; /** * Created by mike on 26.06.2016. */ public class BroadcastUrgentAlarm { - private static Logger log = LoggerFactory.getLogger(BroadcastUrgentAlarm.class); - public static void handleUrgentAlarm(JSONObject urgentalarm, Context context) { Bundle bundle = new Bundle(); bundle.putString("data", urgentalarm.toString()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java index 2723fc0748..ec31141002 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/DbLogger.java @@ -8,32 +8,36 @@ import org.slf4j.LoggerFactory; import java.util.List; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.ToastUtils; /** * Created by mike on 02.07.2016. */ public class DbLogger { - private static Logger log = LoggerFactory.getLogger(DbLogger.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public static void dbAdd(Intent intent, String data) { List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); if (q.size() < 1) { - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.gs(R.string.nsclientnotinstalled)); + ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.nsclientnotinstalled)); log.error("DBADD No receivers"); - } else if (Config.logNSUpload) - log.debug("DBADD dbAdd " + q.size() + " receivers " + data); + } else if (L.isEnabled(L.NSCLIENT)) { + if (L.isEnabled(L.NSCLIENT)) + log.debug("DBADD dbAdd " + q.size() + " receivers " + data); + } } - public static void dbRemove(Intent intent, String data) { + public static void dbRemove(Intent intent, String data) { List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); if (q.size() < 1) { - ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.gs(R.string.nsclientnotinstalled)); + ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.nsclientnotinstalled)); log.error("DBREMOVE No receivers"); - } else if (Config.logNSUpload) - log.debug("DBREMOVE dbRemove " + q.size() + " receivers " + data); + } else if (L.isEnabled(L.NSCLIENT)) { + if (L.isEnabled(L.NSCLIENT)) + log.debug("DBREMOVE dbRemove " + q.size() + " receivers " + data); + } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSAlarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSAlarm.java index 1c28b790d7..7ad82220da 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSAlarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSAlarm.java @@ -5,12 +5,14 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 11.06.2017. */ public class NSAlarm { - private static Logger log = LoggerFactory.getLogger(NSAlarm.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); JSONObject data; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java index 93d46fa18e..83fe44073e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSCal.java @@ -5,8 +5,10 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + public class NSCal { - private static Logger log = LoggerFactory.getLogger(NSCal.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public long date; public double slope; public double intercept; @@ -20,7 +22,7 @@ public class NSCal { scale = json.getDouble("scale"); } catch (JSONException e) { log.error("Unhandled exception", e); - log.debug("Data: " + json.toString()); + log.error("Data: " + json.toString()); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSDeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSDeviceStatus.java index 29d1b33467..1c8aea9b83 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSDeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSDeviceStatus.java @@ -1,8 +1,11 @@ package info.nightscout.androidaps.plugins.NSClientInternal.data; +import android.content.Intent; +import android.os.Bundle; import android.text.Html; import android.text.Spanned; +import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -13,7 +16,10 @@ import java.util.Iterator; import java.util.Map; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.Loop.APSResult; +import info.nightscout.androidaps.logging.BundleLogger; import info.nightscout.utils.DateUtil; import info.nightscout.utils.Round; import info.nightscout.utils.SP; @@ -73,7 +79,7 @@ import info.nightscout.utils.SP; } */ public class NSDeviceStatus { - private static Logger log = LoggerFactory.getLogger(NSDeviceStatus.class); + private Logger log = LoggerFactory.getLogger(L.NSCLIENT); private static NSDeviceStatus instance = null; @@ -88,6 +94,41 @@ public class NSDeviceStatus { public NSDeviceStatus() { } + public void handleNewData(Intent intent) { + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + if (L.isEnabled(L.NSCLIENT)) + log.debug("Got NS devicestatus: " + BundleLogger.log(bundle)); + + try { + if (bundle.containsKey("devicestatus")) { + JSONObject devicestatusJson = new JSONObject(bundle.getString("devicestatus")); + setData(devicestatusJson); + if (devicestatusJson.has("pump")) { + // Objectives 0 + ObjectivesPlugin.pumpStatusIsAvailableInNS = true; + ObjectivesPlugin.saveProgress(); + } + } + if (bundle.containsKey("devicestatuses")) { + String devicestatusesstring = bundle.getString("devicestatuses"); + JSONArray jsonArray = new JSONArray(devicestatusesstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject devicestatusJson = jsonArray.getJSONObject(i); + setData(devicestatusJson); + if (devicestatusJson.has("pump")) { + // Objectives 0 + ObjectivesPlugin.pumpStatusIsAvailableInNS = true; + ObjectivesPlugin.saveProgress(); + } + } + } + } catch (Exception e) { + log.error("Unhandled exception", e); + } + } + public NSDeviceStatus setData(JSONObject obj) { this.data = obj; updatePumpData(obj); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java index 353dd49b74..cd4cd9cdba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSMbg.java @@ -5,8 +5,10 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + public class NSMbg { - private static Logger log = LoggerFactory.getLogger(NSMbg.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); public long date; public double mbg; public String json; @@ -18,7 +20,7 @@ public class NSMbg { this.json = json.toString(); } catch (JSONException e) { log.error("Unhandled exception", e); - log.debug("Data: " + json.toString()); + log.error("Data: " + json.toString()); } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSettingsStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSettingsStatus.java index 8d09a05146..dc3c9f742e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSettingsStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSettingsStatus.java @@ -1,5 +1,8 @@ package info.nightscout.androidaps.plugins.NSClientInternal.data; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.os.Bundle; import android.support.annotation.Nullable; import org.json.JSONException; @@ -10,6 +13,16 @@ import org.slf4j.LoggerFactory; import java.util.Date; import java.util.Objects; +import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; +import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; +import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.BundleLogger; + /* { "status": "ok", @@ -101,7 +114,7 @@ import java.util.Objects; } */ public class NSSettingsStatus { - private static Logger log = LoggerFactory.getLogger(NSSettingsStatus.class); + private Logger log = LoggerFactory.getLogger(L.NSCLIENT); private static NSSettingsStatus instance = null; @@ -111,6 +124,8 @@ public class NSSettingsStatus { return instance; } + public String nightscoutVersionName = ""; + private JSONObject data = null; public NSSettingsStatus() { @@ -121,6 +136,59 @@ public class NSSettingsStatus { return this; } + public void handleNewData(Intent intent) { + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + if (L.isEnabled(L.NSCLIENT)) + log.debug("Got NS status: " + BundleLogger.log(bundle)); + + if (bundle.containsKey("nsclientversioncode")) { + + Integer nightscoutVersionCode = bundle.getInt("nightscoutversioncode"); + nightscoutVersionName = bundle.getString("nightscoutversionname"); + Integer nsClientVersionCode = bundle.getInt("nsclientversioncode"); + String nsClientVersionName = bundle.getString("nsclientversionname"); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Got versions: NSClient: " + nsClientVersionName + " Nightscout: " + nightscoutVersionName); + try { + if (nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) { + Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT); + MainApp.bus().post(new EventNewNotification(notification)); + } else { + MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT)); + } + } catch (PackageManager.NameNotFoundException e) { + log.error("Unhandled exception", e); + } + if (nightscoutVersionCode < Config.SUPPORTEDNSVERSION) { + Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL); + MainApp.bus().post(new EventNewNotification(notification)); + } else { + MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS)); + } + } else { + Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT); + MainApp.bus().post(new EventNewNotification(notification)); + } + if (bundle.containsKey("status")) { + try { + JSONObject statusJson = new JSONObject(bundle.getString("status")); + setData(statusJson); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Received status: " + statusJson.toString()); + Double targetHigh = getThreshold("bgTargetTop"); + Double targetlow = getThreshold("bgTargetBottom"); + if (targetHigh != null) + OverviewPlugin.bgTargetHigh = targetHigh; + if (targetlow != null) + OverviewPlugin.bgTargetLow = targetlow; + } catch (JSONException e) { + log.error("Unhandled exception", e); + } + } + } + public String getName() { return getStringOrNull("name"); } @@ -134,7 +202,7 @@ public class NSSettingsStatus { } public Date getServerTime() { - return getDateOrNull("versionNum"); + return getDateOrNull("serverTime"); } public boolean getApiEnabled() { @@ -202,13 +270,11 @@ public class NSSettingsStatus { if (settingsO.has("thresholds")) { JSONObject tObject = settingsO.getJSONObject("thresholds"); if (tObject.has(what)) { - Double result = tObject.getDouble(what); - return result; + return tObject.getDouble(what); } } if (settingsO.has("alarmTimeagoWarnMins") && Objects.equals(what, "alarmTimeagoWarnMins")) { - Double result = settingsO.getDouble(what); - return result; + return settingsO.getDouble(what); } } } catch (JSONException e) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java index 50336a5f52..2212884a3e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSSgv.java @@ -5,12 +5,14 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * * {"mgdl":105,"mills":1455136282375,"device":"xDrip-BluetoothWixel","direction":"Flat","filtered":98272,"unfiltered":98272,"noise":1,"rssi":100} */ public class NSSgv { - private static Logger log = LoggerFactory.getLogger(NSSgv.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); private JSONObject data; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java index a9f960edd0..d4ee20e2a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/data/NSTreatment.java @@ -7,8 +7,10 @@ import org.slf4j.LoggerFactory; import java.util.Date; +import info.nightscout.androidaps.logging.L; + public class NSTreatment { - private static Logger log = LoggerFactory.getLogger(NSTreatment.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); private JSONObject data; private String action = null; // "update", "remove" or null (add) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AckAlarmReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AckAlarmReceiver.java index 2aae41538a..f23533e9ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AckAlarmReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AckAlarmReceiver.java @@ -11,15 +11,15 @@ import org.slf4j.LoggerFactory; 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.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.utils.SP; public class AckAlarmReceiver extends BroadcastReceiver { - private static Logger log = LoggerFactory.getLogger(AckAlarmReceiver.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); @Override @@ -32,7 +32,8 @@ public class AckAlarmReceiver extends BroadcastReceiver { return; } if (SP.getBoolean(R.string.key_ns_noupload, false)) { - log.debug("Upload disabled. Message dropped"); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Upload disabled. Message dropped"); return; } wakeLock.acquire(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java index 332ccc2ea3..a1300f7b99 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/DBAccessReceiver.java @@ -15,6 +15,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; @@ -22,7 +23,7 @@ import info.nightscout.utils.DateUtil; import info.nightscout.utils.SP; public class DBAccessReceiver extends BroadcastReceiver { - private static Logger log = LoggerFactory.getLogger(DBAccessReceiver.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); @Override @@ -43,18 +44,21 @@ public class DBAccessReceiver extends BroadcastReceiver { try { collection = bundles.getString("collection"); } catch (Exception e) { + log.error("Unhandled exception", e); } try { _id = bundles.getString("_id"); } catch (Exception e) { + log.error("Unhandled exception", e); } try { data = new JSONObject(bundles.getString("data")); } catch (Exception e) { + log.error("Unhandled exception", e); } if (data == null && !action.equals("dbRemove") || _id == null && action.equals("dbRemove")) { - log.debug("DBACCESS no data inside record"); + log.error("DBACCESS no data inside record"); return; } @@ -70,7 +74,7 @@ public class DBAccessReceiver extends BroadcastReceiver { } if (!isAllowedCollection(collection)) { - log.debug("DBACCESS wrong collection specified"); + log.error("DBACCESS wrong collection specified"); return; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java index fab9a181c4..d7066705b9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/services/NSClientService.java @@ -9,7 +9,6 @@ import android.os.HandlerThread; import android.os.IBinder; import android.os.PowerManager; - import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import com.j256.ormlite.dao.CloseableIterator; @@ -23,7 +22,6 @@ import org.slf4j.LoggerFactory; import java.net.URISyntaxException; import java.sql.SQLException; -import java.util.Date; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; @@ -34,6 +32,7 @@ import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck; @@ -70,7 +69,7 @@ import io.socket.client.Socket; import io.socket.emitter.Emitter; public class NSClientService extends Service { - private static Logger log = LoggerFactory.getLogger(NSClientService.class); + private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); static public PowerManager.WakeLock mWakeLock; private IBinder mBinder = new NSClientService.LocalBinder(); @@ -156,13 +155,13 @@ public class NSClientService extends Service { @Subscribe public void onStatusEvent(EventAppExit event) { - if (Config.logFunctionCalls) + if (L.isEnabled(L.NSCLIENT)) log.debug("EventAppExit received"); destroy(); stopSelf(); - if (Config.logFunctionCalls) + if (L.isEnabled(L.NSCLIENT)) log.debug("EventAppExit finished"); } @@ -250,7 +249,8 @@ public class NSClientService extends Service { private Emitter.Listener onDisconnect = new Emitter.Listener() { @Override public void call(Object... args) { - log.debug("disconnect reason: {}", args); + if (L.isEnabled(L.NSCLIENT)) + log.debug("disconnect reason: {}", args); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } }; @@ -326,8 +326,7 @@ public class NSClientService extends Service { private Emitter.Listener onPing = new Emitter.Listener() { @Override public void call(final Object... args) { - if (Config.detailedLog) - MainApp.bus().post(new EventNSClientNewLog("PING", "received")); + MainApp.bus().post(new EventNSClientNewLog("PING", "received")); // send data if there is something waiting resend("Ping received"); } @@ -352,16 +351,18 @@ public class NSClientService extends Service { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Announcement from NS: " + args[0]); + log.error("Unhandled exception", e); return; } - if (Config.detailedLog) - try { - MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); - } catch (Exception e) { - FabricPrivacy.logException(e); - } + try { + MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); + } catch (Exception e) { + FabricPrivacy.logException(e); + log.error("Unhandled exception", e); + } BroadcastAnnouncement.handleAnnouncement(data, getApplicationContext()); - log.debug(data.toString()); + if (L.isEnabled(L.NSCLIENT)) + log.debug(data.toString()); } }; @@ -381,17 +382,18 @@ public class NSClientService extends Service { */ @Override public void call(final Object... args) { - if (Config.detailedLog) - MainApp.bus().post(new EventNSClientNewLog("ALARM", "received")); + MainApp.bus().post(new EventNSClientNewLog("ALARM", "received")); JSONObject data; try { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong alarm from NS: " + args[0]); + log.error("Unhandled exception", e); return; } BroadcastAlarm.handleAlarm(data, getApplicationContext()); - log.debug(data.toString()); + if (L.isEnabled(L.NSCLIENT)) + log.debug(data.toString()); } }; @@ -416,12 +418,13 @@ public class NSClientService extends Service { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); + log.error("Unhandled exception", e); return; } - if (Config.detailedLog) - MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received")); + MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received")); BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext()); - log.debug(data.toString()); + if (L.isEnabled(L.NSCLIENT)) + log.debug(data.toString()); } }; @@ -441,12 +444,13 @@ public class NSClientService extends Service { data = (JSONObject) args[0]; } catch (Exception e) { FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); + log.error("Unhandled exception", e); return; } - if (Config.detailedLog) - MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received")); + MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received")); BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext()); - log.debug(data.toString()); + if (L.isEnabled(L.NSCLIENT)) + log.debug(data.toString()); } }; @@ -743,17 +747,6 @@ public class NSClientService extends Service { } } - private boolean isCurrent(NSTreatment treatment) { - long now = (new Date()).getTime(); - long minPast = now - nsHours * 60L * 60 * 1000; - if (treatment.getMills() == null) { - log.debug("treatment.getMills() == null " + treatment.getData().toString()); - return false; - } - if (treatment.getMills() > minPast) return true; - return false; - } - public void resend(final String reason) { if (UploadQueue.size() == 0) return; @@ -766,7 +759,8 @@ public class NSClientService extends Service { if (mSocket == null || !mSocket.connected()) return; if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { - log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); + if (L.isEnabled(L.NSCLIENT)) + log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } lastResendTime = System.currentTimeMillis(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java index 4c8de10b9c..50e79d1e37 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.OpenAPSAMA; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.mozilla.javascript.Callable; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeJSON; @@ -18,7 +17,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -27,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.logging.L; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; @@ -35,7 +34,7 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.SP; public class DetermineBasalAdapterAMAJS { - private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterAMAJS.class); + private static Logger log = LoggerFactory.getLogger(L.APS); private ScriptReader mScriptReader = null; @@ -56,23 +55,24 @@ public class DetermineBasalAdapterAMAJS { private String scriptDebug = ""; - public DetermineBasalAdapterAMAJS(ScriptReader scriptReader) throws IOException { + public DetermineBasalAdapterAMAJS(ScriptReader scriptReader) { mScriptReader = scriptReader; } public DetermineBasalResultAMA invoke() { - - 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")); + 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")); + } DetermineBasalResultAMA determineBasalResultAMA = null; @@ -119,7 +119,7 @@ public class DetermineBasalAdapterAMAJS { // Parse the jsResult object to a JSON-String String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug("Result: " + result); try { determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result)); @@ -127,17 +127,13 @@ public class DetermineBasalAdapterAMAJS { log.error("Unhandled exception", e); } } else { - log.debug("Problem loading JS Functions"); + log.error("Problem loading JS Functions"); } } catch (IOException e) { - log.debug("IOException"); + log.error("IOException"); } catch (RhinoException e) { log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); - } catch (IllegalAccessException e) { - log.error(e.toString()); - } catch (InstantiationException e) { - log.error(e.toString()); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { log.error(e.toString()); } finally { Context.exit(); @@ -214,7 +210,7 @@ public class DetermineBasalAdapterAMAJS { mProfile.put("temptargetSet", tempTargetSet); mProfile.put("autosens_adjust_targets", SP.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true)); //align with max-absorption model in AMA sensitivity - if(mealData.usedMinCarbsImpact > 0){ + if (mealData.usedMinCarbsImpact > 0) { mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); } else { mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); @@ -265,31 +261,21 @@ public class DetermineBasalAdapterAMAJS { } - public Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { + private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { if (jsonObject == null) return Undefined.instance; - Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), new Callable() { - @Override - public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) { - return objects[1]; - } - }); + Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]); return param; } - public Object makeParamArray(JSONArray jsonArray, Context rhino, Scriptable scope) { + private Object makeParamArray(JSONArray jsonArray, Context rhino, Scriptable scope) { //Object param = NativeJSON.parse(rhino, scope, "{myarray: " + jsonArray.toString() + " }", new Callable() { - Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), new Callable() { - @Override - public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) { - return objects[1]; - } - }); + Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), (context, scriptable, scriptable1, objects) -> objects[1]); return param; } - public String readFile(String filename) throws IOException { + private String readFile(String filename) throws IOException { byte[] bytes = mScriptReader.readFile(filename); String string = new String(bytes, "UTF-8"); if (string.startsWith("#!/usr/bin/env node")) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java index ac7a7c2b49..7d57f52efb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java @@ -6,11 +6,12 @@ import org.mozilla.javascript.NativeObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.utils.DateUtil; public class DetermineBasalResultAMA extends APSResult { - private static Logger log = LoggerFactory.getLogger(DetermineBasalResultAMA.class); + private static Logger log = LoggerFactory.getLogger(L.APS); private double eventualBG; private double snoozeBG; @@ -47,7 +48,7 @@ public class DetermineBasalResultAMA extends APSResult { bolusRequested = false; } - public DetermineBasalResultAMA() { + private DetermineBasalResultAMA() { hasPredictions = true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java index f05b0ac696..0eb327c608 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.OpenAPSAMA; import android.app.Activity; import android.os.Bundle; -import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -19,6 +18,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; @@ -26,7 +26,7 @@ import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.JSONFormatter; public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnClickListener { - private static Logger log = LoggerFactory.getLogger(OpenAPSAMAFragment.class); + private static Logger log = LoggerFactory.getLogger(L.APS); Button run; TextView lastRunView; @@ -43,29 +43,23 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.openapsama_fragment, container, false); + View view = inflater.inflate(R.layout.openapsama_fragment, container, false); - run = (Button) view.findViewById(R.id.openapsma_run); - run.setOnClickListener(this); - lastRunView = (TextView) view.findViewById(R.id.openapsma_lastrun); - glucoseStatusView = (TextView) view.findViewById(R.id.openapsma_glucosestatus); - currentTempView = (TextView) view.findViewById(R.id.openapsma_currenttemp); - iobDataView = (TextView) view.findViewById(R.id.openapsma_iobdata); - profileView = (TextView) view.findViewById(R.id.openapsma_profile); - mealDataView = (TextView) view.findViewById(R.id.openapsma_mealdata); - autosensDataView = (TextView) view.findViewById(R.id.openapsma_autosensdata); - scriptdebugView = (TextView) view.findViewById(R.id.openapsma_scriptdebugdata); - resultView = (TextView) view.findViewById(R.id.openapsma_result); - requestView = (TextView) view.findViewById(R.id.openapsma_request); + run = (Button) view.findViewById(R.id.openapsma_run); + run.setOnClickListener(this); + lastRunView = (TextView) view.findViewById(R.id.openapsma_lastrun); + glucoseStatusView = (TextView) view.findViewById(R.id.openapsma_glucosestatus); + currentTempView = (TextView) view.findViewById(R.id.openapsma_currenttemp); + iobDataView = (TextView) view.findViewById(R.id.openapsma_iobdata); + profileView = (TextView) view.findViewById(R.id.openapsma_profile); + mealDataView = (TextView) view.findViewById(R.id.openapsma_mealdata); + autosensDataView = (TextView) view.findViewById(R.id.openapsma_autosensdata); + scriptdebugView = (TextView) view.findViewById(R.id.openapsma_scriptdebugdata); + resultView = (TextView) view.findViewById(R.id.openapsma_result); + requestView = (TextView) view.findViewById(R.id.openapsma_request); - updateGUI(); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } - - return null; + updateGUI(); + return view; } @Override @@ -93,35 +87,32 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli protected void updateGUI() { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - DetermineBasalResultAMA lastAPSResult = OpenAPSAMAPlugin.getPlugin().lastAPSResult; - if (lastAPSResult != null) { - resultView.setText(JSONFormatter.format(lastAPSResult.json)); - requestView.setText(lastAPSResult.toSpanned()); - } - DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS = OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS; - if (determineBasalAdapterAMAJS != null) { - glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getGlucoseStatusParam())); - currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam())); - try { - JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam()); - iobDataView.setText(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))); - } catch (JSONException e) { - log.error("Unhandled exception", e); - iobDataView.setText("JSONException"); - } - profileView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getProfileParam())); - mealDataView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getMealDataParam())); - scriptdebugView.setText(determineBasalAdapterAMAJS.getScriptDebug()); - } - if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != null) { - lastRunView.setText(OpenAPSAMAPlugin.getPlugin().lastAPSRun.toLocaleString()); - } - if (OpenAPSAMAPlugin.getPlugin().lastAutosensResult != null) { - autosensDataView.setText(JSONFormatter.format(OpenAPSAMAPlugin.getPlugin().lastAutosensResult.json())); + activity.runOnUiThread(() -> { + DetermineBasalResultAMA lastAPSResult = OpenAPSAMAPlugin.getPlugin().lastAPSResult; + if (lastAPSResult != null) { + resultView.setText(JSONFormatter.format(lastAPSResult.json)); + requestView.setText(lastAPSResult.toSpanned()); + } + DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS = OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS; + if (determineBasalAdapterAMAJS != null) { + glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getGlucoseStatusParam())); + currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam())); + try { + JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam()); + iobDataView.setText(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))); + } catch (JSONException e) { + log.error("Unhandled exception", e); + iobDataView.setText("JSONException"); } + profileView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getProfileParam())); + mealDataView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getMealDataParam())); + scriptdebugView.setText(determineBasalAdapterAMAJS.getScriptDebug()); + } + if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != null) { + lastRunView.setText(OpenAPSAMAPlugin.getPlugin().lastAPSRun.toLocaleString()); + } + if (OpenAPSAMAPlugin.getPlugin().lastAutosensResult != null) { + autosensDataView.setText(JSONFormatter.format(OpenAPSAMAPlugin.getPlugin().lastAutosensResult.json())); } }); } @@ -129,20 +120,17 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli void updateResultGUI(final String text) { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - resultView.setText(text); - glucoseStatusView.setText(""); - currentTempView.setText(""); - iobDataView.setText(""); - profileView.setText(""); - mealDataView.setText(""); - autosensDataView.setText(""); - scriptdebugView.setText(""); - requestView.setText(""); - lastRunView.setText(""); - } + activity.runOnUiThread(() -> { + resultView.setText(text); + glucoseStatusView.setText(""); + currentTempView.setText(""); + iobDataView.setText(""); + profileView.setText(""); + mealDataView.setText(""); + autosensDataView.setText(""); + scriptdebugView.setText(""); + requestView.setText(""); + lastRunView.setText(""); }); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java index 74d15cd2a4..cb651a2ae9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java @@ -1,14 +1,11 @@ package info.nightscout.androidaps.plugins.OpenAPSAMA; -import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.GlucoseStatus; @@ -22,7 +19,10 @@ 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.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.APSResult; @@ -39,7 +39,7 @@ import info.nightscout.utils.Round; * Created by mike on 05.08.2016. */ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { - private static Logger log = LoggerFactory.getLogger(OpenAPSAMAPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.APS); private static OpenAPSAMAPlugin openAPSAMAPlugin; @@ -91,37 +91,33 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { @Override public void invoke(String initiator, boolean tempBasalFallback) { - log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); + if (L.isEnabled(L.APS)) + log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; - try { - determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext())); - } catch (IOException e) { - log.error(e.getMessage(), e); - return; - } + determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext())); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (profile == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.noprofileselected)); return; } if (!isEnabled(PluginType.APS)) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); return; } @@ -139,11 +135,13 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { Date start = new Date(); Date startPart = new Date(); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile); - Profiler.log(log, "calculateIobArrayInDia()", startPart); + if (L.isEnabled(L.APS)) + Profiler.log(log, "calculateIobArrayInDia()", startPart); startPart = new Date(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); - Profiler.log(log, "getMealData()", startPart); + if (L.isEnabled(L.APS)) + Profiler.log(log, "getMealData()", startPart); double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); @@ -163,7 +161,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { if (!HardLimits.checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) return; - if (!HardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) + if (!HardLimits.checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) return; if (!HardLimits.checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF)) return; @@ -179,12 +177,15 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata))); return; } + lastAutosensResult = autosensData.autosensResult; } else { lastAutosensResult = new AutosensResult(); lastAutosensResult.sensResult = "autosens disabled"; } - Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); - Profiler.log(log, "AMA data gathering", start); + if (L.isEnabled(L.APS)) + Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); + if (L.isEnabled(L.APS)) + Profiler.log(log, "AMA data gathering", start); start = new Date(); @@ -199,7 +200,8 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { DetermineBasalResultAMA determineBasalResultAMA = determineBasalAdapterAMAJS.invoke(); - Profiler.log(log, "AMA calculation", start); + if (L.isEnabled(L.APS)) + Profiler.log(log, "AMA calculation", start); // Fix bug determine basal if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress()) determineBasalResultAMA.tempBasalRequested = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java index 6275154450..1574665dc4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.OpenAPSMA; import org.json.JSONException; import org.json.JSONObject; -import org.mozilla.javascript.Callable; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeJSON; @@ -16,7 +15,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.GlucoseStatus; @@ -24,14 +22,15 @@ 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.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.SP; public class DetermineBasalAdapterMAJS { - private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterMAJS.class); + private static Logger log = LoggerFactory.getLogger(L.APS); - private ScriptReader mScriptReader = null; + private ScriptReader mScriptReader; private JSONObject mProfile; private JSONObject mGlucoseStatus; private JSONObject mIobData; @@ -39,12 +38,12 @@ public class DetermineBasalAdapterMAJS { private JSONObject mCurrentTemp; private String storedCurrentTemp = null; - public String storedIobData = null; + private String storedIobData = null; private String storedGlucoseStatus = null; private String storedProfile = null; private String storedMeal_data = null; - public DetermineBasalAdapterMAJS(ScriptReader scriptReader) throws IOException { + DetermineBasalAdapterMAJS(ScriptReader scriptReader) { mScriptReader = scriptReader; } @@ -97,7 +96,7 @@ public class DetermineBasalAdapterMAJS { // Parse the jsResult object to a JSON-String String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug("Result: " + result); try { determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result)); @@ -108,14 +107,10 @@ public class DetermineBasalAdapterMAJS { log.debug("Problem loading JS Functions"); } } catch (IOException e) { - log.debug("IOException"); + log.error("IOException"); } catch (RhinoException e) { log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); - } catch (IllegalAccessException e) { - log.error(e.toString()); - } catch (InstantiationException e) { - log.error(e.toString()); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { log.error(e.toString()); } finally { Context.exit(); @@ -210,7 +205,7 @@ public class DetermineBasalAdapterMAJS { mMealData.put("boluses", mealData.boluses); } - public String readFile(String filename) throws IOException { + private String readFile(String filename) throws IOException { byte[] bytes = mScriptReader.readFile(filename); String string = new String(bytes, "UTF-8"); if (string.startsWith("#!/usr/bin/env node")) { @@ -219,13 +214,8 @@ public class DetermineBasalAdapterMAJS { return string; } - public Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { - Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), new Callable() { - @Override - public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) { - return objects[1]; - } - }); + private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { + Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]); return param; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java index 75928f09d0..3f0e9abea9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java @@ -6,17 +6,18 @@ import org.mozilla.javascript.NativeObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Loop.APSResult; public class DetermineBasalResultMA extends APSResult { - private static Logger log = LoggerFactory.getLogger(DetermineBasalResultMA.class); + private static Logger log = LoggerFactory.getLogger(L.APS); public JSONObject json = new JSONObject(); - public double eventualBG; - public double snoozeBG; - public String mealAssist; + private double eventualBG; + private double snoozeBG; + private String mealAssist; - public DetermineBasalResultMA(NativeObject result, JSONObject j) { + DetermineBasalResultMA(NativeObject result, JSONObject j) { json = j; if (result.containsKey("error")) { reason = (String) result.get("error"); @@ -49,7 +50,7 @@ public class DetermineBasalResultMA extends APSResult { } } - public DetermineBasalResultMA() { + private DetermineBasalResultMA() { } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java index 991ec2b25e..8907166951 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java @@ -4,8 +4,7 @@ import org.mozilla.javascript.ScriptableObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; -import info.nightscout.utils.ToastUtils; +import info.nightscout.androidaps.logging.L; /** * Created by adrian on 15/10/17. @@ -14,10 +13,10 @@ import info.nightscout.utils.ToastUtils; public class LoggerCallback extends ScriptableObject { - private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterMAJS.class); + private static Logger log = LoggerFactory.getLogger(L.APS); - static StringBuffer errorBuffer = new StringBuffer(); - static StringBuffer logBuffer = new StringBuffer(); + private static StringBuffer errorBuffer = new StringBuffer(); + private static StringBuffer logBuffer = new StringBuffer(); public LoggerCallback() { @@ -36,26 +35,27 @@ public class LoggerCallback extends ScriptableObject { } public void jsFunction_log(Object obj1) { - log.debug(obj1.toString()); + if (L.isEnabled(L.APS)) + log.debug(obj1.toString()); logBuffer.append(obj1.toString()); logBuffer.append(' '); } public void jsFunction_error(Object obj1) { - log.error(obj1.toString()); + if (L.isEnabled(L.APS)) + log.error(obj1.toString()); errorBuffer.append(obj1.toString()); errorBuffer.append(' '); } - - public static String getScriptDebug(){ + public static String getScriptDebug() { String ret = ""; - if(errorBuffer.length() > 0){ + if (errorBuffer.length() > 0) { ret += "e:\n" + errorBuffer.toString(); } - if(ret.length() > 0 && logBuffer.length() > 0) ret += '\n'; - if(logBuffer.length() > 0){ + if (ret.length() > 0 && logBuffer.length() > 0) ret += '\n'; + if (logBuffer.length() > 0) { ret += "d:\n" + logBuffer.toString(); } return ret; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java index 7360bb8b2a..bcbc8119f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.OpenAPSMA; import android.app.Activity; import android.os.Bundle; -import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -12,10 +11,6 @@ import android.widget.TextView; import com.crashlytics.android.answers.CustomEvent; import com.squareup.otto.Subscribe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; @@ -24,8 +19,6 @@ import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.JSONFormatter; public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener { - private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class); - Button run; TextView lastRunView; TextView glucoseStatusView; @@ -87,25 +80,22 @@ public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClic protected void updateGUI() { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - DetermineBasalResultMA lastAPSResult = OpenAPSMAPlugin.getPlugin().lastAPSResult; - if (lastAPSResult != null) { - resultView.setText(JSONFormatter.format(lastAPSResult.json)); - requestView.setText(lastAPSResult.toSpanned()); - } - DetermineBasalAdapterMAJS determineBasalAdapterMAJS = OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS; - if (determineBasalAdapterMAJS != null) { - glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getGlucoseStatusParam())); - currentTempView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getCurrentTempParam())); - iobDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getIobDataParam())); - profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam())); - mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam())); - } - if (OpenAPSMAPlugin.getPlugin().lastAPSRun != null) { - lastRunView.setText(OpenAPSMAPlugin.getPlugin().lastAPSRun.toLocaleString()); - } + activity.runOnUiThread(() -> { + DetermineBasalResultMA lastAPSResult = OpenAPSMAPlugin.getPlugin().lastAPSResult; + if (lastAPSResult != null) { + resultView.setText(JSONFormatter.format(lastAPSResult.json)); + requestView.setText(lastAPSResult.toSpanned()); + } + DetermineBasalAdapterMAJS determineBasalAdapterMAJS = OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS; + if (determineBasalAdapterMAJS != null) { + glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getGlucoseStatusParam())); + currentTempView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getCurrentTempParam())); + iobDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getIobDataParam())); + profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam())); + mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam())); + } + if (OpenAPSMAPlugin.getPlugin().lastAPSRun != null) { + lastRunView.setText(OpenAPSMAPlugin.getPlugin().lastAPSRun.toLocaleString()); } }); } @@ -113,18 +103,15 @@ public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClic private void updateResultGUI(final String text) { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - resultView.setText(text); - glucoseStatusView.setText(""); - currentTempView.setText(""); - iobDataView.setText(""); - profileView.setText(""); - mealDataView.setText(""); - requestView.setText(""); - lastRunView.setText(""); - } + activity.runOnUiThread(() -> { + resultView.setText(text); + glucoseStatusView.setText(""); + currentTempView.setText(""); + iobDataView.setText(""); + profileView.setText(""); + mealDataView.setText(""); + requestView.setText(""); + lastRunView.setText(""); }); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java index 39d05f8ffb..5b57810632 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java @@ -4,10 +4,8 @@ import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.GlucoseStatus; @@ -21,7 +19,9 @@ 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.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; @@ -39,7 +39,7 @@ import static info.nightscout.utils.HardLimits.verifyHardLimits; * Created by mike on 05.08.2016. */ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { - private static Logger log = LoggerFactory.getLogger(OpenAPSMAPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.APS); private static OpenAPSMAPlugin openAPSMAPlugin; @@ -90,37 +90,33 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { @Override public void invoke(String initiator, boolean tempBasalFallback) { - log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); + if (L.isEnabled(L.APS)) + log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null; - try { - determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext())); - } catch (IOException e) { - log.error(e.getMessage(), e); - return; - } + determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext())); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (profile == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.noprofileselected)); return; } if (!isEnabled(PluginType.APS)) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); return; } @@ -147,7 +143,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); - Profiler.log(log, "MA data gathering", start); + if (L.isEnabled(L.APS)) + Profiler.log(log, "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]); @@ -177,7 +174,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface { } catch (JSONException e) { log.error("Unhandled exception", e); } - Profiler.log(log, "MA calculation", start); + if (L.isEnabled(L.APS)) + Profiler.log(log, "MA calculation", start); long now = System.currentTimeMillis(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java index e65cdd2c57..177133f155 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java @@ -6,7 +6,7 @@ import info.nightscout.androidaps.events.EventUpdateGui; * Created by mike on 05.08.2016. */ public class EventOpenAPSUpdateResultGui extends EventUpdateGui { - public String text = null; + public String text; public EventOpenAPSUpdateResultGui(String text) { this.text = text; 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 48a4c16ccd..7ede714c10 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 @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.OpenAPSSMB; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.mozilla.javascript.Callable; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeJSON; @@ -18,7 +17,6 @@ import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.InvocationTargetException; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -27,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.logging.L; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; @@ -35,10 +34,10 @@ import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; public class DetermineBasalAdapterSMBJS { - private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterSMBJS.class); + private static Logger log = LoggerFactory.getLogger(L.APS); - private ScriptReader mScriptReader = null; + private ScriptReader mScriptReader; private JSONObject mProfile; private JSONObject mGlucoseStatus; private JSONArray mIobData; @@ -64,7 +63,7 @@ public class DetermineBasalAdapterSMBJS { * Main code */ - public DetermineBasalAdapterSMBJS(ScriptReader scriptReader) throws IOException { + DetermineBasalAdapterSMBJS(ScriptReader scriptReader) { mScriptReader = scriptReader; } @@ -72,19 +71,21 @@ public class DetermineBasalAdapterSMBJS { public DetermineBasalResultSMB invoke() { - 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)); + 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)); + } DetermineBasalResultSMB determineBasalResultSMB = null; @@ -135,7 +136,7 @@ public class DetermineBasalAdapterSMBJS { // Parse the jsResult object to a JSON-String String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug("Result: " + result); try { determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result)); @@ -143,17 +144,13 @@ public class DetermineBasalAdapterSMBJS { log.error("Unhandled exception", e); } } else { - log.debug("Problem loading JS Functions"); + log.error("Problem loading JS Functions"); } } catch (IOException e) { - log.debug("IOException"); + log.error("IOException"); } catch (RhinoException e) { log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); - } catch (IllegalAccessException e) { - log.error(e.toString()); - } catch (InstantiationException e) { - log.error(e.toString()); - } catch (InvocationTargetException e) { + } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { log.error(e.toString()); } finally { Context.exit(); @@ -244,7 +241,7 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("maxCOB", SMBDefaults.maxCOB); mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps); //align with max-absorption model in AMA sensitivity - if(mealData.usedMinCarbsImpact > 0){ + if (mealData.usedMinCarbsImpact > 0) { mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); } else { mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); @@ -319,31 +316,21 @@ public class DetermineBasalAdapterSMBJS { } - public Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { + private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { if (jsonObject == null) return Undefined.instance; - Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), new Callable() { - @Override - public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) { - return objects[1]; - } - }); + Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]); return param; } - public Object makeParamArray(JSONArray jsonArray, Context rhino, Scriptable scope) { + private Object makeParamArray(JSONArray jsonArray, Context rhino, Scriptable scope) { //Object param = NativeJSON.parse(rhino, scope, "{myarray: " + jsonArray.toString() + " }", new Callable() { - Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), new Callable() { - @Override - public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) { - return objects[1]; - } - }); + Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), (context, scriptable, scriptable1, objects) -> objects[1]); return param; } - public String readFile(String filename) throws IOException { + private String readFile(String filename) throws IOException { byte[] bytes = mScriptReader.readFile(filename); String string = new String(bytes, "UTF-8"); if (string.startsWith("#!/usr/bin/env node")) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java index d5f108bf4f..bd41120e30 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java @@ -5,11 +5,12 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.utils.DateUtil; public class DetermineBasalResultSMB extends APSResult { - private static final Logger log = LoggerFactory.getLogger(DetermineBasalResultSMB.class); + private static final Logger log = LoggerFactory.getLogger(L.APS); private double eventualBG; private double snoozeBG; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java index 20ccd46b40..91b488e742 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java @@ -21,6 +21,7 @@ import butterknife.ButterKnife; import butterknife.OnClick; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; @@ -28,7 +29,7 @@ import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.JSONFormatter; public class OpenAPSSMBFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(OpenAPSSMBFragment.class); + private static Logger log = LoggerFactory.getLogger(L.APS); @BindView(R.id.openapsma_run) Button run; @@ -84,40 +85,37 @@ public class OpenAPSSMBFragment extends SubscriberFragment { protected void updateGUI() { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - synchronized (OpenAPSSMBFragment.this) { - if (!isBound()) return; - OpenAPSSMBPlugin plugin = OpenAPSSMBPlugin.getPlugin(); - DetermineBasalResultSMB lastAPSResult = plugin.lastAPSResult; - if (lastAPSResult != null) { - resultView.setText(JSONFormatter.format(lastAPSResult.json)); - requestView.setText(lastAPSResult.toSpanned()); - } - DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = plugin.lastDetermineBasalAdapterSMBJS; - if (determineBasalAdapterSMBJS != null) { - glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getGlucoseStatusParam()).toString().trim()); - currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim()); - try { - JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam()); - iobDataView.setText((String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim()); - } catch (JSONException e) { - log.error("Unhandled exception", e); - iobDataView.setText("JSONException see log for details"); - } - profileView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getProfileParam()).toString().trim()); - mealDataView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getMealDataParam()).toString().trim()); - scriptdebugView.setText(determineBasalAdapterSMBJS.getScriptDebug().trim()); - if (lastAPSResult != null && lastAPSResult.inputConstraints != null) - constraintsView.setText(lastAPSResult.inputConstraints.getReasons().trim()); - } - if (plugin.lastAPSRun != null) { - lastRunView.setText(plugin.lastAPSRun.toLocaleString().trim()); - } - if (plugin.lastAutosensResult != null) { - autosensDataView.setText(JSONFormatter.format(plugin.lastAutosensResult.json()).toString().trim()); + activity.runOnUiThread(() -> { + synchronized (OpenAPSSMBFragment.this) { + if (!isBound()) return; + OpenAPSSMBPlugin plugin = OpenAPSSMBPlugin.getPlugin(); + DetermineBasalResultSMB lastAPSResult = plugin.lastAPSResult; + if (lastAPSResult != null) { + resultView.setText(JSONFormatter.format(lastAPSResult.json)); + requestView.setText(lastAPSResult.toSpanned()); + } + DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = plugin.lastDetermineBasalAdapterSMBJS; + if (determineBasalAdapterSMBJS != null) { + glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getGlucoseStatusParam()).toString().trim()); + currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim()); + try { + JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam()); + iobDataView.setText((String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim()); + } catch (JSONException e) { + log.error("Unhandled exception", e); + iobDataView.setText("JSONException see log for details"); } + profileView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getProfileParam()).toString().trim()); + mealDataView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getMealDataParam()).toString().trim()); + scriptdebugView.setText(determineBasalAdapterSMBJS.getScriptDebug().trim()); + if (lastAPSResult != null && lastAPSResult.inputConstraints != null) + constraintsView.setText(lastAPSResult.inputConstraints.getReasons().trim()); + } + if (plugin.lastAPSRun != null) { + lastRunView.setText(plugin.lastAPSRun.toLocaleString().trim()); + } + if (plugin.lastAutosensResult != null) { + autosensDataView.setText(JSONFormatter.format(plugin.lastAutosensResult.json()).toString().trim()); } } }); @@ -126,22 +124,19 @@ public class OpenAPSSMBFragment extends SubscriberFragment { void updateResultGUI(final String text) { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - synchronized (OpenAPSSMBFragment.this) { - if (isBound()) { - resultView.setText(text); - glucoseStatusView.setText(""); - currentTempView.setText(""); - iobDataView.setText(""); - profileView.setText(""); - mealDataView.setText(""); - autosensDataView.setText(""); - scriptdebugView.setText(""); - requestView.setText(""); - lastRunView.setText(""); - } + activity.runOnUiThread(() -> { + synchronized (OpenAPSSMBFragment.this) { + if (isBound()) { + resultView.setText(text); + glucoseStatusView.setText(""); + currentTempView.setText(""); + iobDataView.setText(""); + profileView.setText(""); + mealDataView.setText(""); + autosensDataView.setText(""); + scriptdebugView.setText(""); + requestView.setText(""); + lastRunView.setText(""); } } }); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java index 570b76502f..5f6b13c416 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java @@ -1,14 +1,11 @@ package info.nightscout.androidaps.plugins.OpenAPSSMB; -import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import org.json.JSONException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.IOException; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.GlucoseStatus; @@ -23,17 +20,20 @@ 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.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.ScriptReader; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.HardLimits; -import info.nightscout.utils.NSUpload; import info.nightscout.utils.Profiler; import info.nightscout.utils.Round; import info.nightscout.utils.ToastUtils; @@ -42,7 +42,7 @@ import info.nightscout.utils.ToastUtils; * Created by mike on 05.08.2016. */ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { - private static Logger log = LoggerFactory.getLogger(OpenAPSSMBPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.APS); private static OpenAPSSMBPlugin openAPSSMBPlugin; @@ -94,37 +94,33 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { @Override public void invoke(String initiator, boolean tempBasalFallback) { - log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); + if (L.isEnabled(L.APS)) + log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback); lastAPSResult = null; - DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = null; - try { - determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext())); - } catch (IOException e) { - log.error(e.getMessage(), e); - return; - } + DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS; + determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext())); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (profile == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.noprofileselected)); return; } if (!isEnabled(PluginType.APS)) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.openapsma_disabled)); return; } if (glucoseStatus == null) { MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); - if (Config.logAPSResult) + if (L.isEnabled(L.APS)) log.debug(MainApp.gs(R.string.openapsma_noglucosedata)); return; } @@ -146,11 +142,13 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { Date start = new Date(); Date startPart = new Date(); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(profile); - Profiler.log(log, "calculateIobArrayInDia()", startPart); + if (L.isEnabled(L.APS)) + Profiler.log(log, "calculateIobArrayInDia()", startPart); startPart = new Date(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); - Profiler.log(log, "getMealData()", startPart); + if (L.isEnabled(L.APS)) + Profiler.log(log, "getMealData()", startPart); double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); @@ -170,7 +168,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) return; - if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) + if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) return; if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF)) return; @@ -200,8 +198,10 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); inputConstraints.copyReasons(advancedFiltering); - Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); - Profiler.log(log, "SMB data gathering", start); + if (L.isEnabled(L.APS)) + Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); + if (L.isEnabled(L.APS)) + Profiler.log(log, "SMB data gathering", start); start = new Date(); try { @@ -219,7 +219,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { long now = System.currentTimeMillis(); DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke(); - Profiler.log(log, "SMB calculation", start); + if (L.isEnabled(L.APS)) + Profiler.log(log, "SMB calculation", start); // TODO still needed with oref1? // Fix bug determine basal if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java index f0ccdd9809..f1f62c0bc4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/CalibrationDialog.java @@ -23,6 +23,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.NumberPicker; import info.nightscout.utils.SafeParse; @@ -63,7 +64,7 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis view.findViewById(R.id.ok).setOnClickListener(this); view.findViewById(R.id.cancel).setOnClickListener(this); - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, units); bgNumber = (NumberPicker) view.findViewById(R.id.overview_calibration_bg); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java index 7d45c35792..7c05b4398e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java @@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.AlarmSoundService; +import info.nightscout.androidaps.services.AlarmSoundService; public class ErrorDialog extends DialogFragment implements View.OnClickListener { private static Logger log = LoggerFactory.getLogger(ErrorDialog.class); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java index 90cf9aecd5..c556a6c844 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java @@ -4,7 +4,7 @@ import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import info.nightscout.androidaps.R; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; public class ErrorHelperActivity extends AppCompatActivity { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java index 26f46081ea..40450adf77 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewCarbsDialog.java @@ -21,7 +21,8 @@ import android.widget.RadioButton; import com.google.common.base.Joiner; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -157,13 +158,22 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C BgReading bgReading = DatabaseHelper.actualBg(); if (bgReading != null && bgReading.value < 72) { - startHypoTTCheckbox.setOnCheckedChangeListener(null); startHypoTTCheckbox.setChecked(true); + // see #onCheckedChanged why listeners are registered like this + startHypoTTCheckbox.setOnClickListener(this); + } else { + startHypoTTCheckbox.setOnCheckedChangeListener(this); } - startHypoTTCheckbox.setOnClickListener(this); setCancelable(true); getDialog().setCanceledOnTouchOutside(false); + + //recovering state if there is something + if (savedInstanceState != null) { + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editTime.setValue(savedInstanceState.getDouble("editTime")); + editDuration.setValue(savedInstanceState.getDouble("editDuration")); + } return view; } @@ -171,6 +181,19 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C return value > 0 ? "+" + value : String.valueOf(value); } + + @Override + public void onSaveInstanceState(Bundle carbsDialogState) { + carbsDialogState.putBoolean("startActivityTTCheckbox",startActivityTTCheckbox.isChecked()); + carbsDialogState.putBoolean("startEatingSoonTTCheckbox", startEatingSoonTTCheckbox.isChecked()); + carbsDialogState.putBoolean("startHypoTTCheckbox", startHypoTTCheckbox.isChecked()); + carbsDialogState.putDouble("editTime", editTime.getValue()); + carbsDialogState.putDouble("editDuration", editDuration.getValue()); + carbsDialogState.putDouble("editCarbs", editCarbs.getValue()); + super.onSaveInstanceState(carbsDialogState); + } + + @Override public synchronized void onClick(View view) { switch (view.getId()) { @@ -228,6 +251,8 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C } } + + @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // Logic to disable a selected radio when pressed: when a checked radio @@ -285,7 +310,7 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C } okClicked = true; try { - final Profile currentProfile = MainApp.getConfigBuilder().getProfile(); + final Profile currentProfile = ProfileFunctions.getInstance().getProfile(); if (currentProfile == null) { return; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewInsulinDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewInsulinDialog.java index 2889c8266b..1fad80af8f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewInsulinDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/NewInsulinDialog.java @@ -40,6 +40,7 @@ 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.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.DateUtil; @@ -208,7 +209,7 @@ public class NewInsulinDialog extends DialogFragment implements OnClickListener okClicked = true; try { - Profile currentProfile = MainApp.getConfigBuilder().getProfile(); + Profile currentProfile = ProfileFunctions.getInstance().getProfile(); if (currentProfile == null) return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java index 032104e103..7985418ada 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java @@ -56,6 +56,7 @@ import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; @@ -147,6 +148,23 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com MainApp.bus().unregister(this); } + @Override + public void onSaveInstanceState(Bundle savedInstanceState) { + savedInstanceState.putBoolean("bgCheckbox", bgCheckbox.isChecked()); + savedInstanceState.putBoolean("ttCheckbox", ttCheckbox.isChecked()); + savedInstanceState.putBoolean("bolusIobCheckbox", bolusIobCheckbox.isChecked()); + savedInstanceState.putBoolean("basalIobCheckbox", basalIobCheckbox.isChecked()); + savedInstanceState.putBoolean("bgtrendCheckbox", bgtrendCheckbox.isChecked()); + savedInstanceState.putBoolean("cobCheckbox", cobCheckbox.isChecked()); + savedInstanceState.putDouble("editBg", editBg.getValue()); + savedInstanceState.putDouble("editCarbs", editCarbs.getValue()); + savedInstanceState.putDouble("editCorr", editCorr.getValue()); + savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue()); + super.onSaveInstanceState(savedInstanceState); + } + + + @Subscribe public void onStatusEvent(final EventNewBG e) { Activity activity = getActivity(); @@ -259,6 +277,13 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com setCancelable(true); getDialog().setCanceledOnTouchOutside(false); + //recovering state if there is something + if (savedInstanceState != null) { + editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); + editBg.setValue(savedInstanceState.getDouble("editBg")); + editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime")); + editCorr.setValue(savedInstanceState.getDouble("editCorr")); + } return view; } @@ -301,7 +326,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com return; } okClicked = true; - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile != null && (calculatedTotalInsulin > 0d || calculatedCarbs > 0d)) { String confirmMessage = MainApp.gs(R.string.entertreatmentquestion); @@ -408,7 +433,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com } private void initDialog() { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface() != null ? MainApp.getConfigBuilder().getActiveProfileInterface().getProfile() : null; if (profile == null || profileStore == null) { @@ -459,7 +484,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString(); Profile specificProfile; if (selectedAlternativeProfile.equals(MainApp.gs(R.string.active))) - specificProfile = MainApp.getConfigBuilder().getProfile(); + specificProfile = ProfileFunctions.getInstance().getProfile(); else specificProfile = profileStore.getSpecificProfile(selectedAlternativeProfile); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java index 2b4ab247b8..6fc1e8d5dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewFragment.java @@ -80,12 +80,14 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Careportal.CareportalFragment; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; -import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; +import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; @@ -114,7 +116,7 @@ import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DefaultValueHelper; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.OKDialog; import info.nightscout.utils.Profiler; import info.nightscout.utils.SP; @@ -125,7 +127,7 @@ import info.nightscout.utils.ToastUtils; import static info.nightscout.utils.DateUtil.now; public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener { - private static Logger log = LoggerFactory.getLogger(OverviewFragment.class); + private static Logger log = LoggerFactory.getLogger(L.OVERVIEW); TextView timeView; TextView bgView; @@ -200,143 +202,136 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - //check screen width - final DisplayMetrics dm = new DisplayMetrics(); - getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); - int screen_width = dm.widthPixels; - int screen_height = dm.heightPixels; - smallWidth = screen_width <= Constants.SMALL_WIDTH; - smallHeight = screen_height <= Constants.SMALL_HEIGHT; - boolean landscape = screen_height < screen_width; + //check screen width + final DisplayMetrics dm = new DisplayMetrics(); + getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); + int screen_width = dm.widthPixels; + int screen_height = dm.heightPixels; + smallWidth = screen_width <= Constants.SMALL_WIDTH; + smallHeight = screen_height <= Constants.SMALL_HEIGHT; + boolean landscape = screen_height < screen_width; - View view; + View view; - if (MainApp.sResources.getBoolean(R.bool.isTablet) && (Config.NSCLIENT || Config.G5UPLOADER)) { - view = inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false); - } else if (Config.NSCLIENT || Config.G5UPLOADER) { - view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false); - shorttextmode = true; - } else if (smallHeight || landscape) { - view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false); - } else { - view = inflater.inflate(R.layout.overview_fragment, container, false); - } - - timeView = (TextView) view.findViewById(R.id.overview_time); - bgView = (TextView) view.findViewById(R.id.overview_bg); - arrowView = (TextView) view.findViewById(R.id.overview_arrow); - if (smallWidth) { - arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35); - } - sensitivityView = (TextView) view.findViewById(R.id.overview_sensitivity); - timeAgoView = (TextView) view.findViewById(R.id.overview_timeago); - timeAgoShortView = (TextView) view.findViewById(R.id.overview_timeagoshort); - deltaView = (TextView) view.findViewById(R.id.overview_delta); - deltaShortView = (TextView) view.findViewById(R.id.overview_deltashort); - avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta); - baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal); - extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus); - activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile); - pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus); - pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump); - openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps); - uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader); - iobCalculationProgressView = (TextView) view.findViewById(R.id.overview_iobcalculationprogess); - loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout); - pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout); - - pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); - - iobView = (TextView) view.findViewById(R.id.overview_iob); - cobView = (TextView) view.findViewById(R.id.overview_cob); - apsModeView = (TextView) view.findViewById(R.id.overview_apsmode); - tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget); - - iage = (TextView) view.findViewById(R.id.careportal_insulinage); - cage = (TextView) view.findViewById(R.id.careportal_canulaage); - sage = (TextView) view.findViewById(R.id.careportal_sensorage); - pbage = (TextView) view.findViewById(R.id.careportal_pbage); - - bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); - iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph); - - treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton); - treatmentButton.setOnClickListener(this); - wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton); - wizardButton.setOnClickListener(this); - insulinButton = (SingleClickButton) view.findViewById(R.id.overview_insulinbutton); - if (insulinButton != null) - insulinButton.setOnClickListener(this); - carbsButton = (SingleClickButton) view.findViewById(R.id.overview_carbsbutton); - if (carbsButton != null) - carbsButton.setOnClickListener(this); - acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton); - if (acceptTempButton != null) - acceptTempButton.setOnClickListener(this); - quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton); - quickWizardButton.setOnClickListener(this); - quickWizardButton.setOnLongClickListener(this); - calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton); - if (calibrationButton != null) - calibrationButton.setOnClickListener(this); - cgmButton = (SingleClickButton) view.findViewById(R.id.overview_cgmbutton); - if (cgmButton != null) - cgmButton.setOnClickListener(this); - - acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout); - - notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications); - notificationsView.setHasFixedSize(false); - llm = new LinearLayoutManager(view.getContext()); - notificationsView.setLayoutManager(llm); - - int axisWidth = 50; - - if (dm.densityDpi <= 120) - axisWidth = 3; - else if (dm.densityDpi <= 160) - axisWidth = 10; - else if (dm.densityDpi <= 320) - axisWidth = 35; - else if (dm.densityDpi <= 420) - axisWidth = 50; - else if (dm.densityDpi <= 560) - axisWidth = 70; - else - axisWidth = 80; - - bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); - bgGraph.getGridLabelRenderer().reloadStyles(); - iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); - iobGraph.getGridLabelRenderer().reloadStyles(); - iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false); - bgGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); - iobGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); - iobGraph.getGridLabelRenderer().setNumVerticalLabels(3); - - rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6); - - bgGraph.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - rangeToDisplay += 6; - rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; - SP.putInt(R.string.key_rangetodisplay, rangeToDisplay); - updateGUI("rangeChange"); - return false; - } - }); - - setupChartMenu(view); - - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - log.debug("Runtime Exception", e); + if (MainApp.sResources.getBoolean(R.bool.isTablet) && (Config.NSCLIENT || Config.G5UPLOADER)) { + view = inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false); + } else if (Config.NSCLIENT || Config.G5UPLOADER) { + view = inflater.inflate(R.layout.overview_fragment_nsclient, container, false); + shorttextmode = true; + } else if (smallHeight || landscape) { + view = inflater.inflate(R.layout.overview_fragment_smallheight, container, false); + } else { + view = inflater.inflate(R.layout.overview_fragment, container, false); } - return null; + timeView = (TextView) view.findViewById(R.id.overview_time); + bgView = (TextView) view.findViewById(R.id.overview_bg); + arrowView = (TextView) view.findViewById(R.id.overview_arrow); + if (smallWidth) { + arrowView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35); + } + sensitivityView = (TextView) view.findViewById(R.id.overview_sensitivity); + timeAgoView = (TextView) view.findViewById(R.id.overview_timeago); + timeAgoShortView = (TextView) view.findViewById(R.id.overview_timeagoshort); + deltaView = (TextView) view.findViewById(R.id.overview_delta); + deltaShortView = (TextView) view.findViewById(R.id.overview_deltashort); + avgdeltaView = (TextView) view.findViewById(R.id.overview_avgdelta); + baseBasalView = (TextView) view.findViewById(R.id.overview_basebasal); + extendedBolusView = (TextView) view.findViewById(R.id.overview_extendedbolus); + activeProfileView = (TextView) view.findViewById(R.id.overview_activeprofile); + pumpStatusView = (TextView) view.findViewById(R.id.overview_pumpstatus); + pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump); + openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps); + uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader); + iobCalculationProgressView = (TextView) view.findViewById(R.id.overview_iobcalculationprogess); + loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout); + pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout); + + pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); + + iobView = (TextView) view.findViewById(R.id.overview_iob); + cobView = (TextView) view.findViewById(R.id.overview_cob); + apsModeView = (TextView) view.findViewById(R.id.overview_apsmode); + tempTargetView = (TextView) view.findViewById(R.id.overview_temptarget); + + iage = (TextView) view.findViewById(R.id.careportal_insulinage); + cage = (TextView) view.findViewById(R.id.careportal_canulaage); + sage = (TextView) view.findViewById(R.id.careportal_sensorage); + pbage = (TextView) view.findViewById(R.id.careportal_pbage); + + bgGraph = (GraphView) view.findViewById(R.id.overview_bggraph); + iobGraph = (GraphView) view.findViewById(R.id.overview_iobgraph); + + treatmentButton = (SingleClickButton) view.findViewById(R.id.overview_treatmentbutton); + treatmentButton.setOnClickListener(this); + wizardButton = (SingleClickButton) view.findViewById(R.id.overview_wizardbutton); + wizardButton.setOnClickListener(this); + insulinButton = (SingleClickButton) view.findViewById(R.id.overview_insulinbutton); + if (insulinButton != null) + insulinButton.setOnClickListener(this); + carbsButton = (SingleClickButton) view.findViewById(R.id.overview_carbsbutton); + if (carbsButton != null) + carbsButton.setOnClickListener(this); + acceptTempButton = (SingleClickButton) view.findViewById(R.id.overview_accepttempbutton); + if (acceptTempButton != null) + acceptTempButton.setOnClickListener(this); + quickWizardButton = (SingleClickButton) view.findViewById(R.id.overview_quickwizardbutton); + quickWizardButton.setOnClickListener(this); + quickWizardButton.setOnLongClickListener(this); + calibrationButton = (SingleClickButton) view.findViewById(R.id.overview_calibrationbutton); + if (calibrationButton != null) + calibrationButton.setOnClickListener(this); + cgmButton = (SingleClickButton) view.findViewById(R.id.overview_cgmbutton); + if (cgmButton != null) + cgmButton.setOnClickListener(this); + + acceptTempLayout = (LinearLayout) view.findViewById(R.id.overview_accepttemplayout); + + notificationsView = (RecyclerView) view.findViewById(R.id.overview_notifications); + notificationsView.setHasFixedSize(false); + llm = new LinearLayoutManager(view.getContext()); + notificationsView.setLayoutManager(llm); + + int axisWidth = 50; + + if (dm.densityDpi <= 120) + axisWidth = 3; + else if (dm.densityDpi <= 160) + axisWidth = 10; + else if (dm.densityDpi <= 320) + axisWidth = 35; + else if (dm.densityDpi <= 420) + axisWidth = 50; + else if (dm.densityDpi <= 560) + axisWidth = 70; + else + axisWidth = 80; + + bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); + bgGraph.getGridLabelRenderer().reloadStyles(); + iobGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid)); + iobGraph.getGridLabelRenderer().reloadStyles(); + iobGraph.getGridLabelRenderer().setHorizontalLabelsVisible(false); + bgGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); + iobGraph.getGridLabelRenderer().setLabelVerticalWidth(axisWidth); + iobGraph.getGridLabelRenderer().setNumVerticalLabels(3); + + rangeToDisplay = SP.getInt(R.string.key_rangetodisplay, 6); + + bgGraph.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View v) { + rangeToDisplay += 6; + rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay; + SP.putInt(R.string.key_rangetodisplay, rangeToDisplay); + updateGUI("rangeChange"); + return false; + } + }); + + setupChartMenu(view); + + return view; } private void setupChartMenu(View view) { @@ -459,7 +454,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, if (v == apsModeView) { final LoopPlugin loopPlugin = LoopPlugin.getPlugin(); final PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription(); - if (loopPlugin == null || !MainApp.getConfigBuilder().isProfileValid("ContexMenuCreation")) + if (!ProfileFunctions.getInstance().isProfileValid("ContexMenuCreation")) return; menu.setHeaderTitle(MainApp.gs(R.string.loop)); if (loopPlugin.isEnabled(PluginType.LOOP)) { @@ -502,7 +497,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, @Override public boolean onContextItemSelected(MenuItem item) { - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return true; final LoopPlugin loopPlugin = LoopPlugin.getPlugin(); @@ -542,39 +537,39 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, NSUpload.uploadOpenAPSOffline(0); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.suspendloopfor1h))) { - MainApp.getConfigBuilder().suspendLoop(60); + LoopPlugin.getPlugin().suspendLoop(60); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.suspendloopfor2h))) { - MainApp.getConfigBuilder().suspendLoop(120); + LoopPlugin.getPlugin().suspendLoop(120); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.suspendloopfor3h))) { - MainApp.getConfigBuilder().suspendLoop(180); + LoopPlugin.getPlugin().suspendLoop(180); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.suspendloopfor10h))) { - MainApp.getConfigBuilder().suspendLoop(600); + LoopPlugin.getPlugin().suspendLoop(600); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.disconnectpumpfor15m))) { - MainApp.getConfigBuilder().disconnectPump(15, profile); + LoopPlugin.getPlugin().disconnectPump(15, profile); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.disconnectpumpfor30m))) { - MainApp.getConfigBuilder().disconnectPump(30, profile); + LoopPlugin.getPlugin().disconnectPump(30, profile); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.disconnectpumpfor1h))) { - MainApp.getConfigBuilder().disconnectPump(60, profile); + LoopPlugin.getPlugin().disconnectPump(60, profile); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.disconnectpumpfor2h))) { - MainApp.getConfigBuilder().disconnectPump(120, profile); + LoopPlugin.getPlugin().disconnectPump(120, profile); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.disconnectpumpfor3h))) { - MainApp.getConfigBuilder().disconnectPump(180, profile); + LoopPlugin.getPlugin().disconnectPump(180, profile); updateGUI("suspendmenu"); return true; } else if (item.getTitle().equals(MainApp.gs(R.string.careportal_profileswitch))) { @@ -589,7 +584,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, pvd.show(manager, "ProfileViewDialog"); } else if (item.getTitle().equals(MainApp.gs(R.string.eatingsoon))) { DefaultValueHelper defHelper = new DefaultValueHelper(); - double target = defHelper.determineEatingSoonTT(profile.getUnits()); + double target = defHelper.determineEatingSoonTT(Constants.MGDL); TempTarget tempTarget = new TempTarget() .date(System.currentTimeMillis()) .duration(defHelper.determineEatingSoonTTDuration()) @@ -600,7 +595,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget); } else if (item.getTitle().equals(MainApp.gs(R.string.activity))) { DefaultValueHelper defHelper = new DefaultValueHelper(); - double target = defHelper.determineActivityTT(profile.getUnits()); + double target = defHelper.determineActivityTT(Constants.MGDL); TempTarget tempTarget = new TempTarget() .date(now()) .duration(defHelper.determineActivityTTDuration()) @@ -611,7 +606,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget); } else if (item.getTitle().equals(MainApp.gs(R.string.hypo))) { DefaultValueHelper defHelper = new DefaultValueHelper(); - double target = defHelper.determineHypoTT(profile.getUnits()); + double target = defHelper.determineHypoTT(Constants.MGDL); TempTarget tempTarget = new TempTarget() .date(now()) .duration(defHelper.determineHypoTTDuration()) @@ -643,7 +638,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, public void onClick(View v) { boolean xdrip = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE); boolean g5 = MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class) != null && MainApp.getSpecificPlugin(SourceDexcomG5Plugin.class).isEnabled(PluginType.BGSOURCE); - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); FragmentManager manager = getFragmentManager(); // try to fix https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days @@ -731,7 +726,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } private void onClickAcceptTemp() { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); Context context = getContext(); if (context == null) return; @@ -746,7 +741,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> { hideTempRecommendation(); clearNotification(); - MainApp.getConfigBuilder().applyTBRRequest(finalLastRun.constraintsProcessed, profile, new Callback() { + LoopPlugin.getPlugin().applyTBRRequest(finalLastRun.constraintsProcessed, profile, new Callback() { @Override public void run() { if (result.enacted) { @@ -773,7 +768,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, void onClickQuickwizard() { final BgReading actualBg = DatabaseHelper.actualBg(); - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); final TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory(); final QuickWizardEntry quickWizardEntry = OverviewPlugin.getPlugin().quickWizard.getActive(); @@ -832,7 +827,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> { synchronized (builder) { if (accepted) { - log.debug("guarding: already accepted"); + if (L.isEnabled(L.OVERVIEW)) + log.debug("guarding: already accepted"); return; } accepted = true; @@ -1037,7 +1033,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, @SuppressLint("SetTextI18n") public void updateGUI(final String from) { - log.debug("updateGUI entered from: " + from); + if (L.isEnabled(L.OVERVIEW)) + log.debug("updateGUI entered from: " + from); final Date updateGUIStart = new Date(); if (getActivity() == null) @@ -1052,7 +1049,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, pumpStatusLayout.setVisibility(View.GONE); loopStatusLayout.setVisibility(View.GONE); - if (!MainApp.getConfigBuilder().isProfileValid("Overview")) { + if (!ProfileFunctions.getInstance().isProfileValid("Overview")) { pumpStatusView.setText(R.string.noprofileset); pumpStatusLayout.setVisibility(View.VISIBLE); return; @@ -1065,7 +1062,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); final String units = profile.getUnits(); final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units); @@ -1249,7 +1246,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, extendedBolusView.setVisibility(View.VISIBLE); } - activeProfileView.setText(MainApp.getConfigBuilder().getProfileName()); + activeProfileView.setText(ProfileFunctions.getInstance().getProfileName()); activeProfileView.setBackgroundColor(Color.GRAY); // QuickWizard button @@ -1384,9 +1381,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, // Sensitivity if (sensitivityView != null) { - AutosensResult lastAutosensResult = IobCobCalculatorPlugin.getPlugin().detectSensitivityWithLock(IobCobCalculatorPlugin.getPlugin().oldestDataAvailable(), System.currentTimeMillis()); - if (lastAutosensResult != null) - sensitivityView.setText(String.format("%.0f%%", lastAutosensResult.ratio * 100)); + AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("Overview"); + if (autosensData != null) + sensitivityView.setText(String.format("%.0f%%", autosensData.autosensResult.ratio * 100)); else sensitivityView.setText(""); } @@ -1432,7 +1429,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, final long now = System.currentTimeMillis(); // ------------------ 1st graph - Profiler.log(log, from + " - 1st graph - START", updateGUIStart); + if (L.isEnabled(L.OVERVIEW)) + Profiler.log(log, from + " - 1st graph - START", updateGUIStart); final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin()); @@ -1464,7 +1462,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, graphData.addNowLine(now); // ------------------ 2nd graph - Profiler.log(log, from + " - 2nd graph - START", updateGUIStart); + if (L.isEnabled(L.OVERVIEW)) + Profiler.log(log, from + " - 2nd graph - START", updateGUIStart); final GraphData secondGraphData = new GraphData(iobGraph, IobCobCalculatorPlugin.getPlugin()); @@ -1518,12 +1517,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, // finally enforce drawing of graphs graphData.performUpdate(); secondGraphData.performUpdate(); - Profiler.log(log, from + " - onDataChanged", updateGUIStart); + if (L.isEnabled(L.OVERVIEW)) + Profiler.log(log, from + " - onDataChanged", updateGUIStart); }); } }).start(); - Profiler.log(log, from, updateGUIStart); + if (L.isEnabled(L.OVERVIEW)) + Profiler.log(log, from, updateGUIStart); } //Notifications diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java index 3b787fd768..b184201908 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java @@ -15,6 +15,8 @@ import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore; @@ -24,7 +26,7 @@ import info.nightscout.utils.SP; * Created by mike on 05.08.2016. */ public class OverviewPlugin extends PluginBase { - private static Logger log = LoggerFactory.getLogger(OverviewPlugin.class); + private static Logger log = LoggerFactory.getLogger(L.OVERVIEW); private static OverviewPlugin overviewPlugin = new OverviewPlugin(); @@ -91,7 +93,7 @@ public class OverviewPlugin extends PluginBase { } public double determineLowLine() { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { return bgTargetLow; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java index 6f9526369e..18e8ff91bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java @@ -7,7 +7,6 @@ import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.Event; public class EventOverviewBolusProgress extends Event { - private static Logger log = LoggerFactory.getLogger(EventOverviewBolusProgress.class); public String status = ""; public Treatment t = null; public int percent = 0; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java index 20feb76124..30ed626b89 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/graphData/GraphData.java @@ -11,6 +11,9 @@ import com.jjoe64.graphview.series.DataPoint; import com.jjoe64.graphview.series.LineGraphSeries; import com.jjoe64.graphview.series.Series; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -24,7 +27,9 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.TempTarget; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.BasalData; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; @@ -47,6 +52,7 @@ import info.nightscout.utils.Round; */ public class GraphData { + private static Logger log = LoggerFactory.getLogger(L.OVERVIEW); private GraphView graph; public double maxY = Double.MIN_VALUE; @@ -58,21 +64,25 @@ public class GraphData { private IobCobCalculatorPlugin iobCobCalculatorPlugin; public GraphData(GraphView graph, IobCobCalculatorPlugin iobCobCalculatorPlugin) { - units = MainApp.getConfigBuilder().getProfileUnits(); + units = ProfileFunctions.getInstance().getProfileUnits(); this.graph = graph; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; } public void addBgReadings(long fromTime, long toTime, double lowLine, double highLine, List predictions) { double maxBgValue = Double.MIN_VALUE; - bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true); + //bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true); + bgReadingsArray = iobCobCalculatorPlugin.getBgReadings(); List bgListArray = new ArrayList<>(); - if (bgReadingsArray.size() == 0) { + if (bgReadingsArray == null || bgReadingsArray.size() == 0) { + if (L.isEnabled(L.OVERVIEW)) + log.debug("No BG data."); return; } for (BgReading bg : bgReadingsArray) { + if (bg.date < fromTime || bg.date > toTime) continue; if (bg.value > maxBgValue) maxBgValue = bg.value; bgListArray.add(bg); } @@ -135,9 +145,9 @@ public class GraphData { double lastBaseBasal = 0; double lastTempBasal = 0; for (long time = fromTime; time < toTime; time += 60 * 1000L) { - Profile profile = MainApp.getConfigBuilder().getProfile(time); + Profile profile = ProfileFunctions.getInstance().getProfile(time); if (profile == null) continue; - BasalData basalData = IobCobCalculatorPlugin.getPlugin().getBasalData(profile, time); + BasalData basalData = iobCobCalculatorPlugin.getBasalData(profile, time); double baseBasalValue = basalData.basal; double absoluteLineValue = baseBasalValue; double tempBasalValue = 0; @@ -321,13 +331,13 @@ public class GraphData { } private double getNearestBg(long date) { - for (int r = bgReadingsArray.size() - 1; r >= 0; r--) { + for (int r = 0; r < bgReadingsArray.size(); r++) { BgReading reading = bgReadingsArray.get(r); if (reading.date > date) continue; return Profile.fromMgdlToUnits(reading.value, units); } return bgReadingsArray.size() > 0 - ? Profile.fromMgdlToUnits(bgReadingsArray.get(0).value, units) : 0; + ? Profile.fromMgdlToUnits(bgReadingsArray.get(0).value, units) : Profile.fromMgdlToUnits(100, units); } // scale in % of vertical size (like 0.3) @@ -339,10 +349,10 @@ public class GraphData { Scale iobScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - Profile profile = MainApp.getConfigBuilder().getProfile(time); + Profile profile = ProfileFunctions.getInstance().getProfile(time); double iob = 0d; if (profile != null) - iob = IobCobCalculatorPlugin.getPlugin().calculateFromTreatmentsAndTempsSynchronized(time, profile).iob; + iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTempsSynchronized(time, profile).iob; if (Math.abs(lastIob - iob) > 0.02) { if (Math.abs(lastIob - iob) > 0.2) iobArray.add(new ScaledDataPoint(time, lastIob, iobScale)); @@ -380,7 +390,7 @@ public class GraphData { Scale cobScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { int cob = (int) autosensData.cob; if (cob != lastCob) { @@ -438,7 +448,7 @@ public class GraphData { Scale devScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { int color = MainApp.gc(R.color.deviationblack); // "=" if (autosensData.type.equals("") || autosensData.type.equals("non-meal")) { @@ -488,7 +498,7 @@ public class GraphData { Scale ratioScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { ratioArray.add(new ScaledDataPoint(time, autosensData.autosensResult.ratio - 1, ratioScale)); maxRatioValueFound = Math.max(maxRatioValueFound, autosensData.autosensResult.ratio - 1); @@ -504,11 +514,11 @@ public class GraphData { ratioSeries.setThickness(3); if (useForScale) { - maxY = maxRatioValueFound; - minY = minRatioValueFound; + maxY = Math.max(maxRatioValueFound, Math.abs(minRatioValueFound)); + minY = -maxY; } - ratioScale.setMultiplier(maxY * scale / maxRatioValueFound); + ratioScale.setMultiplier(maxY * scale / Math.max(maxRatioValueFound, Math.abs(minRatioValueFound))); addSeries(ratioSeries); } @@ -525,7 +535,7 @@ public class GraphData { Scale dsMinScale = new Scale(); for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { - AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); + AutosensData autosensData = iobCobCalculatorPlugin.getAutosensData(time); if (autosensData != null) { dsMaxArray.add(new ScaledDataPoint(time, autosensData.slopeFromMaxDeviation, dsMaxScale)); dsMinArray.add(new ScaledDataPoint(time, autosensData.slopeFromMinDeviation, dsMinScale)); @@ -604,8 +614,10 @@ public class GraphData { } } - graph.getViewport().setMaxY(Round.ceilTo(maxY, 1d)); - graph.getViewport().setMinY(Round.floorTo(minY, 1d)); + double step = 1d; + if (maxY < 1) step = 0.1d; + graph.getViewport().setMaxY(Round.ceilTo(maxY, step)); + graph.getViewport().setMinY(Round.floorTo(minY, step)); graph.getViewport().setYAxisBoundsManual(true); // draw it diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java index 8c91e2896b..57e6b72377 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/Notification.java @@ -20,8 +20,6 @@ import info.nightscout.utils.SP; */ public class Notification { - private static Logger log = LoggerFactory.getLogger(Notification.class); - public static final int URGENT = 0; public static final int NORMAL = 1; public static final int LOW = 2; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java index 895b99a43e..9af6be3be3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/notifications/NotificationRecyclerViewAdapter.java @@ -17,6 +17,7 @@ import java.util.Objects; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; @@ -24,7 +25,7 @@ import info.nightscout.utils.DateUtil; import info.nightscout.utils.SP; public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter { - private static Logger log = LoggerFactory.getLogger(NotificationRecyclerViewAdapter.class); + private static Logger log = LoggerFactory.getLogger(L.NOTIFICATION); private List notificationsList; @@ -96,11 +97,13 @@ public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter store = new ArrayList(); - public long snoozedUntil = 0L; + private static Logger log = LoggerFactory.getLogger(L.NOTIFICATION); + public List store = new ArrayList<>(); private boolean usesChannels; public NotificationStore() { @@ -52,7 +52,8 @@ public class NotificationStore { } public synchronized boolean add(Notification n) { - log.info("Notification received: " + n.text); + if (L.isEnabled(L.NOTIFICATION)) + log.debug("Notification received: " + n.text); for (Notification storeNotification : store) { if (storeNotification.id == n.id) { storeNotification.date = n.date; @@ -107,7 +108,8 @@ public class NotificationStore { } public void snoozeTo(long timeToSnooze) { - log.debug("Snoozing alarm until: " + timeToSnooze); + if (L.isEnabled(L.NOTIFICATION)) + log.debug("Snoozing alarm until: " + timeToSnooze); SP.putLong("snoozedTo", timeToSnooze); } @@ -116,7 +118,8 @@ public class NotificationStore { Notification notification = new Notification(Notification.NSALARM, MainApp.gs(R.string.nsalarm_staledata), Notification.URGENT); SP.putLong("snoozedTo", System.currentTimeMillis()); add(notification); - log.debug("Snoozed to current time and added back notification!"); + if (L.isEnabled(L.NOTIFICATION)) + log.debug("Snoozed to current time and added back notification!"); } } @@ -125,7 +128,7 @@ public class NotificationStore { NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(), R.mipmap.blueowl); int smallIcon = R.drawable.ic_notification; - if (Config.NSCLIENT || Config.G5UPLOADER){ + if (Config.NSCLIENT || Config.G5UPLOADER) { largeIcon = BitmapFactory.decodeResource(MainApp.instance().getResources(), R.mipmap.yellowowl); smallIcon = R.drawable.nsclient_smallicon; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java index f6a9494a20..f87643fcf8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java @@ -37,6 +37,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DecimalFormatter; @@ -108,9 +109,9 @@ public class PersistentNotificationPlugin extends PluginBase { String line1 = ""; - if (MainApp.getConfigBuilder().getActiveProfileInterface() == null || !MainApp.getConfigBuilder().isProfileValid("Notificiation")) + if (MainApp.getConfigBuilder().getActiveProfileInterface() == null || !ProfileFunctions.getInstance().isProfileValid("Notificiation")) return null; - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); BgReading lastBG = DatabaseHelper.lastBg(); @@ -147,7 +148,7 @@ public class PersistentNotificationPlugin extends PluginBase { String line3 = DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getActivePump().getBaseBasalRate()) + " U/h"; - line3 += " - " + MainApp.getConfigBuilder().getProfileName(); + line3 += " - " + ProfileFunctions.getInstance().getProfileName(); NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java index 18060ba1ec..3fab80855a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfileFragment.java @@ -25,20 +25,18 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.interfaces.PumpDescription; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Careportal.CareportalFragment; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.utils.DecimalFormatter; -import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.NumberPicker; import info.nightscout.utils.SafeParse; import info.nightscout.utils.TimeListEdit; public class LocalProfileFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(LocalProfileFragment.class); - NumberPicker diaView; RadioButton mgdlView; RadioButton mmolView; @@ -81,80 +79,72 @@ public class LocalProfileFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { + PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription(); + View layout = inflater.inflate(R.layout.localprofile_fragment, container, false); + diaView = (NumberPicker) layout.findViewById(R.id.localprofile_dia); + diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch); + mgdlView = (RadioButton) layout.findViewById(R.id.localprofile_mgdl); + mmolView = (RadioButton) layout.findViewById(R.id.localprofile_mmol); + icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.gs(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save); + isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.gs(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save); + basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.gs(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save); + targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.gs(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save); + profileswitchButton = (Button) layout.findViewById(R.id.localprofile_profileswitch); + resetButton = (Button) layout.findViewById(R.id.localprofile_reset); + saveButton = (Button) layout.findViewById(R.id.localprofile_save); - PumpDescription pumpDescription = ConfigBuilderPlugin.getActivePump().getPumpDescription(); - View layout = inflater.inflate(R.layout.localprofile_fragment, container, false); - diaView = (NumberPicker) layout.findViewById(R.id.localprofile_dia); - diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch); - mgdlView = (RadioButton) layout.findViewById(R.id.localprofile_mgdl); - mmolView = (RadioButton) layout.findViewById(R.id.localprofile_mmol); + + invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile); + + if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) { + layout.findViewById(R.id.localprofile_basal).setVisibility(View.GONE); + } + + mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); + mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); + + mgdlView.setOnClickListener(v -> { + LocalProfilePlugin.getPlugin().mgdl = mgdlView.isChecked(); + LocalProfilePlugin.getPlugin().mmol = !LocalProfilePlugin.getPlugin().mgdl; + mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); + doEdit(); + }); + mmolView.setOnClickListener(v -> { + LocalProfilePlugin.getPlugin().mmol = mmolView.isChecked(); + LocalProfilePlugin.getPlugin().mgdl = !LocalProfilePlugin.getPlugin().mmol; + mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); + doEdit(); + }); + + profileswitchButton.setOnClickListener(view -> { + NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); + final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCHDIRECT; + profileswitch.executeProfileSwitch = true; + newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); + newDialog.show(getFragmentManager(), "NewNSTreatmentDialog"); + }); + + resetButton.setOnClickListener(view -> { + LocalProfilePlugin.getPlugin().loadSettings(); + mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); + mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); + diaView.setParams(LocalProfilePlugin.getPlugin().dia, 5d, 12d, 0.1d, new DecimalFormat("0.0"), false, textWatch); icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.gs(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save); isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.gs(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save); basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.gs(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save); targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.gs(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save); - profileswitchButton = (Button) layout.findViewById(R.id.localprofile_profileswitch); - resetButton = (Button) layout.findViewById(R.id.localprofile_reset); - saveButton = (Button) layout.findViewById(R.id.localprofile_save); + updateGUI(); + }); - - invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile); - - if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) { - layout.findViewById(R.id.localprofile_basal).setVisibility(View.GONE); + saveButton.setOnClickListener(view -> { + if (!LocalProfilePlugin.getPlugin().isValidEditState()) { + return; //Should not happen as saveButton should not be visible if not valid } + LocalProfilePlugin.getPlugin().storeSettings(); + updateGUI(); + }); - mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); - mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); - - mgdlView.setOnClickListener(v -> { - LocalProfilePlugin.getPlugin().mgdl = mgdlView.isChecked(); - LocalProfilePlugin.getPlugin().mmol = !LocalProfilePlugin.getPlugin().mgdl; - mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); - doEdit(); - }); - mmolView.setOnClickListener(v -> { - LocalProfilePlugin.getPlugin().mmol = mmolView.isChecked(); - LocalProfilePlugin.getPlugin().mgdl = !LocalProfilePlugin.getPlugin().mmol; - mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); - doEdit(); - }); - - profileswitchButton.setOnClickListener(view -> { - NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); - final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCHDIRECT; - profileswitch.executeProfileSwitch = true; - newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); - newDialog.show(getFragmentManager(), "NewNSTreatmentDialog"); - }); - - resetButton.setOnClickListener(view -> { - LocalProfilePlugin.getPlugin().loadSettings(); - mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); - mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); - diaView.setParams(LocalProfilePlugin.getPlugin().dia, 5d, 12d, 0.1d, new DecimalFormat("0.0"), false, textWatch); - icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.gs(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save); - isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.gs(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save); - basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.gs(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save); - targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.gs(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save); - updateGUI(); - }); - - saveButton.setOnClickListener(view -> { - if(!LocalProfilePlugin.getPlugin().isValidEditState()){ - return; //Should not happen as saveButton should not be visible if not valid - } - LocalProfilePlugin.getPlugin().storeSettings(); - updateGUI(); - }); - - return layout; - } catch (Exception e) { - log.error("Unhandled exception: ", e); - FabricPrivacy.logException(e); - } - - return null; + return layout; } public void doEdit() { @@ -203,7 +193,7 @@ public class LocalProfileFragment extends SubscriberFragment { } //Show reset button iff data was edited - if(isEdited) { + if (isEdited) { resetButton.setVisibility(View.VISIBLE); } else { resetButton.setVisibility(View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java index 8d4e2d6a36..7a06860327 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileLocal/LocalProfilePlugin.java @@ -8,7 +8,6 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -18,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.SP; @@ -26,7 +26,7 @@ import info.nightscout.utils.SP; */ public class LocalProfilePlugin extends PluginBase implements ProfileInterface { public static final String LOCAL_PROFILE = "LocalProfile"; - private static Logger log = LoggerFactory.getLogger(LocalProfilePlugin.class); + private static Logger log = LoggerFactory.getLogger(L.PROFILE); private static LocalProfilePlugin localProfilePlugin; @@ -81,13 +81,13 @@ public class LocalProfilePlugin extends PluginBase implements ProfileInterface { createAndStoreConvertedProfile(); edited = false; - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Storing settings: " + getRawProfile().getData().toString()); MainApp.bus().post(new EventProfileStoreChanged()); } public synchronized void loadSettings() { - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Loading stored settings"); mgdl = SP.getBoolean(LOCAL_PROFILE + "mgdl", false); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java index 6cc9fdf98e..e3aeca0c45 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java @@ -24,10 +24,10 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI; import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph; import info.nightscout.utils.DecimalFormatter; -import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.OKDialog; import static butterknife.OnItemSelected.Callback.NOTHING_SELECTED; @@ -62,24 +62,22 @@ public class NSProfileFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.nsprofile_fragment, container, false); + View view = inflater.inflate(R.layout.nsprofile_fragment, container, false); - unbinder = ButterKnife.bind(this, view); - updateGUI(); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } - - return null; + unbinder = ButterKnife.bind(this, view); + updateGUI(); + return view; } @Subscribe public void onStatusEvent(final EventNSProfileUpdateGUI ev) { Activity activity = getActivity(); if (activity != null) - activity.runOnUiThread(() -> { synchronized (NSProfileFragment.this) { updateGUI(); } }); + activity.runOnUiThread(() -> { + synchronized (NSProfileFragment.this) { + updateGUI(); + } + }); } @Override @@ -95,7 +93,7 @@ public class NSProfileFragment extends SubscriberFragment { profileSpinner.setAdapter(adapter); // set selected to actual profile for (int p = 0; p < profileList.size(); p++) { - if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName())) + if (profileList.get(p).equals(ProfileFunctions.getInstance().getProfileName())) profileSpinner.setSelection(p); } noProfile.setVisibility(View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java index 404aff0608..99e4ad9115 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfilePlugin.java @@ -1,10 +1,9 @@ package info.nightscout.androidaps.plugins.ProfileNS; import android.content.Intent; +import android.os.Bundle; import android.support.annotation.Nullable; -import com.squareup.otto.Subscribe; - import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -14,7 +13,8 @@ import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.events.EventProfileStoreChanged; import info.nightscout.androidaps.interfaces.PluginBase; @@ -28,7 +28,7 @@ import info.nightscout.utils.SP; * Created by mike on 05.08.2016. */ public class NSProfilePlugin extends PluginBase implements ProfileInterface { - private static Logger log = LoggerFactory.getLogger(NSProfilePlugin.class); + private static Logger log = LoggerFactory.getLogger(L.PROFILE); private static NSProfilePlugin nsProfilePlugin; @@ -65,41 +65,51 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface { MainApp.bus().unregister(this); } - @Subscribe - public void storeNewProfile(ProfileStore newProfile) { - profile = new ProfileStore(newProfile.getData()); - storeNSProfile(); - MainApp.bus().post(new EventNSProfileUpdateGUI()); - MainApp.bus().post(new EventProfileStoreChanged()); + public void handleNewData(Intent intent) { + try { + Bundle bundles = intent.getExtras(); + if (bundles == null) return; + + String activeProfile = bundles.getString("activeprofile"); + String profileString = bundles.getString("profile"); + profile = new ProfileStore(new JSONObject(profileString)); + storeNSProfile(); + if (isEnabled(PluginType.PROFILE)) { + MainApp.bus().post(new EventProfileStoreChanged()); + MainApp.bus().post(new EventNSProfileUpdateGUI()); + } + if (L.isEnabled(L.PROFILE)) + log.debug("Received profileStore: " + activeProfile + " " + profile); + } catch (JSONException e) { + log.error("Unhandled exception", e); + } } private void storeNSProfile() { SP.putString("profile", profile.getData().toString()); - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Storing profile"); } private void loadNSProfile() { - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Loading stored profile"); String profileString = SP.getString("profile", null); if (profileString != null) { - if (Config.logPrefsChange) { + if (L.isEnabled(L.PROFILE)) log.debug("Loaded profile: " + profileString); - try { - profile = new ProfileStore(new JSONObject(profileString)); - } catch (JSONException e) { - log.error("Unhandled exception", e); - profile = null; - } + try { + profile = new ProfileStore(new JSONObject(profileString)); + } catch (JSONException e) { + log.error("Unhandled exception", e); + profile = null; } } else { - if (Config.logPrefsChange) { + if (L.isEnabled(L.PROFILE)) log.debug("Stored profile not found"); - // force restart of nsclient to fetch profile - Intent restartNSClient = new Intent(Intents.ACTION_RESTART); - MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); - } + // force restart of nsclient to fetch profile + Intent restartNSClient = new Intent(Intents.ACTION_RESTART); + MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfileFragment.java index 1315413e38..5e090cd9ba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfileFragment.java @@ -26,12 +26,9 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.SafeParse; public class SimpleProfileFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(SimpleProfileFragment.class); - EditText diaView; RadioButton mgdlView; RadioButton mmolView; @@ -46,92 +43,86 @@ public class SimpleProfileFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View layout = inflater.inflate(R.layout.simpleprofile_fragment, container, false); - diaView = (EditText) layout.findViewById(R.id.simpleprofile_dia); - mgdlView = (RadioButton) layout.findViewById(R.id.simpleprofile_mgdl); - mmolView = (RadioButton) layout.findViewById(R.id.simpleprofile_mmol); - icView = (EditText) layout.findViewById(R.id.simpleprofile_ic); - isfView = (EditText) layout.findViewById(R.id.simpleprofile_isf); - basalView = (EditText) layout.findViewById(R.id.simpleprofile_basalrate); - targetlowView = (EditText) layout.findViewById(R.id.simpleprofile_targetlow); - targethighView = (EditText) layout.findViewById(R.id.simpleprofile_targethigh); - profileswitchButton = (Button) layout.findViewById(R.id.simpleprofile_profileswitch); - invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile); + View layout = inflater.inflate(R.layout.simpleprofile_fragment, container, false); + diaView = (EditText) layout.findViewById(R.id.simpleprofile_dia); + mgdlView = (RadioButton) layout.findViewById(R.id.simpleprofile_mgdl); + mmolView = (RadioButton) layout.findViewById(R.id.simpleprofile_mmol); + icView = (EditText) layout.findViewById(R.id.simpleprofile_ic); + isfView = (EditText) layout.findViewById(R.id.simpleprofile_isf); + basalView = (EditText) layout.findViewById(R.id.simpleprofile_basalrate); + targetlowView = (EditText) layout.findViewById(R.id.simpleprofile_targetlow); + targethighView = (EditText) layout.findViewById(R.id.simpleprofile_targethigh); + profileswitchButton = (Button) layout.findViewById(R.id.simpleprofile_profileswitch); + invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile); - if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) { - layout.findViewById(R.id.simpleprofile_basalrate).setVisibility(View.GONE); - layout.findViewById(R.id.simpleprofile_basalrate_label).setVisibility(View.GONE); - } - - mgdlView.setChecked(SimpleProfilePlugin.getPlugin().mgdl); - mmolView.setChecked(SimpleProfilePlugin.getPlugin().mmol); - diaView.setText(SimpleProfilePlugin.getPlugin().dia.toString()); - icView.setText(SimpleProfilePlugin.getPlugin().ic.toString()); - isfView.setText(SimpleProfilePlugin.getPlugin().isf.toString()); - basalView.setText(SimpleProfilePlugin.getPlugin().basal.toString()); - targetlowView.setText(SimpleProfilePlugin.getPlugin().targetLow.toString()); - targethighView.setText(SimpleProfilePlugin.getPlugin().targetHigh.toString()); - - mgdlView.setOnClickListener(v -> { - SimpleProfilePlugin.getPlugin().mgdl = mgdlView.isChecked(); - SimpleProfilePlugin.getPlugin().mmol = !SimpleProfilePlugin.getPlugin().mgdl; - mmolView.setChecked(SimpleProfilePlugin.getPlugin().mmol); - SimpleProfilePlugin.getPlugin().storeSettings(); - }); - mmolView.setOnClickListener(v -> { - SimpleProfilePlugin.getPlugin().mmol = mmolView.isChecked(); - SimpleProfilePlugin.getPlugin().mgdl = !SimpleProfilePlugin.getPlugin().mmol; - mgdlView.setChecked(SimpleProfilePlugin.getPlugin().mgdl); - SimpleProfilePlugin.getPlugin().storeSettings(); - }); - - profileswitchButton.setOnClickListener(view -> { - NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); - final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCH; - profileswitch.executeProfileSwitch = true; - newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); - newDialog.show(getFragmentManager(), "NewNSTreatmentDialog"); - }); - - TextWatcher textWatch = new TextWatcher() { - - @Override - public void afterTextChanged(Editable s) { - } - - @Override - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, - int before, int count) { - SimpleProfilePlugin.getPlugin().dia = SafeParse.stringToDouble(diaView.getText().toString()); - SimpleProfilePlugin.getPlugin().ic = SafeParse.stringToDouble(icView.getText().toString()); - SimpleProfilePlugin.getPlugin().isf = SafeParse.stringToDouble(isfView.getText().toString()); - SimpleProfilePlugin.getPlugin().basal = SafeParse.stringToDouble(basalView.getText().toString()); - SimpleProfilePlugin.getPlugin().targetLow = SafeParse.stringToDouble(targetlowView.getText().toString()); - SimpleProfilePlugin.getPlugin().targetHigh = SafeParse.stringToDouble(targethighView.getText().toString()); - SimpleProfilePlugin.getPlugin().storeSettings(); - updateGUI(); - } - }; - - diaView.addTextChangedListener(textWatch); - icView.addTextChangedListener(textWatch); - isfView.addTextChangedListener(textWatch); - basalView.addTextChangedListener(textWatch); - targetlowView.addTextChangedListener(textWatch); - targethighView.addTextChangedListener(textWatch); - - return layout; - } catch (Exception e) { - FabricPrivacy.logException(e); + if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) { + layout.findViewById(R.id.simpleprofile_basalrate).setVisibility(View.GONE); + layout.findViewById(R.id.simpleprofile_basalrate_label).setVisibility(View.GONE); } - return null; + mgdlView.setChecked(SimpleProfilePlugin.getPlugin().mgdl); + mmolView.setChecked(SimpleProfilePlugin.getPlugin().mmol); + diaView.setText(SimpleProfilePlugin.getPlugin().dia.toString()); + icView.setText(SimpleProfilePlugin.getPlugin().ic.toString()); + isfView.setText(SimpleProfilePlugin.getPlugin().isf.toString()); + basalView.setText(SimpleProfilePlugin.getPlugin().basal.toString()); + targetlowView.setText(SimpleProfilePlugin.getPlugin().targetLow.toString()); + targethighView.setText(SimpleProfilePlugin.getPlugin().targetHigh.toString()); + + mgdlView.setOnClickListener(v -> { + SimpleProfilePlugin.getPlugin().mgdl = mgdlView.isChecked(); + SimpleProfilePlugin.getPlugin().mmol = !SimpleProfilePlugin.getPlugin().mgdl; + mmolView.setChecked(SimpleProfilePlugin.getPlugin().mmol); + SimpleProfilePlugin.getPlugin().storeSettings(); + }); + mmolView.setOnClickListener(v -> { + SimpleProfilePlugin.getPlugin().mmol = mmolView.isChecked(); + SimpleProfilePlugin.getPlugin().mgdl = !SimpleProfilePlugin.getPlugin().mmol; + mgdlView.setChecked(SimpleProfilePlugin.getPlugin().mgdl); + SimpleProfilePlugin.getPlugin().storeSettings(); + }); + + profileswitchButton.setOnClickListener(view -> { + NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); + final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCH; + profileswitch.executeProfileSwitch = true; + newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); + newDialog.show(getFragmentManager(), "NewNSTreatmentDialog"); + }); + + TextWatcher textWatch = new TextWatcher() { + + @Override + public void afterTextChanged(Editable s) { + } + + @Override + public void beforeTextChanged(CharSequence s, int start, + int count, int after) { + } + + @Override + public void onTextChanged(CharSequence s, int start, + int before, int count) { + SimpleProfilePlugin.getPlugin().dia = SafeParse.stringToDouble(diaView.getText().toString()); + SimpleProfilePlugin.getPlugin().ic = SafeParse.stringToDouble(icView.getText().toString()); + SimpleProfilePlugin.getPlugin().isf = SafeParse.stringToDouble(isfView.getText().toString()); + SimpleProfilePlugin.getPlugin().basal = SafeParse.stringToDouble(basalView.getText().toString()); + SimpleProfilePlugin.getPlugin().targetLow = SafeParse.stringToDouble(targetlowView.getText().toString()); + SimpleProfilePlugin.getPlugin().targetHigh = SafeParse.stringToDouble(targethighView.getText().toString()); + SimpleProfilePlugin.getPlugin().storeSettings(); + updateGUI(); + } + }; + + diaView.addTextChangedListener(textWatch); + icView.addTextChangedListener(textWatch); + isfView.addTextChangedListener(textWatch); + basalView.addTextChangedListener(textWatch); + targetlowView.addTextChangedListener(textWatch); + targethighView.addTextChangedListener(textWatch); + + return layout; } @Subscribe diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java index bb669289ee..09742bd3f9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileSimple/SimpleProfilePlugin.java @@ -9,7 +9,6 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -19,13 +18,14 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. */ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface { - private static Logger log = LoggerFactory.getLogger(SimpleProfilePlugin.class); + private static Logger log = LoggerFactory.getLogger(L.PROFILE); private static SimpleProfilePlugin simpleProfilePlugin; @@ -58,7 +58,7 @@ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface } public void storeSettings() { - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Storing settings"); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences.Editor editor = settings.edit(); @@ -73,13 +73,13 @@ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface editor.apply(); createConvertedProfile(); - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Storing settings: " + getRawProfile().getData().toString()); MainApp.bus().post(new EventProfileStoreChanged()); } private void loadSettings() { - if (Config.logPrefsChange) + if (L.isEnabled(L.PROFILE)) log.debug("Loading stored settings"); mgdl = SP.getBoolean("SimpleProfile" + "mgdl", true); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java index a16ffbda05..ff866702b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboPlugin.java @@ -31,8 +31,6 @@ import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; -import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.Constraint; @@ -42,7 +40,10 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; @@ -60,6 +61,7 @@ import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.PumpHistory; import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.PumpHistoryRequest; import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.Tdd; +import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.FabricPrivacy; @@ -69,7 +71,7 @@ import info.nightscout.utils.SP; * Created by mike on 05.08.2016. */ public class ComboPlugin extends PluginBase implements PumpInterface, ConstraintsInterface { - private static final Logger log = LoggerFactory.getLogger(ComboPlugin.class); + private static final Logger log = LoggerFactory.getLogger(L.PUMP); static final String COMBO_TBRS_SET = "combo_tbrs_set"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; @@ -198,7 +200,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint @Override public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); - if (allowHardwarePump || context == null){ + if (allowHardwarePump || context == null) { pluginSwitcher.invoke(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(context); @@ -207,13 +209,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint public void onClick(DialogInterface dialog, int id) { pluginSwitcher.invoke(); SP.putBoolean("allow_hardware_pump", true); - log.debug("First time HW pump allowed!"); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.cancel(); - log.debug("User does not allow switching to HW pump!"); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); } }); builder.create().show(); @@ -260,7 +264,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint @Override public void disconnect(String reason) { - log.debug("Disconnect called with reason: " + reason); + if (L.isEnabled(L.PUMP)) + log.debug("Disconnect called with reason: " + reason); ruffyScripter.disconnect(); } @@ -359,7 +364,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ @Override public synchronized void getPumpStatus() { - log.debug("getPumpStatus called"); + if (L.isEnabled(L.PUMP)) + log.debug("getPumpStatus called"); if (!pump.initialized) { initializePump(); } else { @@ -371,10 +377,12 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint private synchronized void initializePump() { long maxWait = System.currentTimeMillis() + 15 * 1000; while (!ruffyScripter.isPumpAvailable()) { - log.debug("Waiting for ruffy service to come up ..."); + if (L.isEnabled(L.PUMP)) + log.debug("Waiting for ruffy service to come up ..."); SystemClock.sleep(100); if (System.currentTimeMillis() > maxWait) { - log.debug("ruffy service unavailable, wtf"); + if (L.isEnabled(L.PUMP)) + log.debug("ruffy service unavailable, wtf"); return; } } @@ -393,7 +401,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // note that since the history is checked upon every connect, the above already updated // the DB with any changed history records if (pumpHistoryChanged) { - log.debug("Pump history has changed and was imported"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump history has changed and was imported"); pumpHistoryChanged = false; } @@ -542,7 +551,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // within the last 1-2 minutes if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01 && previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) { - log.debug("Bolu request rejected, same bolus was successfully delivered very recently"); + if (L.isEnabled(L.PUMP)) + log.debug("Bolus request rejected, same bolus was successfully delivered very recently"); return new PumpEnactResult().success(false).enacted(false) .comment(MainApp.gs(R.string.bolus_frequency_exceeded)); } @@ -562,7 +572,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint return new PumpEnactResult().success(false).enacted(false) .comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); } - log.debug("Waiting for pump clock to advance for the next unused bolus record timestamp"); + if (L.isEnabled(L.PUMP)) + log.debug("Waiting for pump clock to advance for the next unused bolus record timestamp"); SystemClock.sleep(2000); timeCheckResult = runCommand(null, 0, ruffyScripter::readPumpState); waitLoops++; @@ -573,7 +584,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("version", BuildConfig.VERSION) .putCustomAttribute("waitTimeSecs", String.valueOf(waitDuration))); - log.debug("Waited " + waitDuration + "s for pump to switch to a fresh minute before bolusing"); + if (L.isEnabled(L.PUMP)) + log.debug("Waited " + waitDuration + "s for pump to switch to a fresh minute before bolusing"); } if (cancelBolus) { @@ -735,11 +747,13 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean force) { - log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min."); + if (L.isEnabled(L.PUMP)) + log.debug("setTempBasalAbsolute called with a rate of " + absoluteRate + " for " + durationInMinutes + " min."); int unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10); if (unroundedPercentage != roundedPercentage) { - log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%"); + if (L.isEnabled(L.PUMP)) + log.debug("Rounded requested rate " + unroundedPercentage + "% -> " + roundedPercentage + "%"); } return setTempBasalPercent(roundedPercentage, durationInMinutes); @@ -757,7 +771,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) { - log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min"); + if (L.isEnabled(L.PUMP)) + log.debug("setTempBasalPercent called with " + percent + "% for " + durationInMinutes + "min"); if (pumpHistoryChanged && percent > 110) { return new PumpEnactResult().success(false).enacted(false) @@ -767,13 +782,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint int adjustedPercent = percent; if (adjustedPercent > pumpDescription.maxTempPercent) { - log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent); + if (L.isEnabled(L.PUMP)) + log.debug("Reducing requested TBR to the maximum support by the pump: " + percent + " -> " + pumpDescription.maxTempPercent); adjustedPercent = pumpDescription.maxTempPercent; } if (adjustedPercent % 10 != 0) { Long rounded = Math.round(adjustedPercent / 10d) * 10; - log.debug("Rounded requested percentage:" + adjustedPercent + " -> " + rounded); + if (L.isEnabled(L.PUMP)) + log.debug("Rounded requested percentage:" + adjustedPercent + " -> " + rounded); adjustedPercent = rounded.intValue(); } @@ -822,7 +839,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint */ @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { - log.debug("cancelTempBasal called"); + if (L.isEnabled(L.PUMP)) + log.debug("cancelTempBasal called"); final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); if (enforceNew) { CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); @@ -832,7 +850,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (!stateResult.state.tbrActive) { return new PumpEnactResult().success(true).enacted(false); } - log.debug("cancelTempBasal: hard-cancelling TBR since force requested"); + if (L.isEnabled(L.PUMP)) + log.debug("cancelTempBasal: hard-cancelling TBR since force requested"); CommandResult cancelResult = runCommand(MainApp.gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr); if (!cancelResult.success) { return new PumpEnactResult().success(false).enacted(false); @@ -853,7 +872,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // Let fake neutral temp keep run (see below) // Note that since this runs on the queue a connection is opened regardless, but this // case doesn't occur all that often, so it's not worth optimizing (1.3k SetTBR vs 4 cancelTBR). - log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); + if (L.isEnabled(L.PUMP)) + log.debug("cancelTempBasal: skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " + activeTemp.getPlannedRemainingMinutes() + " mins."); return new PumpEnactResult().success(true).enacted(true) .comment("cancelTempBasal skipping changing tbr since it already is at " + activeTemp.percentRate + "% and running for another " @@ -862,7 +882,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // Set a fake neutral temp to avoid TBR cancel alert. Decide 90% vs 110% based on // on whether the TBR we're cancelling is above or below 100%. final int percentage = (activeTemp.percentRate > 100) ? 110 : 90; - log.debug("cancelTempBasal: changing TBR to " + percentage + "% for 15 mins."); + if (L.isEnabled(L.PUMP)) + log.debug("cancelTempBasal: changing TBR to " + percentage + "% for 15 mins."); return setTempBasalPercent(percentage, 15); } } @@ -901,7 +922,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (!commandResult.success && retries > 0) { for (int retryAttempts = 1; !commandResult.success && retryAttempts <= retries; retryAttempts++) { - log.debug("Command was not successful, retries requested, doing retry #" + retryAttempts); + if (L.isEnabled(L.PUMP)) + log.debug("Command was not successful, retries requested, doing retry #" + retryAttempts); commandResult = commandExecution.execute(); } } @@ -982,7 +1004,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint long now = System.currentTimeMillis(); TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); if (aapsTbr == null || aapsTbr.percentRate != 0) { - log.debug("Creating 15m zero temp since pump is suspended"); + if (L.isEnabled(L.PUMP)) + log.debug("Creating 15m zero temp since pump is suspended"); TemporaryBasal newTempBasal = new TemporaryBasal() .date(now) .percent(0) @@ -1042,11 +1065,13 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (state.pumpTime == 0) { // time couldn't be read (e.g. a warning is displayed on the menu , hiding the time field) } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 10 * 60 * 1000) { - log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) { - log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump clock needs update, pump time: " + state.pumpTime + " (" + new Date(state.pumpTime) + ")"); Notification notification = new Notification(Notification.COMBO_PUMP_ALARM, MainApp.gs(R.string.combo_notification_check_time_date), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); } @@ -1108,7 +1133,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint long now = System.currentTimeMillis(); TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) { - log.debug("Creating temp basal from pump TBR"); + if (L.isEnabled(L.PUMP)) + log.debug("Creating temp basal from pump TBR"); FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboTbrMismatch") .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("version", BuildConfig.VERSION) @@ -1120,7 +1146,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); } else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) { - log.debug("Ending AAPS-TBR since pump has no TBR active"); + if (L.isEnabled(L.PUMP)) + log.debug("Ending AAPS-TBR since pump has no TBR active"); FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboTbrMismatch") .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("version", BuildConfig.VERSION) @@ -1133,7 +1160,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } else if (aapsTbr != null && state.tbrActive && (aapsTbr.percentRate != state.tbrPercent || Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) { - log.debug("AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR"); + if (L.isEnabled(L.PUMP)) + log.debug("AAPSs and pump-TBR differ; ending AAPS-TBR and creating new TBR based on pump TBR"); FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboTbrMismatch") .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("version", BuildConfig.VERSION) @@ -1218,7 +1246,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // no history, nothing to check or complain about if (quickInfoResult.history == null || quickInfoResult.history.bolusHistory.isEmpty()) { - log.debug("Setting 'pumpHistoryChanged' false"); + if (L.isEnabled(L.PUMP)) + log.debug("Setting 'pumpHistoryChanged' false"); pumpHistoryChanged = false; return null; } @@ -1227,13 +1256,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint List initialPumpBolusHistory = quickInfoResult.history.bolusHistory; if (recentBoluses.size() == 1 && initialPumpBolusHistory.size() >= 1 && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))) { - log.debug("Setting 'pumpHistoryChanged' false"); + if (L.isEnabled(L.PUMP)) + log.debug("Setting 'pumpHistoryChanged' false"); pumpHistoryChanged = false; return null; } else if (recentBoluses.size() == 2 && initialPumpBolusHistory.size() >= 2 && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0)) && recentBoluses.get(1).equals(quickInfoResult.history.bolusHistory.get(1))) { - log.debug("Setting 'pumpHistoryChanged' false"); + if (L.isEnabled(L.PUMP)) + log.debug("Setting 'pumpHistoryChanged' false"); pumpHistoryChanged = false; return null; } @@ -1253,7 +1284,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // for. HashSet bolusSet = new HashSet<>(historyResult.history.bolusHistory); if (bolusSet.size() != historyResult.history.bolusHistory.size()) { - log.debug("Bolus with same amount within the same minute imported. Only one will make it to the DB."); + if (L.isEnabled(L.PUMP)) + log.debug("Bolus with same amount within the same minute imported. Only one will make it to the DB."); FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboBolusToDbError") .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("version", BuildConfig.VERSION) @@ -1266,7 +1298,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history); if (pumpHistoryChanged) { - log.debug("Setting 'pumpHistoryChanged' true"); + if (L.isEnabled(L.PUMP)) + log.debug("Setting 'pumpHistoryChanged' true"); } List updatedPumpBolusHistory = historyResult.history.bolusHistory; @@ -1306,7 +1339,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint JSONObject extendedJson = new JSONObject(); extendedJson.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); - extendedJson.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName()); + extendedJson.put("ActiveProfile", ProfileFunctions.getInstance().getProfileName()); PumpState ps = pump.state; if (ps.tbrActive) { extendedJson.put("TempBasalAbsoluteRate", ps.basalRate); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/AbstractDanaRPlugin.java index 1f51979126..81f301b81b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/AbstractDanaRPlugin.java @@ -5,11 +5,11 @@ import android.support.annotation.Nullable; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Date; import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; @@ -26,6 +26,7 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -43,7 +44,7 @@ import info.nightscout.utils.SP; */ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface { - protected Logger log; + protected Logger log = LoggerFactory.getLogger(L.PUMP); protected AbstractDanaRExecutionService sExecutionService; @@ -133,7 +134,8 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement); if (profileValue == null) return true; if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { - log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); + if (L.isEnabled(L.PUMP)) + log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); return false; } } @@ -183,7 +185,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent: Correct value already set"); return result; } @@ -197,7 +199,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent: OK"); return result; } @@ -225,7 +227,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte result.absolute = pump.extendedBolusAbsoluteRate; result.isPercent = false; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount + " Asked: " + insulin); return result; } @@ -240,7 +242,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte if (!SP.getBoolean("danar_useextended", false)) result.bolusDelivered = pump.extendedBolusAmount; result.isPercent = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setExtendedBolus: OK"); return result; } @@ -263,7 +265,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte if (!pump.isExtendedInProgress) { result.success = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("cancelExtendedBolus: OK"); return result; } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java index 7288602d65..f261bc470d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java @@ -25,12 +25,13 @@ import butterknife.ButterKnife; import butterknife.OnClick; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.TDDStatsActivity; +import info.nightscout.androidaps.activities.TDDStatsActivity; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.Dialogs.ProfileViewDialog; @@ -42,11 +43,10 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.events.EventQueueChanged; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; -import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.SetWarnColor; public class DanaRFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(DanaRFragment.class); + private static Logger log = LoggerFactory.getLogger(L.PUMP); private Handler loopHandler = new Handler(); private Runnable refreshLoop = new Runnable() { @@ -113,18 +113,12 @@ public class DanaRFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.danar_fragment, container, false); - unbinder = ButterKnife.bind(this, view); + View view = inflater.inflate(R.layout.danar_fragment, container, false); + unbinder = ButterKnife.bind(this, view); - pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); + pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } - - return null; + return view; } @OnClick(R.id.danar_history) @@ -145,11 +139,14 @@ public class DanaRFragment extends SubscriberFragment { } @OnClick(R.id.danar_user_options) - void onUserOptionsClick() { startActivity(new Intent(getContext(), DanaRUserOptionsActivity.class)); } + void onUserOptionsClick() { + startActivity(new Intent(getContext(), DanaRUserOptionsActivity.class)); + } @OnClick(R.id.danar_btconnection) void onBtConnectionClick() { - log.debug("Clicked connect to pump"); + if (L.isEnabled(L.PUMP)) + log.debug("Clicked connect to pump"); DanaRPump.getInstance().lastConnection = 0; ConfigBuilderPlugin.getCommandQueue().readStatus("Clicked connect to pump", null); } @@ -162,10 +159,11 @@ public class DanaRFragment extends SubscriberFragment { activity.runOnUiThread( new Runnable() { @Override - public void run() { - synchronized(DanaRFragment.this){ + public void run() { + synchronized (DanaRFragment.this) { - if(btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null ) return; + if (btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null) + return; if (c.sStatus == EventPumpStatusChanged.CONNECTING) btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); @@ -216,7 +214,7 @@ public class DanaRFragment extends SubscriberFragment { @SuppressLint("SetTextI18n") @Override public void run() { - synchronized(DanaRFragment.this) { + synchronized (DanaRFragment.this) { if (!isBound()) return; DanaRPump pump = DanaRPump.getInstance(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java index 144107779d..68ea3fe851 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPlugin.java @@ -11,9 +11,6 @@ import android.support.v7.app.AlertDialog; import com.squareup.otto.Subscribe; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -21,6 +18,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.Treatments.Treatment; @@ -49,7 +47,6 @@ public class DanaRPlugin extends AbstractDanaRPlugin { public DanaRPlugin() { super(); - log = LoggerFactory.getLogger(DanaRPlugin.class); useExtendedBoluses = SP.getBoolean("danar_useextended", false); pumpDescription.isBolusCapable = true; @@ -85,7 +82,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { @Override public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); - if (allowHardwarePump || context == null){ + if (allowHardwarePump || context == null) { pluginSwitcher.invoke(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(context); @@ -94,13 +91,15 @@ public class DanaRPlugin extends AbstractDanaRPlugin { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.invoke(); SP.putBoolean("allow_hardware_pump", true); - log.debug("First time HW pump allowed!"); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.cancel(); - log.debug("User does not allow switching to HW pump!"); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); } }); builder.create().show(); @@ -127,12 +126,14 @@ public class DanaRPlugin extends AbstractDanaRPlugin { private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { - log.debug("Service is disconnected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is disconnected"); sExecutionService = null; } public void onServiceConnected(ComponentName name, IBinder service) { - log.debug("Service is connected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is connected"); DanaRExecutionService.LocalBinder mLocalBinder = (DanaRExecutionService.LocalBinder) service; sExecutionService = mLocalBinder.getServiceInstance(); } @@ -195,7 +196,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStartWithSpeed.errorCode); else result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); detailedBolusInfo.insulin = t.insulin; detailedBolusInfo.date = System.currentTimeMillis(); @@ -237,13 +238,13 @@ public class DanaRPlugin extends AbstractDanaRPlugin { if (doTempOff) { // If extended in progress if (activeExtended != null && useExtendedBoluses) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping extended bolus (doTempOff)"); return cancelExtendedBolus(); } // If temp in progress if (activeTemp != null) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)"); return cancelRealTempBasal(); } @@ -252,7 +253,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { result.percent = 100; result.isPercent = true; result.isTempCancel = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: doTempOff OK"); return result; } @@ -264,12 +265,12 @@ public class DanaRPlugin extends AbstractDanaRPlugin { if (percentRate > getPumpDescription().maxTempPercent) { percentRate = getPumpDescription().maxTempPercent; } - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Calculated percent rate: " + percentRate); // If extended in progress if (activeExtended != null && useExtendedBoluses) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)"); result = cancelExtendedBolus(); if (!result.success) { @@ -280,7 +281,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { // Check if some temp is already in progress if (activeTemp != null) { // Correct basal already set ? - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: currently running: " + activeTemp.toString()); if (activeTemp.percentRate == percentRate) { if (enforceNew) { @@ -292,21 +293,21 @@ public class DanaRPlugin extends AbstractDanaRPlugin { result.duration = activeTemp.getPlannedRemainingMinutes(); result.isPercent = true; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); return result; } } } // Convert duration from minutes to hours - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); return setTempBasalPercent(percentRate, durationInMinutes, profile, false); } if (doExtendedTemp) { // Check if some temp is already in progress if (activeTemp != null) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping temp basal (doExtendedTemp)"); result = cancelRealTempBasal(); // Check for proper result @@ -325,7 +326,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours // What is current rate of extended bolusing in u/h? - if (Config.logPumpActions) { + if (L.isEnabled(L.PUMP)) { log.debug("setTempBasalAbsolute: Extended bolus in progress: " + (activeExtended != null) + " rate: " + pump.extendedBolusAbsoluteRate + "U/h duration remaining: " + pump.extendedBolusRemainingMinutes + "min"); log.debug("setTempBasalAbsolute: Rate to set: " + extendedRateToSet + "U/h"); } @@ -339,21 +340,21 @@ public class DanaRPlugin extends AbstractDanaRPlugin { result.duration = pump.extendedBolusRemainingMinutes; result.isPercent = false; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Correct extended already set"); return result; } // Now set new extended, no need to to stop previous (if running) because it's replaced Double extendedAmount = extendedRateToSet / 2 * durationInHalfHours; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Setting extended: " + extendedAmount + "U halfhours: " + durationInHalfHours); result = setExtendedBolus(extendedAmount, durationInMinutes); if (!result.success) { log.error("setTempBasalAbsolute: Failed to set extended bolus"); return result; } - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Extended bolus set ok"); result.absolute = result.absolute + getBaseBasalRate(); return result; @@ -392,7 +393,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { result.success = true; result.isTempCancel = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("cancelRealTempBasal: OK"); return result; } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java index d9bc947b84..b5c1e6030e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRPump.java @@ -9,18 +9,18 @@ import org.slf4j.LoggerFactory; import java.text.DecimalFormat; import java.util.Date; -import info.nightscout.androidaps.Config; 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.logging.L; import info.nightscout.utils.SP; /** * Created by mike on 04.07.2016. */ public class DanaRPump { - private static Logger log = LoggerFactory.getLogger(DanaRPump.class); + private Logger log = LoggerFactory.getLogger(L.PUMP); private static DanaRPump instance = null; @@ -236,13 +236,13 @@ public class DanaRPump { return PROFILE_PREFIX + (activeProfile + 1); } - public static double[] buildDanaRProfileRecord(Profile nsProfile) { + public double[] buildDanaRProfileRecord(Profile nsProfile) { double[] record = new double[24]; for (Integer hour = 0; hour < 24; hour++) { //Some values get truncated to the next lower one. // -> round them to two decimals and make sure we are a small delta larger (that will get truncated) double value = Math.round(100d * nsProfile.getBasalTimeFromMidnight((Integer) (hour * 60 * 60)))/100d + 0.00001; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMP)) log.debug("NS basal value for " + hour + ":00 is " + value); record[hour] = value; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java index d8157281bd..24728f2cf6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java @@ -33,8 +33,6 @@ import info.nightscout.utils.DecimalFormatter; * Created by mike on 10.07.2016. */ public class ProfileViewDialog extends DialogFragment { - private static Logger log = LoggerFactory.getLogger(ProfileViewDialog.class); - private TextView noProfile; private TextView units; private TextView dia; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/SerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/SerialIOThread.java index 2f377a566a..a319353d63 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/SerialIOThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/SerialIOThread.java @@ -10,7 +10,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageHashTable; import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread; @@ -20,7 +20,7 @@ import info.nightscout.utils.CRC; * Created by mike on 17.07.2016. */ public class SerialIOThread extends AbstractSerialIOThread { - private static Logger log = LoggerFactory.getLogger(SerialIOThread.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPBTCOMM); private InputStream mInputStream = null; private OutputStream mOutputStream = null; @@ -71,7 +71,7 @@ public class SerialIOThread extends AbstractSerialIOThread { message = MessageHashTable.findMessage(command); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff)); // process the message content @@ -83,7 +83,7 @@ public class SerialIOThread extends AbstractSerialIOThread { } } } catch (Exception e) { - if (Config.logDanaSerialEngine && e.getMessage().indexOf("bt socket closed") < 0) + if (e.getMessage().indexOf("bt socket closed") < 0) log.error("Thread exception: ", e); mKeepRunning = false; } @@ -147,7 +147,7 @@ public class SerialIOThread extends AbstractSerialIOThread { processedMessage = message; byte[] messageBytes = message.getRawMessageBytes(); - if (Config.logDanaSerialEngine) + if (L.isEnabled(L.PUMPBTCOMM)) log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes)); try { @@ -169,7 +169,8 @@ public class SerialIOThread extends AbstractSerialIOThread { log.warn("Reply not received " + message.getMessageName()); if (message.getCommand() == 0xF0F1) { DanaRPump.getInstance().isNewPump = false; - log.debug("Old firmware detected"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Old firmware detected"); } } } @@ -180,24 +181,29 @@ public class SerialIOThread extends AbstractSerialIOThread { try { mInputStream.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { mOutputStream.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { mRfCommSocket.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { System.runFinalization(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } - if (Config.logDanaSerialEngine) log.debug("Disconnected: " + reason); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Disconnected: " + reason); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRHistoryActivity.java index 97c5569b4b..6398c41a09 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRHistoryActivity.java @@ -31,7 +31,9 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; @@ -42,12 +44,9 @@ import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.ToastUtils; public class DanaRHistoryActivity extends Activity { - private static Logger log = LoggerFactory.getLogger(DanaRHistoryActivity.class); - - private boolean mBounded; + private static Logger log = LoggerFactory.getLogger(L.PUMP); private Handler mHandler; - private static HandlerThread mHandlerThread; static Profile profile = null; @@ -65,7 +64,7 @@ public class DanaRHistoryActivity extends Activity { public byte type; String name; - public TypeList(byte type, String name) { + TypeList(byte type, String name) { this.type = type; this.name = name; } @@ -78,7 +77,7 @@ public class DanaRHistoryActivity extends Activity { public DanaRHistoryActivity() { super(); - mHandlerThread = new HandlerThread(DanaRHistoryActivity.class.getSimpleName()); + HandlerThread mHandlerThread = new HandlerThread(DanaRHistoryActivity.class.getSimpleName()); mHandlerThread.start(); this.mHandler = new Handler(mHandlerThread.getLooper()); } @@ -116,8 +115,8 @@ public class DanaRHistoryActivity extends Activity { statusView.setVisibility(View.GONE); - boolean isKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class) != null && MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginType.PUMP); - boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class) != null && MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginType.PUMP); + boolean isKorean = DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PUMP); + boolean isRS = DanaRSPlugin.getPlugin().isEnabled(PluginType.PUMP); // Types @@ -141,10 +140,30 @@ public class DanaRHistoryActivity extends Activity { R.layout.spinner_centered, typeList); historyTypeSpinner.setAdapter(spinnerAdapter); - reloadButton.setOnClickListener(new View.OnClickListener() { + reloadButton.setOnClickListener(v -> { + final TypeList selected = (TypeList) historyTypeSpinner.getSelectedItem(); + runOnUiThread(() -> { + reloadButton.setVisibility(View.GONE); + syncButton.setVisibility(View.GONE); + statusView.setVisibility(View.VISIBLE); + }); + clearCardView(); + ConfigBuilderPlugin.getCommandQueue().loadHistory(selected.type, new Callback() { + @Override + public void run() { + loadDataFromDB(selected.type); + runOnUiThread(() -> { + reloadButton.setVisibility(View.VISIBLE); + syncButton.setVisibility(View.VISIBLE); + statusView.setVisibility(View.GONE); + }); + } + }); + }); + + syncButton.setOnClickListener(v -> mHandler.post(new Runnable() { @Override - public void onClick(View v) { - final TypeList selected = (TypeList) historyTypeSpinner.getSelectedItem(); + public void run() { runOnUiThread(new Runnable() { @Override public void run() { @@ -153,52 +172,18 @@ public class DanaRHistoryActivity extends Activity { statusView.setVisibility(View.VISIBLE); } }); - clearCardView(); - ConfigBuilderPlugin.getCommandQueue().loadHistory(selected.type, new Callback() { + DanaRNSHistorySync sync = new DanaRNSHistorySync(historyList); + sync.sync(DanaRNSHistorySync.SYNC_ALL); + runOnUiThread(new Runnable() { @Override public void run() { - loadDataFromDB(selected.type); - runOnUiThread(new Runnable() { - @Override - public void run() { - reloadButton.setVisibility(View.VISIBLE); - syncButton.setVisibility(View.VISIBLE); - statusView.setVisibility(View.GONE); - } - }); + reloadButton.setVisibility(View.VISIBLE); + syncButton.setVisibility(View.VISIBLE); + statusView.setVisibility(View.GONE); } }); } - }); - - syncButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - mHandler.post(new Runnable() { - @Override - public void run() { - runOnUiThread(new Runnable() { - @Override - public void run() { - reloadButton.setVisibility(View.GONE); - syncButton.setVisibility(View.GONE); - statusView.setVisibility(View.VISIBLE); - } - }); - DanaRNSHistorySync sync = new DanaRNSHistorySync(historyList); - sync.sync(DanaRNSHistorySync.SYNC_ALL); - runOnUiThread(new Runnable() { - @Override - public void run() { - reloadButton.setVisibility(View.VISIBLE); - syncButton.setVisibility(View.VISIBLE); - statusView.setVisibility(View.GONE); - } - }); - } - }); - } - }); + })); historyTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override @@ -213,7 +198,7 @@ public class DanaRHistoryActivity extends Activity { clearCardView(); } }); - profile = MainApp.getConfigBuilder().getProfile(); + profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.noprofile)); finish(); @@ -324,7 +309,7 @@ public class DanaRHistoryActivity extends Activity { super.onAttachedToRecyclerView(recyclerView); } - public static class HistoryViewHolder extends RecyclerView.ViewHolder { + static class HistoryViewHolder extends RecyclerView.ViewHolder { CardView cv; TextView time; TextView value; @@ -355,45 +340,26 @@ public class DanaRHistoryActivity extends Activity { private void loadDataFromDB(byte type) { historyList = MainApp.getDbHelper().getDanaRHistoryRecordsByType(type); - runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new RecyclerViewAdapter(historyList), false); - } - }); + runOnUiThread(() -> recyclerView.swapAdapter(new RecyclerViewAdapter(historyList), false)); } private void clearCardView() { historyList = new ArrayList<>(); - runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new RecyclerViewAdapter(historyList), false); - } - }); + runOnUiThread(() -> recyclerView.swapAdapter(new RecyclerViewAdapter(historyList), false)); } @Subscribe public void onStatusEvent(final EventDanaRSyncStatus s) { - log.debug("EventDanaRSyncStatus: " + s.message); + if (L.isEnabled(L.PUMP)) + log.debug("EventDanaRSyncStatus: " + s.message); runOnUiThread( - new Runnable() { - @Override - public void run() { - statusView.setText(s.message); - } - }); + () -> statusView.setText(s.message)); } @Subscribe public void onStatusEvent(final EventPumpStatusChanged s) { runOnUiThread( - new Runnable() { - @Override - public void run() { - statusView.setText(s.textStatus()); - } - } + () -> statusView.setText(s.textStatus()) ); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRNSHistorySync.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRNSHistorySync.java index d505443c1d..eab9e8bc6e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRNSHistorySync.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRNSHistorySync.java @@ -10,22 +10,22 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.DanaRHistoryRecord; -import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; -import info.nightscout.utils.ToastUtils; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; /** * Created by mike on 20.07.2016. */ public class DanaRNSHistorySync { - private static Logger log = LoggerFactory.getLogger(DanaRNSHistorySync.class); + private static Logger log = LoggerFactory.getLogger(L.PUMP); private List historyRecords; public final static int SYNC_BOLUS = 0b00000001; @@ -50,7 +50,8 @@ public class DanaRNSHistorySync { long records = historyRecords.size(); long processing = 0; long uploaded = 0; - log.debug("Database contains " + records + " records"); + if (L.isEnabled(L.PUMP)) + log.debug("Database contains " + records + " records"); EventDanaRSyncStatus ev = new EventDanaRSyncStatus(); for (DanaRHistoryRecord record : historyRecords) { processing++; @@ -63,7 +64,8 @@ public class DanaRNSHistorySync { if ((what & SYNC_BOLUS) == 0) break; switch (record.bolusType) { case "S": - log.debug("Syncing standard bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing standard bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", "Meal Bolus"); nsrec.put("insulin", record.recordValue); @@ -75,7 +77,8 @@ public class DanaRNSHistorySync { break; case "E": if (record.recordDuration > 0) { - log.debug("Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", CareportalEvent.COMBOBOLUS); nsrec.put("insulin", 0); @@ -91,11 +94,13 @@ public class DanaRNSHistorySync { uploaded++; ev.message += MainApp.gs(R.string.danar_ebolus); } else { - log.debug("NOT Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate) + " zero duration"); + if (L.isEnabled(L.PUMP)) + log.debug("NOT Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate) + " zero duration"); } break; case "DS": - log.debug("Syncing dual(S) bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing dual(S) bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", CareportalEvent.COMBOBOLUS); nsrec.put("insulin", record.recordValue); @@ -108,7 +113,8 @@ public class DanaRNSHistorySync { ev.message += MainApp.gs(R.string.danar_dsbolus); break; case "DE": - log.debug("Syncing dual(E) bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing dual(E) bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", CareportalEvent.COMBOBOLUS); nsrec.put("duration", record.recordDuration); @@ -124,13 +130,14 @@ public class DanaRNSHistorySync { ev.message += MainApp.gs(R.string.danar_debolus); break; default: - log.debug("Unknown bolus record"); + log.error("Unknown bolus record"); break; } break; case RecordTypes.RECORD_TYPE_ERROR: if ((what & SYNC_ERROR) == 0) break; - log.debug("Syncing error record " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing error record " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", "Note"); nsrec.put("notes", "Error"); @@ -142,7 +149,8 @@ public class DanaRNSHistorySync { break; case RecordTypes.RECORD_TYPE_REFILL: if ((what & SYNC_REFILL) == 0) break; - log.debug("Syncing refill record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing refill record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", "Insulin Change"); nsrec.put("notes", "Refill " + record.recordValue + "U"); @@ -154,7 +162,8 @@ public class DanaRNSHistorySync { break; case RecordTypes.RECORD_TYPE_BASALHOUR: if ((what & SYNC_BASALHOURS) == 0) break; - log.debug("Syncing basal hour record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing basal hour record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", CareportalEvent.TEMPBASAL); nsrec.put("absolute", record.recordValue); @@ -170,10 +179,11 @@ public class DanaRNSHistorySync { break; case RecordTypes.RECORD_TYPE_GLUCOSE: if ((what & SYNC_GLUCOSE) == 0) break; - log.debug("Syncing glucose record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing glucose record " + record.recordValue + " " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", "BG Check"); - nsrec.put("glucose", Profile.fromMgdlToUnits(record.recordValue, MainApp.getConfigBuilder().getProfileUnits())); + nsrec.put("glucose", Profile.fromMgdlToUnits(record.recordValue, ProfileFunctions.getInstance().getProfileUnits())); nsrec.put("glucoseType", "Finger"); nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); @@ -183,7 +193,8 @@ public class DanaRNSHistorySync { break; case RecordTypes.RECORD_TYPE_CARBO: if ((what & SYNC_CARBO) == 0) break; - log.debug("Syncing carbo record " + record.recordValue + "g " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing carbo record " + record.recordValue + "g " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", "Meal Bolus"); nsrec.put("carbs", record.recordValue); @@ -195,7 +206,8 @@ public class DanaRNSHistorySync { break; case RecordTypes.RECORD_TYPE_ALARM: if ((what & SYNC_ALARM) == 0) break; - log.debug("Syncing alarm record " + record.recordAlarm + " " + DateUtil.toISOString(record.recordDate)); + if (L.isEnabled(L.PUMP)) + log.debug("Syncing alarm record " + record.recordAlarm + " " + DateUtil.toISOString(record.recordDate)); nsrec.put(DANARSIGNATURE, record.bytes); nsrec.put("eventType", "Note"); nsrec.put("notes", "Alarm: " + record.recordAlarm); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java index b4930a2a1a..336c526d82 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/activities/DanaRUserOptionsActivity.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; @@ -30,7 +31,7 @@ import info.nightscout.utils.NumberPicker; */ public class DanaRUserOptionsActivity extends Activity { - private static Logger log = LoggerFactory.getLogger(DanaRUserOptionsActivity.class); + private static Logger log = LoggerFactory.getLogger(L.PUMP); Switch timeFormat; Switch buttonScroll; @@ -45,6 +46,10 @@ public class DanaRUserOptionsActivity extends Activity { NumberPicker shutdown; NumberPicker lowReservoir; Button saveToPumpButton; + // This is for Dana pumps only + boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class) != null && MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginType.PUMP); + boolean isDanaR = MainApp.getSpecificPlugin(DanaRPlugin.class) != null && MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PUMP); + boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); @Override protected void onResume() { @@ -81,14 +86,15 @@ public class DanaRUserOptionsActivity extends Activity { DanaRPump pump = DanaRPump.getInstance(); //used for debugging - log.debug("UserOptionsLoaded:" + (System.currentTimeMillis() - pump.lastConnection) / 1000 + " s ago" - + "\ntimeDisplayType:" + pump.timeDisplayType - + "\nbuttonScroll:" + pump.buttonScrollOnOff - + "\ntimeDisplayType:" + pump.timeDisplayType - + "\nlcdOnTimeSec:" + pump.lcdOnTimeSec - + "\nbacklight:" + pump.backlightOnTimeSec - + "\npumpUnits:" + pump.units - + "\nlowReservoir:" + pump.lowReservoirRate); + if (L.isEnabled(L.PUMP)) + log.debug("UserOptionsLoaded:" + (System.currentTimeMillis() - pump.lastConnection) / 1000 + " s ago" + + "\ntimeDisplayType:" + pump.timeDisplayType + + "\nbuttonScroll:" + pump.buttonScrollOnOff + + "\ntimeDisplayType:" + pump.timeDisplayType + + "\nlcdOnTimeSec:" + pump.lcdOnTimeSec + + "\nbacklight:" + pump.backlightOnTimeSec + + "\npumpUnits:" + pump.units + + "\nlowReservoir:" + pump.lowReservoirRate); screenTimeout.setParams((double) pump.lcdOnTimeSec, 5d, 240d, 5d, new DecimalFormat("1"), false); backlightTimeout.setParams((double) pump.backlightOnTimeSec, 1d, 60d, 1d, new DecimalFormat("1"), false); @@ -118,15 +124,15 @@ public class DanaRUserOptionsActivity extends Activity { break; } if (pump.lastSettingsRead == 0) - log.debug("No settings loaded from pump!"); + log.error("No settings loaded from pump!"); else setData(); } public void setData() { DanaRPump pump = DanaRPump.getInstance(); - - timeFormat.setChecked(pump.timeDisplayType != 0); + // in DanaRS timeDisplay values are reversed + timeFormat.setChecked((!isRS && pump.timeDisplayType != 0) || (isRS && pump.timeDisplayType == 0)); buttonScroll.setChecked(pump.buttonScrollOnOff != 0); beep.setChecked(pump.beepAndAlarm > 4); screenTimeout.setValue((double) pump.lcdOnTimeSec); @@ -142,19 +148,22 @@ public class DanaRUserOptionsActivity extends Activity { } public void onSaveClick() { - boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class) != null && MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginType.PUMP); - boolean isDanaR = MainApp.getSpecificPlugin(DanaRPlugin.class) != null && MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PUMP); - boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); if (!isRS && !isDanaR && !isDanaRv2) { //exit if pump is not DanaRS, Dana!, or DanaR with upgraded firmware return; } DanaRPump pump = DanaRPump.getInstance(); - if (timeFormat.isChecked()) pump.timeDisplayType = 1; else pump.timeDisplayType = 0; + // displayTime on RS is reversed + if (isRS) { + if (timeFormat.isChecked()) + pump.timeDisplayType = 0; + else + pump.timeDisplayType = 1; + } if (buttonScroll.isChecked()) pump.buttonScrollOnOff = 1; else @@ -168,13 +177,13 @@ public class DanaRUserOptionsActivity extends Activity { // step is 5 seconds - int screenTimeoutValue = !screenTimeout.getText().isEmpty() ? (Integer.parseInt(screenTimeout.getText().toString()) / 5) * 5: 5; + int screenTimeoutValue = !screenTimeout.getText().isEmpty() ? (Integer.parseInt(screenTimeout.getText().toString()) / 5) * 5 : 5; if (screenTimeoutValue > 4 && screenTimeoutValue < 241) { pump.lcdOnTimeSec = screenTimeoutValue; } else { pump.lcdOnTimeSec = 5; } - int backlightTimeoutValue = !backlightTimeout.getText().isEmpty() ? Integer.parseInt(backlightTimeout.getText().toString()): 1; + int backlightTimeoutValue = !backlightTimeout.getText().isEmpty() ? Integer.parseInt(backlightTimeout.getText().toString()) : 1; if (backlightTimeoutValue > 0 && backlightTimeoutValue < 61) { pump.backlightOnTimeSec = backlightTimeoutValue; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageBase.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageBase.java index 2e6c02458e..b48940807d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageBase.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageBase.java @@ -12,7 +12,7 @@ import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.CRC; /* @@ -22,7 +22,7 @@ import info.nightscout.utils.CRC; */ public class MessageBase { - private static Logger log = LoggerFactory.getLogger(MessageBase.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); protected byte[] buffer = new byte[512]; private int position = 6; @@ -95,7 +95,7 @@ public class MessageBase { } public void handleMessage(byte[] bytes) { - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (bytes.length > 6) { int command = (bytes[5] & 0xFF) | ((bytes[4] << 8) & 0xFF00); log.debug("UNPROCESSED MSG: " + getMessageName() + " Command: " + String.format("%04X", command) + " Data: " + toHexString(bytes)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java index 4b90b8f02d..e7f1adca07 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java @@ -9,8 +9,6 @@ import java.util.HashMap; * Created by mike on 28.05.2016. */ public class MessageHashTable { - private static Logger log = LoggerFactory.getLogger(MessageHashTable.class); - public static HashMap messages = null; static { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageOriginalNames.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageOriginalNames.java index 3712945094..a285ce5120 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageOriginalNames.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageOriginalNames.java @@ -5,13 +5,15 @@ import org.slf4j.LoggerFactory; import java.util.HashMap; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 28.05.2016. */ public class MessageOriginalNames { - private static Logger log = LoggerFactory.getLogger(MessageOriginalNames.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public static HashMap messageNames; + private static HashMap messageNames; static { messageNames = new HashMap<>(); @@ -162,7 +164,7 @@ public class MessageOriginalNames { if (messageNames.containsKey(command)) return messageNames.get(command); else { - log.debug("Unknown command: " + String.format("%04X", command)); + log.error("Unknown command: " + String.format("%04X", command)); return "UNKNOWN_COMMAND"; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java index cb01a7d901..873824f966 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusProgress.java @@ -3,14 +3,14 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.Treatments.Treatment; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; +import info.nightscout.androidaps.plugins.Treatments.Treatment; public class MsgBolusProgress extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgBolusProgress.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Treatment t; private static double amount; @@ -27,6 +27,8 @@ public class MsgBolusProgress extends MessageBase { this.amount = amount; this.t = t; lastReceive = System.currentTimeMillis(); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: amount: " + amount + " treatment: " + t.toString()); } @Override @@ -40,7 +42,7 @@ public class MsgBolusProgress extends MessageBase { bolusingEvent.t = t; bolusingEvent.percent = Math.min((int) (done / amount * 100), 100); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Bolus remaining: " + progress + " delivered: " + done); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStart.java index 7586edf825..06200d1f0c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStart.java @@ -3,13 +3,12 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.utils.HardLimits; +import info.nightscout.androidaps.logging.L; public class MsgBolusStart extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgBolusStart.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public static int errorCode; @@ -25,7 +24,7 @@ public class MsgBolusStart extends MessageBase { AddParamInt((int) (amount * 100)); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Bolus start : " + amount); } @@ -34,9 +33,10 @@ public class MsgBolusStart extends MessageBase { errorCode = intFromBuff(bytes, 0, 1); if (errorCode != 2) { failed = true; - log.debug("Messsage response: " + errorCode + " FAILED!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Messsage response: " + errorCode + " FAILED!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Messsage response: " + errorCode + " OK"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStartWithSpeed.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStartWithSpeed.java index dd4251a350..a3160ff887 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStartWithSpeed.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStartWithSpeed.java @@ -3,13 +3,12 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.utils.HardLimits; +import info.nightscout.androidaps.logging.L; public class MsgBolusStartWithSpeed extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgBolusStartWithSpeed.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public static int errorCode; @@ -26,7 +25,7 @@ public class MsgBolusStartWithSpeed extends MessageBase { AddParamInt((int) (amount * 100)); AddParamByte((byte) speed); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Bolus start : " + amount + " speed: " + speed); } @@ -35,9 +34,10 @@ public class MsgBolusStartWithSpeed extends MessageBase { errorCode = intFromBuff(bytes, 0, 1); if (errorCode != 2) { failed = true; - log.debug("Messsage response: " + errorCode + " FAILED!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Messsage response: " + errorCode + " FAILED!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Messsage response: " + errorCode + " OK"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java index 5c677b813e..fe5d47c131 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgBolusStop.java @@ -5,11 +5,12 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.Treatments.Treatment; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; +import info.nightscout.androidaps.plugins.Treatments.Treatment; public class MsgBolusStop extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgBolusStop.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Treatment t; private static Double amount; @@ -26,10 +27,14 @@ public class MsgBolusStop extends MessageBase { this.t = t; this.amount = amount; forced = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Bolus stop: amount: " + amount + " treatment: " + t.toString()); } @Override public void handleMessage(byte[] bytes) { + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Messsage received"); EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); stopped = true; if (!forced) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgCheckValue.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgCheckValue.java index 3f0c306940..e04d9243e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgCheckValue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgCheckValue.java @@ -3,21 +3,21 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import info.nightscout.utils.ToastUtils; /** * Created by mike on 30.06.2016. */ public class MsgCheckValue extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgCheckValue.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgCheckValue() { SetCommand(0xF0F1); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -25,7 +25,8 @@ public class MsgCheckValue extends MessageBase { DanaRPump pump = DanaRPump.getInstance(); pump.isNewPump = true; - log.debug("New firmware confirmed"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New firmware confirmed"); pump.model = intFromBuff(bytes, 0, 1); pump.protocol = intFromBuff(bytes, 1, 1); @@ -35,7 +36,7 @@ public class MsgCheckValue extends MessageBase { log.debug("Wrong model selected"); } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Model: " + String.format("%02X ", pump.model)); log.debug("Protocol: " + String.format("%02X ", pump.protocol)); log.debug("Product Code: " + String.format("%02X ", pump.productCode)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java index e42327c3b0..b5d4267203 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgError.java @@ -3,17 +3,19 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; public class MsgError extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgError.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgError() { SetCommand(0x0601); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -47,7 +49,7 @@ public class MsgError extends MessageBase { bolusingEvent.status = errorString; MainApp.bus().post(bolusingEvent); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Error detected: " + errorString); NSUpload.uploadError(errorString); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAlarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAlarm.java index 24ea6d0f37..7adb335e93 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAlarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAlarm.java @@ -3,13 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryAlarm extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryAlarm.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgHistoryAlarm() { SetCommand(0x3105); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAll.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAll.java index 4e4bc759f5..a0e1075056 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAll.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAll.java @@ -7,14 +7,17 @@ import java.util.Date; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DanaRHistoryRecord; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.utils.DateUtil; public class MsgHistoryAll extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgHistoryAll.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgHistoryAll() { SetCommand(0x41F2); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAllDone.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAllDone.java index 6ce3325715..e78771f99d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAllDone.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryAllDone.java @@ -3,21 +3,23 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgHistoryAllDone extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgHistoryAllDone.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public static boolean received = false; public MsgHistoryAllDone() { SetCommand(0x41F1); received = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] bytes) { received = true; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("History all done received"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBasalHour.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBasalHour.java index 3fd97135f0..f56e2af273 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBasalHour.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBasalHour.java @@ -3,13 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryBasalHour extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryBasalHour.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgHistoryBasalHour() { SetCommand(0x310A); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBolus.java index b213ba52fd..d675ddc488 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryBolus.java @@ -3,13 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryBolus extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryBolus.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgHistoryBolus() { SetCommand(0x3101); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryCarbo.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryCarbo.java index 115dc73e02..6755800bba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryCarbo.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryCarbo.java @@ -3,13 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryCarbo extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryCarbo.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgHistoryCarbo() { SetCommand(0x3107); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDailyInsulin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDailyInsulin.java index 77933c40da..68d46f0d20 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDailyInsulin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDailyInsulin.java @@ -3,13 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryDailyInsulin extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryDailyInsulin.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgHistoryDailyInsulin() { SetCommand(0x3102); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDone.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDone.java index 04d3cb3faf..63e51e24ba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDone.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryDone.java @@ -3,24 +3,26 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 20.07.2016. */ public class MsgHistoryDone extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgHistoryDone.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public static boolean received = false; public MsgHistoryDone() { SetCommand(0x31F1); received = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] bytes) { received = true; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("History done received"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryError.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryError.java index 3358a88fea..8d6d0615d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryError.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryError.java @@ -3,13 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryError extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryError.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgHistoryError() { SetCommand(0x3106); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryGlucose.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryGlucose.java index f07b91e9d8..10fd68e3ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryGlucose.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryGlucose.java @@ -3,13 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryGlucose extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryGlucose.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgHistoryGlucose() { SetCommand(0x3104); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNew.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNew.java index 5de685f65b..01f7197434 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNew.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNew.java @@ -3,13 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryNew extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryNew.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgHistoryNew() { SetCommand(0x42F2); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNewDone.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNewDone.java index 2cde92bf9a..fb9118e629 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNewDone.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryNewDone.java @@ -3,24 +3,26 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 20.07.2016. */ public class MsgHistoryNewDone extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgHistoryNewDone.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public static boolean received = false; public MsgHistoryNewDone() { SetCommand(0x42F1); received = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] bytes) { received = true; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("History new done received"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryRefill.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryRefill.java index daaed79023..238a606cfb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryRefill.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistoryRefill.java @@ -3,13 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistoryRefill extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistoryRefill.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgHistoryRefill() { SetCommand(0x3108); - } + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistorySuspend.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistorySuspend.java index db807a31b5..7182722f97 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistorySuspend.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgHistorySuspend.java @@ -3,13 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import info.nightscout.androidaps.logging.L; + /** * Created by mike on 20.07.2016. */ public class MsgHistorySuspend extends MsgHistoryAll { - private static Logger log = LoggerFactory.getLogger(MsgHistorySuspend.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgHistorySuspend() { SetCommand(0x3109); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // Handle message taken from MsgHistoryAll } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBasic.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBasic.java index e7f6032c00..61150079cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBasic.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBasic.java @@ -3,14 +3,16 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class MsgInitConnStatusBasic extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBasic.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusBasic() { SetCommand(0x0303); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -39,14 +41,17 @@ public class MsgInitConnStatusBasic extends MessageBase { boolean deliveryStepBolus = (bolusConfig & DanaRPump.DELIVERY_STEP_BOLUS) != 0; boolean deliveryBasal = (bolusConfig & DanaRPump.DELIVERY_BASAL) != 0; boolean deliveryExtBolus = (bolusConfig & DanaRPump.DELIVERY_EXT_BOLUS) != 0; - log.debug("Delivery prime: " + deliveryPrime); - log.debug("Delivery step bolus: " + deliveryStepBolus); - log.debug("Delivery basal: " + deliveryBasal); - log.debug("Delivery ext bolus: " + deliveryExtBolus); + if (L.isEnabled(L.PUMPCOMM)) { + log.debug("Delivery prime: " + deliveryPrime); + log.debug("Delivery step bolus: " + deliveryStepBolus); + log.debug("Delivery basal: " + deliveryBasal); + log.debug("Delivery ext bolus: " + deliveryExtBolus); + } } catch (Exception e) { + log.error("Unhadled exception", e); } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Pump suspended: " + pump.pumpSuspended); log.debug("Calculator enabled: " + pump.calculatorEnabled); log.debug("Daily total units: " + pump.dailyTotalUnits); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBolus.java index 4fc9844b0d..49e00e1bbb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusBolus.java @@ -3,22 +3,24 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; /** * Created by mike on 28.05.2016. */ public class MsgInitConnStatusBolus extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBolus.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusBolus() { SetCommand(0x0302); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -34,7 +36,7 @@ public class MsgInitConnStatusBolus extends MessageBase { pump.maxBolus = intFromBuff(bytes, 2, 2) / 100d; //int bolusRate = intFromBuff(bytes, 4, 8); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Is Extended bolus enabled: " + pump.isExtendedBolusEnabled); log.debug("Bolus increment: " + pump.bolusStep); log.debug("Bolus max: " + pump.maxBolus); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusOption.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusOption.java index 560ed8b332..c3b73c0ae1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusOption.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusOption.java @@ -3,17 +3,19 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; /** * Created by mike on 28.05.2016. */ public class MsgInitConnStatusOption extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusOption.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusOption() { SetCommand(0x0304); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -29,7 +31,7 @@ public class MsgInitConnStatusOption extends MessageBase { //int none = intFromBuff(bytes, 8, 1); if (bytes.length >= 21) { DanaRPump.getInstance().password = intFromBuff(bytes, 9, 2) ^ 0x3463; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Pump password: " + DanaRPump.getInstance().password); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusTime.java index 84d9c413bf..93bea19218 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusTime.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgInitConnStatusTime.java @@ -5,11 +5,11 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -18,19 +18,21 @@ import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; public class MsgInitConnStatusTime extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusTime.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusTime() { SetCommand(0x0301); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] bytes) { if (bytes.length - 10 > 7) { - Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL); + Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model"); - log.debug("Wrong model selected. Switching to Korean DanaR"); + log.error("Wrong model selected. Switching to Korean DanaR"); MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, true); MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setFragmentVisible(PluginType.PUMP, true); MainApp.getSpecificPlugin(DanaRPlugin.class).setPluginEnabled(PluginType.PUMP, false); @@ -39,7 +41,7 @@ public class MsgInitConnStatusTime extends MessageBase { DanaRPump.reset(); // mark not initialized //If profile coming from pump, switch it as well - if(MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PROFILE)){ + if (MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PROFILE)) { (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PROFILE, false); (MainApp.getSpecificPlugin(DanaRKoreanPlugin.class)).setPluginEnabled(PluginType.PROFILE, true); } @@ -53,7 +55,7 @@ public class MsgInitConnStatusTime extends MessageBase { Date time = dateTimeSecFromBuff(bytes, 0); int versionCode = intFromBuff(bytes, 6, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Pump time: " + time); log.debug("Version code: " + versionCode); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStart.java index 619bbd9461..6f92c3241c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStart.java @@ -3,17 +3,20 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgPCCommStart extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgPCCommStart.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + public MsgPCCommStart() { SetCommand(0x3001); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] bytes) { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("PC comm start received"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStop.java index 20dd4e060f..255bb17532 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgPCCommStop.java @@ -3,17 +3,19 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgPCCommStop extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgPCCommStop.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgPCCommStop() { SetCommand(0x3002); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] bytes) { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("PC comm stop received"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetActivateBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetActivateBasalProfile.java index 64ed0488a4..2d222f9601 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetActivateBasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetActivateBasalProfile.java @@ -3,20 +3,22 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgSetActivateBasalProfile extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetActivateBasalProfile.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetActivateBasalProfile() { SetCommand(0x330C); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // index 0-3 public MsgSetActivateBasalProfile(byte index) { this(); AddParamByte(index); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Activate basal profile: " + index); } @@ -25,9 +27,10 @@ public class MsgSetActivateBasalProfile extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Activate basal profile result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Activate basal profile result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Activate basal profile result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetBasalProfile.java index 9f945e8b26..3e87e4bf41 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetBasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetBasalProfile.java @@ -3,17 +3,19 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; public class MsgSetBasalProfile extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetBasalProfile.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetBasalProfile() { SetCommand(0x3306); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } // index 0-3 @@ -23,7 +25,7 @@ public class MsgSetBasalProfile extends MessageBase { for (Integer i = 0; i < 24; i++) { AddParamInt((int) (values[i] * 100)); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set basal profile: " + index); } @@ -32,11 +34,12 @@ public class MsgSetBasalProfile extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set basal profile result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set basal profile result: " + result + " FAILED!!!"); Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.gs(R.string.profile_set_failed), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set basal profile result: " + result); Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60); MainApp.bus().post(new EventNewNotification(reportOK)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetCarbsEntry.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetCarbsEntry.java index 4fcd6dee9c..59cbcdafa0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetCarbsEntry.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetCarbsEntry.java @@ -5,13 +5,15 @@ import org.slf4j.LoggerFactory; import java.util.Calendar; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgSetCarbsEntry extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetCarbsEntry.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetCarbsEntry() { SetCommand(0x0402); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public MsgSetCarbsEntry(long time, int amount) { @@ -27,7 +29,7 @@ public class MsgSetCarbsEntry extends MessageBase { AddParamByte((byte) (calendar.get(Calendar.SECOND))); AddParamByte((byte) 0x43); //?? AddParamInt(amount); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set carb entry: " + amount + " date " + calendar.getTime().toString()); } @@ -36,9 +38,10 @@ public class MsgSetCarbsEntry extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set carb entry result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set carb entry result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set carb entry result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStart.java index 420f0ccbf9..a7f2a0e1b8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStart.java @@ -3,16 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.utils.HardLimits; +import info.nightscout.androidaps.logging.L; public class MsgSetExtendedBolusStart extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStart.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetExtendedBolusStart() { SetCommand(0x0407); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public MsgSetExtendedBolusStart(double amount, byte halfhours) { @@ -25,7 +26,7 @@ public class MsgSetExtendedBolusStart extends MessageBase { AddParamInt((int) (amount * 100)); AddParamByte(halfhours); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set extended bolus start: " + (((int) (amount * 100)) / 100d) + "U halfhours: " + (int) halfhours); } @@ -34,9 +35,10 @@ public class MsgSetExtendedBolusStart extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set extended bolus start result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set extended bolus start result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set extended bolus start result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStop.java index 7084949daa..504db719ea 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetExtendedBolusStop.java @@ -3,15 +3,15 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgSetExtendedBolusStop extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetExtendedBolusStop.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetExtendedBolusStop() { SetCommand(0x0406); - if (Config.logDanaMessageDetail) - log.debug("Set extended bolus stop"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -19,9 +19,10 @@ public class MsgSetExtendedBolusStop extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set extended bolus stop result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set extended bolus stop result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set extended bolus stop result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetSingleBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetSingleBasalProfile.java index 7dd9ca522b..eabf383b94 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetSingleBasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetSingleBasalProfile.java @@ -3,14 +3,14 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; public class MsgSetSingleBasalProfile extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetSingleBasalProfile.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetSingleBasalProfile() { SetCommand(0x3302); @@ -22,8 +22,8 @@ public class MsgSetSingleBasalProfile extends MessageBase { for (Integer i = 0; i < 24; i++) { AddParamInt((int) (values[i] * 100)); } - if (Config.logDanaMessageDetail) - log.debug("Set basal profile"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -31,11 +31,12 @@ public class MsgSetSingleBasalProfile extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set basal profile result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set basal profile result: " + result + " FAILED!!!"); Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.gs(R.string.profile_set_failed), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set basal profile result: " + result); Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60); MainApp.bus().post(new EventNewNotification(reportOK)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStart.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStart.java index 2b72c35749..c756af3491 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStart.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStart.java @@ -3,10 +3,10 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgSetTempBasalStart extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetTempBasalStart.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetTempBasalStart() { SetCommand(0x0401); @@ -24,7 +24,7 @@ public class MsgSetTempBasalStart extends MessageBase { AddParamByte((byte) (percent & 255)); AddParamByte((byte) (durationInHours & 255)); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Temp basal start percent: " + percent + " duration hours: " + durationInHours); } @@ -32,9 +32,10 @@ public class MsgSetTempBasalStart extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set temp basal start result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set temp basal start result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set temp basal start result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStop.java index 39582ac399..7b14e8e3e3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTempBasalStop.java @@ -3,14 +3,14 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class MsgSetTempBasalStop extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetTempBasalStop.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetTempBasalStop() { SetCommand(0x0403); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Temp basal stop"); } @@ -18,9 +18,10 @@ public class MsgSetTempBasalStop extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set temp basal stop result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set temp basal stop result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set temp basal stop result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTime.java index 3910d52c97..6d33aef8cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTime.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetTime.java @@ -5,26 +5,29 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; +import info.nightscout.utils.DateUtil; /** * Created by mike on 09.12.2016. */ public class MsgSetTime extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetTime.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Date time; public MsgSetTime(Date time) { SetCommand(0x330a); this.time = time; AddParamDateTime(time); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: time:" + DateUtil.dateAndTimeString(time)); } public void handleMessage(byte[] bytes) { int result = intFromBuff(bytes, 0, 1); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Result of setting time: " + time + " is " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetUserOptions.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetUserOptions.java index 407b19da8d..7484966dba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetUserOptions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MsgSetUserOptions.java @@ -2,9 +2,8 @@ package info.nightscout.androidaps.plugins.PumpDanaR.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import android.support.v4.internal.view.SupportMenu; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; /** @@ -12,7 +11,7 @@ import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; */ public class MsgSetUserOptions extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetUserOptions.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public boolean done; @@ -21,7 +20,7 @@ public class MsgSetUserOptions extends MessageBase { DanaRPump pump = DanaRPump.getInstance(); if (pump.userOptionsFrompump == null) { // No options set -> Exitting - log.debug("NO USER OPTIONS LOADED EXITTING!"); + log.error("NO USER OPTIONS LOADED EXITTING!"); return; } pump.userOptionsFrompump[0] = (byte) (pump.timeDisplayType == 1 ? 0 : 1); @@ -33,18 +32,21 @@ public class MsgSetUserOptions extends MessageBase { pump.userOptionsFrompump[8] = (byte) pump.units; pump.userOptionsFrompump[9] = (byte) pump.shutdownHour; pump.userOptionsFrompump[27] = (byte) pump.lowReservoirRate; - for(int i=0; i>>>> @ " + (mBolusingTreatment == null ? "" : mBolusingTreatment.insulin)); MsgBolusStop stop = new MsgBolusStop(); stop.forced = true; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java index ea4dec25fb..446913b1b8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/services/DanaRExecutionService.java @@ -7,12 +7,9 @@ import android.os.SystemClock; import com.squareup.otto.Subscribe; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -24,7 +21,9 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; 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.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; @@ -64,13 +63,12 @@ import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; -public class DanaRExecutionService extends AbstractDanaRExecutionService{ +public class DanaRExecutionService extends AbstractDanaRExecutionService { public DanaRExecutionService() { - log = LoggerFactory.getLogger(DanaRExecutionService.class); mBinder = new LocalBinder(); registerBus(); @@ -100,7 +98,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ public void connect() { if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) { - if(System.currentTimeMillis() > lastWrongPumpPassword + 30 * 1000) { + if (System.currentTimeMillis() > lastWrongPumpPassword + 30 * 1000) { Notification notification = new Notification(Notification.WRONG_PUMP_PASSWORD, MainApp.gs(R.string.wrongpumppassword), Notification.URGENT); notification.soundId = R.raw.error; lastWrongPumpPassword = System.currentTimeMillis(); @@ -170,7 +168,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ long now = System.currentTimeMillis(); mDanaRPump.lastConnection = now; - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (profile != null && Math.abs(mDanaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); @@ -196,12 +194,14 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 10) { mSerialIOThread.sendMessage(new MsgSetTime(new Date())); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds"); } mDanaRPump.lastSettingsRead = now; } @@ -210,8 +210,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ MainApp.bus().post(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { - log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); - if(System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { + if (L.isEnabled(L.PUMP)) + log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); + if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U"); @@ -301,7 +302,8 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm stop.stopped = true; stop.forced = true; - log.debug("Communication stopped"); + if (L.isEnabled(L.PUMP)) + log.debug("Communication stopped"); } } SystemClock.sleep(300); @@ -344,9 +346,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ public void run() { if (mDanaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old t.insulin = mDanaRPump.lastBolusAmount; - log.debug("Used bolus amount from history: " + mDanaRPump.lastBolusAmount); + if (L.isEnabled(L.PUMP)) + log.debug("Used bolus amount from history: " + mDanaRPump.lastBolusAmount); } else { - log.debug("Bolus amount in history too old: " + mDanaRPump.lastBolusTime.toLocaleString()); + if (L.isEnabled(L.PUMP)) + log.debug("Bolus amount in history too old: " + mDanaRPump.lastBolusTime.toLocaleString()); } synchronized (o) { o.notify(); @@ -386,7 +390,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ public boolean updateBasalsInPump(final Profile profile) { if (!isConnected()) return false; MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); - double[] basal = DanaRPump.buildDanaRProfileRecord(profile); + double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); mSerialIOThread.sendMessage(msgSet); MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0); @@ -399,7 +403,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ @Subscribe public void onStatusEvent(EventAppExit event) { - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received"); if (mSerialIOThread != null) @@ -408,7 +412,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{ MainApp.instance().getApplicationContext().unregisterReceiver(receiver); stopSelf(); - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit finished"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java index 49edb6b096..327a8a5dea 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/DanaRKoreanPlugin.java @@ -11,9 +11,6 @@ import android.support.v7.app.AlertDialog; import com.squareup.otto.Subscribe; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -26,6 +23,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.PumpDanaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStart; @@ -51,7 +49,6 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { public DanaRKoreanPlugin() { pluginDescription.description(R.string.description_pump_dana_r_korean); - log = LoggerFactory.getLogger(DanaRKoreanPlugin.class); useExtendedBoluses = SP.getBoolean("danar_useextended", false); pumpDescription.isBolusCapable = true; @@ -87,7 +84,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { @Override public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); - if (allowHardwarePump || context == null){ + if (allowHardwarePump || context == null) { pluginSwitcher.invoke(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(context); @@ -96,13 +93,15 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.invoke(); SP.putBoolean("allow_hardware_pump", true); - log.debug("First time HW pump allowed!"); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.cancel(); - log.debug("User does not allow switching to HW pump!"); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); } }); builder.create().show(); @@ -130,12 +129,14 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { - log.debug("Service is disconnected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is disconnected"); sExecutionService = null; } public void onServiceConnected(ComponentName name, IBinder service) { - log.debug("Service is connected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is connected"); DanaRKoreanExecutionService.LocalBinder mLocalBinder = (DanaRKoreanExecutionService.LocalBinder) service; sExecutionService = mLocalBinder.getServiceInstance(); } @@ -198,7 +199,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStart.errorCode); else result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); detailedBolusInfo.insulin = t.insulin; detailedBolusInfo.date = System.currentTimeMillis(); @@ -240,13 +241,13 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { if (doTempOff) { // If extended in progress if (activeExtended != null && useExtendedBoluses) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping extended bolus (doTempOff)"); return cancelExtendedBolus(); } // If temp in progress if (activeTemp != null) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)"); return cancelRealTempBasal(); } @@ -255,7 +256,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { result.percent = 100; result.isPercent = true; result.isTempCancel = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: doTempOff OK"); return result; } @@ -267,12 +268,12 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { if (percentRate > getPumpDescription().maxTempPercent) { percentRate = getPumpDescription().maxTempPercent; } - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Calculated percent rate: " + percentRate); // If extended in progress if (activeExtended != null && useExtendedBoluses) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)"); result = cancelExtendedBolus(); if (!result.success) { @@ -283,7 +284,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { // Check if some temp is already in progress if (activeTemp != null) { // Correct basal already set ? - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: currently running: " + activeTemp.toString()); if (activeTemp.percentRate == percentRate) { if (enforceNew) { @@ -295,21 +296,21 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { result.duration = activeTemp.getPlannedRemainingMinutes(); result.isPercent = true; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); return result; } } } // Convert duration from minutes to hours - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); return setTempBasalPercent(percentRate, durationInMinutes, profile, false); } if (doExtendedTemp) { // Check if some temp is already in progress if (activeTemp != null) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping temp basal (doExtendedTemp)"); result = cancelRealTempBasal(); // Check for proper result @@ -328,7 +329,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours // What is current rate of extended bolusing in u/h? - if (Config.logPumpActions) { + if (L.isEnabled(L.PUMP)) { log.debug("setTempBasalAbsolute: Extended bolus in progress: " + (activeExtended != null) + " rate: " + pump.extendedBolusAbsoluteRate + "U/h duration remaining: " + pump.extendedBolusRemainingMinutes + "min"); log.debug("setTempBasalAbsolute: Rate to set: " + extendedRateToSet + "U/h"); } @@ -342,21 +343,21 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { result.duration = pump.extendedBolusRemainingMinutes; result.isPercent = false; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Correct extended already set"); return result; } // Now set new extended, no need to to stop previous (if running) because it's replaced Double extendedAmount = extendedRateToSet / 2 * durationInHalfHours; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Setting extended: " + extendedAmount + "U halfhours: " + durationInHalfHours); result = setExtendedBolus(extendedAmount, durationInMinutes); if (!result.success) { log.error("setTempBasalAbsolute: Failed to set extended bolus"); return result; } - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Extended bolus set ok"); result.absolute = result.absolute + getBaseBasalRate(); return result; @@ -395,7 +396,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { result.success = true; result.isTempCancel = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("cancelRealTempBasal: OK"); return result; } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java index 9a8f3edb05..ea12b2b9c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java @@ -10,7 +10,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread; @@ -21,7 +21,7 @@ import info.nightscout.utils.CRC; * Created by mike on 17.07.2016. */ public class SerialIOThread extends AbstractSerialIOThread { - private static Logger log = LoggerFactory.getLogger(SerialIOThread.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPBTCOMM); private InputStream mInputStream = null; private OutputStream mOutputStream = null; @@ -72,7 +72,7 @@ public class SerialIOThread extends AbstractSerialIOThread { message = MessageHashTable_k.findMessage(command); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff)); // process the message content @@ -84,7 +84,7 @@ public class SerialIOThread extends AbstractSerialIOThread { } } } catch (Exception e) { - if (Config.logDanaSerialEngine && e.getMessage().indexOf("bt socket closed") < 0) + if (e.getMessage().indexOf("bt socket closed") < 0) log.error("Thread exception: ", e); mKeepRunning = false; } @@ -148,7 +148,7 @@ public class SerialIOThread extends AbstractSerialIOThread { processedMessage = message; byte[] messageBytes = message.getRawMessageBytes(); - if (Config.logDanaSerialEngine) + if (L.isEnabled(L.PUMPBTCOMM)) log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes)); try { @@ -167,10 +167,11 @@ public class SerialIOThread extends AbstractSerialIOThread { SystemClock.sleep(200); if (!message.received) { - log.warn("Reply not received " + message.getMessageName()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.warn("Reply not received " + message.getMessageName()); if (message.getCommand() == 0xF0F1) { DanaRPump.getInstance().isNewPump = false; - log.debug("Old firmware detected"); + log.error("Old firmware detected"); } } } @@ -181,24 +182,29 @@ public class SerialIOThread extends AbstractSerialIOThread { try { mInputStream.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { mOutputStream.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { mRfCommSocket.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { System.runFinalization(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } - if (Config.logDanaSerialEngine) log.debug("Disconnected: " + reason); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Disconnected: " + reason); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgCheckValue_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgCheckValue_k.java index 684fa30997..7bde73d5a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgCheckValue_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgCheckValue_k.java @@ -3,22 +3,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; -import info.nightscout.utils.ToastUtils; /** * Created by mike on 30.06.2016. */ public class MsgCheckValue_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgCheckValue_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgCheckValue_k() { SetCommand(0xF0F1); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -26,17 +25,18 @@ public class MsgCheckValue_k extends MessageBase { DanaRPump pump = DanaRPump.getInstance(); pump.isNewPump = true; - log.debug("New firmware confirmed"); + if (L.isEnabled(L.PUMP)) + log.debug("New firmware confirmed"); pump.model = intFromBuff(bytes, 0, 1); pump.protocol = intFromBuff(bytes, 1, 1); pump.productCode = intFromBuff(bytes, 2, 1); if (pump.model != DanaRPump.DOMESTIC_MODEL) { DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model"); - log.debug("Wrong model selected"); + log.error("Wrong model selected"); } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMP)) { log.debug("Model: " + String.format("%02X ", pump.model)); log.debug("Protocol: " + String.format("%02X ", pump.protocol)); log.debug("Product Code: " + String.format("%02X ", pump.productCode)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBasic_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBasic_k.java index fa28e664ed..46222938d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBasic_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBasic_k.java @@ -3,20 +3,22 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgInitConnStatusBasic_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBasic_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusBasic_k() { SetCommand(0x0303); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -30,7 +32,7 @@ public class MsgInitConnStatusBasic_k extends MessageBase { pump.isEasyModeEnabled = intFromBuff(bytes, 2, 1) == 1; int easyUIMode = intFromBuff(bytes, 3, 1); pump.password = intFromBuff(bytes, 4, 2) ^ 0x3463; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("isStatusSuspendOn: " + pump.pumpSuspended); log.debug("isUtilityEnable: " + isUtilityEnable); log.debug("Is EasyUI Enabled: " + pump.isEasyModeEnabled); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBolus_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBolus_k.java index 552511cf7c..4be04f538f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBolus_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusBolus_k.java @@ -3,23 +3,25 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; +import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; /** * Created by mike on 28.05.2016. */ public class MsgInitConnStatusBolus_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusBolus_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusBolus_k() { SetCommand(0x0302); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -36,7 +38,7 @@ public class MsgInitConnStatusBolus_k extends MessageBase { //int bolusRate = intFromBuff(bytes, 4, 8); int deliveryStatus = intFromBuff(bytes, 12, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Is Extended bolus enabled: " + pump.isExtendedBolusEnabled); log.debug("Bolus increment: " + pump.bolusStep); log.debug("Bolus max: " + pump.maxBolus); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusTime_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusTime_k.java index 7553b0cc37..5aadfeae42 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusTime_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgInitConnStatusTime_k.java @@ -5,11 +5,11 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -19,10 +19,12 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; public class MsgInitConnStatusTime_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgInitConnStatusTime_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgInitConnStatusTime_k() { SetCommand(0x0301); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -32,7 +34,7 @@ public class MsgInitConnStatusTime_k extends MessageBase { Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model"); - log.debug("Wrong model selected. Switching to export DanaR"); + log.error("Wrong model selected. Switching to export DanaR"); MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, false); MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setFragmentVisible(PluginType.PUMP, false); MainApp.getSpecificPlugin(DanaRPlugin.class).setPluginEnabled(PluginType.PUMP, true); @@ -58,7 +60,7 @@ public class MsgInitConnStatusTime_k extends MessageBase { int versionCode3 = intFromBuff(bytes, 8, 1); int versionCode4 = intFromBuff(bytes, 9, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Pump time: " + time); log.debug("Version code1: " + versionCode1); log.debug("Version code2: " + versionCode2); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasalProfileAll_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasalProfileAll_k.java index 304ec9fc37..2455f59e14 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasalProfileAll_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasalProfileAll_k.java @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; @@ -15,10 +15,12 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; * THIS IS BROKEN IN PUMP... SENDING ONLY 1 PROFILE */ public class MsgSettingBasalProfileAll_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSettingBasalProfileAll_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSettingBasalProfileAll_k() { SetCommand(0x3206); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -49,7 +51,7 @@ public class MsgSettingBasalProfileAll_k extends MessageBase { } } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (pump.basal48Enable) { for (int profile = 0; profile < 4; profile++) { for (int index = 0; index < 24; index++) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasal_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasal_k.java index 5c8b40b959..b149ceb2ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasal_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgSettingBasal_k.java @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; @@ -12,10 +12,12 @@ import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; * Created by mike on 05.07.2016. */ public class MsgSettingBasal_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSettingBasal_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSettingBasal_k() { SetCommand(0x3202); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -28,7 +30,7 @@ public class MsgSettingBasal_k extends MessageBase { pump.pumpProfiles[pump.activeProfile][index] = basal / 100d; } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) for (int index = 0; index < 24; index++) { log.debug("Basal " + String.format("%02d", index) + "h: " + pump.pumpProfiles[pump.activeProfile][index]); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatusBasic_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatusBasic_k.java index 0fcaf17d83..d22c6e376a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatusBasic_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatusBasic_k.java @@ -3,16 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgStatusBasic_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgStatusBasic_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgStatusBasic_k() { SetCommand(0x020A); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -29,7 +31,7 @@ public class MsgStatusBasic_k extends MessageBase { pump.currentBasal = currentBasal; pump.batteryRemaining = batteryRemaining; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Daily total units: " + dailyTotalUnits); log.debug("Max daily total units: " + maxDailyTotalUnits); log.debug("Reservoir remaining units: " + reservoirRemainingUnits); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatus_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatus_k.java index 1fdcf26917..4d8b012244 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatus_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MsgStatus_k.java @@ -3,15 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgStatus_k extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgStatus_k.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgStatus_k() { SetCommand(0x020B); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -27,7 +29,7 @@ public class MsgStatus_k extends MessageBase { // } pump.iob = intFromBuff(bytes, 15, 2) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Daily total: " + pump.dailyTotalUnits); log.debug("Is extended bolus running: " + pump.isExtendedInProgress); log.debug("Extended bolus min: " + pump.extendedBolusMinutes); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java index 0f4afa4314..4be6cee2c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/services/DanaRKoreanExecutionService.java @@ -7,12 +7,9 @@ import android.os.SystemClock; import com.squareup.otto.Subscribe; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -24,7 +21,9 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; 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.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -50,20 +49,18 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusBolusExtended; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgStatusTempBasal; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractDanaRExecutionService; -import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRKorean.SerialIOThread; import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgCheckValue_k; import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgSettingBasal_k; import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MsgStatusBasic_k; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public DanaRKoreanExecutionService() { - log = LoggerFactory.getLogger(DanaRKoreanExecutionService.class); mBinder = new LocalBinder(); registerBus(); @@ -87,7 +84,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Subscribe public void onStatusEvent(EventAppExit event) { - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received"); if (mSerialIOThread != null) @@ -96,7 +93,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { MainApp.instance().getApplicationContext().unregisterReceiver(receiver); stopSelf(); - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit finished"); } @@ -108,7 +105,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public void connect() { if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) { - if(System.currentTimeMillis() > lastWrongPumpPassword + 30 * 1000) { + if (System.currentTimeMillis() > lastWrongPumpPassword + 30 * 1000) { Notification notification = new Notification(Notification.WRONG_PUMP_PASSWORD, MainApp.gs(R.string.wrongpumppassword), Notification.URGENT); notification.soundId = R.raw.error; lastWrongPumpPassword = System.currentTimeMillis(); @@ -119,35 +116,32 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (mConnectionInProgress) return; - new Thread(new Runnable() { - @Override - public void run() { - mConnectionInProgress = true; - getBTSocketForSelectedPump(); - if (mRfcommSocket == null || mBTDevice == null) { - mConnectionInProgress = false; - return; // Device not found - } - - try { - mRfcommSocket.connect(); - } catch (IOException e) { - //log.error("Unhandled exception", e); - if (e.getMessage().contains("socket closed")) { - log.error("Unhandled exception", e); - } - } - - if (isConnected()) { - if (mSerialIOThread != null) { - mSerialIOThread.disconnect("Recreate SerialIOThread"); - } - mSerialIOThread = new SerialIOThread(mRfcommSocket); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0)); - } - + new Thread(() -> { + mConnectionInProgress = true; + getBTSocketForSelectedPump(); + if (mRfcommSocket == null || mBTDevice == null) { mConnectionInProgress = false; + return; // Device not found } + + try { + mRfcommSocket.connect(); + } catch (IOException e) { + //log.error("Unhandled exception", e); + if (e.getMessage().contains("socket closed")) { + log.error("Unhandled exception", e); + } + } + + if (isConnected()) { + if (mSerialIOThread != null) { + mSerialIOThread.disconnect("Recreate SerialIOThread"); + } + mSerialIOThread = new SerialIOThread(mRfcommSocket); + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0)); + } + + mConnectionInProgress = false; }).start(); } @@ -178,7 +172,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { long now = System.currentTimeMillis(); mDanaRPump.lastConnection = now; - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (profile != null && Math.abs(mDanaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); @@ -200,12 +194,14 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 10) { mSerialIOThread.sendMessage(new MsgSetTime(new Date())); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds"); } mDanaRPump.lastSettingsRead = now; } @@ -214,8 +210,9 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { MainApp.bus().post(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { - log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); - if(System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { + if (L.isEnabled(L.PUMP)) + log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); + if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U"); @@ -300,7 +297,8 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm stop.stopped = true; stop.forced = true; - log.debug("Communication stopped"); + if (L.isEnabled(L.PUMP)) + log.debug("Communication stopped"); } } SystemClock.sleep(300); @@ -332,7 +330,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { if (!isConnected()) return false; MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); - double[] basal = DanaRPump.buildDanaRProfileRecord(profile); + double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal); mSerialIOThread.sendMessage(msgSet); mDanaRPump.lastSettingsRead = 0; // force read full settings diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java index 36edf1e94f..f83702d7c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/DanaRSPlugin.java @@ -20,7 +20,6 @@ import org.slf4j.LoggerFactory; import java.util.Date; import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -39,8 +38,10 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.DetailedBolusInfoStorage; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -64,7 +65,7 @@ import info.nightscout.utils.T; */ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface { - private static Logger log = LoggerFactory.getLogger(DanaRSPlugin.class); + private Logger log = LoggerFactory.getLogger(L.PUMP); private static DanaRSPlugin plugin = null; public static DanaRSPlugin getPlugin() { @@ -155,7 +156,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); - if (allowHardwarePump || context == null){ + if (allowHardwarePump || context == null) { pluginSwitcher.invoke(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(context); @@ -164,13 +165,15 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte public void onClick(DialogInterface dialog, int id) { pluginSwitcher.invoke(); SP.putBoolean("allow_hardware_pump", true); - log.debug("First time HW pump allowed!"); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.cancel(); - log.debug("User does not allow switching to HW pump!"); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); } }); builder.create().show(); @@ -180,12 +183,14 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { - log.debug("Service is disconnected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is disconnected"); danaRSService = null; } public void onServiceConnected(ComponentName name, IBinder service) { - log.debug("Service is connected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is connected"); DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder) service; danaRSService = mLocalBinder.getServiceInstance(); } @@ -205,7 +210,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public void connect(String from) { - log.debug("RS connect from: " + from); + if (L.isEnabled(L.PUMP)) + log.debug("RS connect from: " + from); if (danaRSService != null && !mDeviceAddress.equals("") && !mDeviceName.equals("")) { final Object o = new Object(); @@ -225,6 +231,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte @Override public void disconnect(String from) { + if (L.isEnabled(L.PUMP)) + log.debug("RS disconnect from: " + from); if (danaRSService != null) danaRSService.disconnect(from); } @@ -370,7 +378,8 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte Double profileValue = profile.getBasalTimeFromMidnight((Integer) (h * basalIncrement)); if (profileValue == null) return true; if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { - log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); + if (L.isEnabled(L.PUMP)) + log.debug("Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); return false; } } @@ -430,7 +439,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, DanaRS_Packet_Bolus_Set_Step_Bolus_Start.errorCode); else result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); return result; } else { @@ -474,7 +483,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte if (doTempOff) { // If temp in progress if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)"); return cancelTempBasal(false); } @@ -483,7 +492,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.percent = 100; result.isPercent = true; result.isTempCancel = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: doTempOff OK"); return result; } @@ -497,7 +506,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte // Check if some temp is already in progress TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: currently running: " + activeTemp.toString()); // Correct basal already set ? if (activeTemp.percentRate == percentRate) { @@ -508,14 +517,14 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.duration = activeTemp.getPlannedRemainingMinutes(); result.isPercent = true; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); return result; } } } // Convert duration from minutes to hours - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); if (percentRate == 0 && durationInMinutes > 30) { result = setTempBasalPercent(percentRate, durationInMinutes, profile, false); @@ -527,7 +536,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte log.error("setTempBasalAbsolute: Failed to set hightemp basal"); return result; } - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: hightemp basal set ok"); return result; } @@ -562,7 +571,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent: Correct value already set"); return result; } @@ -581,7 +590,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent: OK"); return result; } @@ -603,7 +612,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setHighTempBasalPercent: OK"); return result; } @@ -630,7 +639,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.absolute = pump.extendedBolusAbsoluteRate; result.isPercent = false; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount + " Asked: " + insulin); return result; } @@ -644,7 +653,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.absolute = pump.extendedBolusAbsoluteRate; result.bolusDelivered = pump.extendedBolusAmount; result.isPercent = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setExtendedBolus: OK"); return result; } @@ -668,7 +677,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte result.success = true; result.isTempCancel = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("cancelRealTempBasal: OK"); return result; } else { @@ -692,7 +701,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte if (!pump.isExtendedInProgress) { result.success = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("cancelExtendedBolus: OK"); return result; } else { @@ -737,7 +746,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } extended.put("BaseBasalRate", getBaseBasalRate()); try { - extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName()); + extended.put("ActiveProfile", ProfileFunctions.getInstance().getProfileName()); } catch (Exception e) { } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java index 3b6bcaf099..7594e917c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/BLEScanActivity.java @@ -31,9 +31,6 @@ import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSDeviceCha import info.nightscout.utils.SP; public class BLEScanActivity extends AppCompatActivity { - private static Logger log = LoggerFactory.getLogger(BLEScanActivity.class); - - private ListView listView = null; private ListAdapter mListAdapter = null; private ArrayList mDevices = new ArrayList<>(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java index 9f72e1d08f..5f339cd528 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/activities/PairingProgressDialog.java @@ -9,7 +9,6 @@ import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.view.Window; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; @@ -63,46 +62,37 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic button.setOnClickListener(this); setCancelable(false); - sHandler.post(new Runnable() { - @Override - public void run() { - for (int i = 0; i < 20; i++) { - if (pairingEnded) { - Activity activity = getActivity(); - if (activity != null) { - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - progressBar.setProgress(100); - statusView.setText(R.string.pairingok); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - dismiss(); - } - }); - } else - dismiss(); - return; - } - progressBar.setProgress(i * 5); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - } - } - Activity activity = getActivity(); - if (activity != null) { - activity.runOnUiThread(new Runnable() { - @Override - public void run() { + sHandler.post(() -> { + for (int i = 0; i < 20; i++) { + if (pairingEnded) { + Activity activity = getActivity(); + if (activity != null) { + activity.runOnUiThread(() -> { progressBar.setProgress(100); - statusView.setText(R.string.pairingtimedout); - button.setVisibility(View.VISIBLE); - } - }); + statusView.setText(R.string.pairingok); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { + } + dismiss(); + }); + } else + dismiss(); + return; } + progressBar.setProgress(i * 5); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) { + } + } + Activity activity = getActivity(); + if (activity != null) { + activity.runOnUiThread(() -> { + progressBar.setProgress(100); + statusView.setText(R.string.pairingtimedout); + button.setVisibility(View.VISIBLE); + }); } }); return view; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRSMessageHashTable.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRSMessageHashTable.java index 5457bb4155..bda5d42207 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRSMessageHashTable.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRSMessageHashTable.java @@ -1,25 +1,17 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.HashMap; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 28.05.2016. */ public class DanaRSMessageHashTable { - private static Logger log = LoggerFactory.getLogger(DanaRSMessageHashTable.class); - public static HashMap messages = null; static { if (messages == null) { - boolean savedState = Config.logDanaMessageDetail; - Config.logDanaMessageDetail = false; - messages = new HashMap<>(); put(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal()); put(new DanaRS_Packet_Basal_Get_Basal_Rate()); @@ -89,7 +81,6 @@ public class DanaRSMessageHashTable { put(new DanaRS_Packet_APS_History_Events()); put(new DanaRS_Packet_APS_Set_Event_History()); - Config.logDanaMessageDetail = savedState; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.java index 5da3655ceb..c33cd7b405 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Basal_Set_Temporary_Basal.java @@ -5,10 +5,10 @@ import com.cozmo.danar.util.BleCommandUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_APS_Basal_Set_Temporary_Basal extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_APS_Basal_Set_Temporary_Basal.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); int temporaryBasalRatio; int temporaryBasalDuration; @@ -25,6 +25,8 @@ public class DanaRS_Packet_APS_Basal_Set_Temporary_Basal extends DanaRS_Packet { public DanaRS_Packet_APS_Basal_Set_Temporary_Basal(int percent) { this(); setParams(percent); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: percent: " + percent); } protected void setParams(int percent) { @@ -35,16 +37,16 @@ public class DanaRS_Packet_APS_Basal_Set_Temporary_Basal extends DanaRS_Packet { temporaryBasalRatio = percent; if (percent < 100) { temporaryBasalDuration = PARAM30MIN; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 30 min"); } else { temporaryBasalDuration = PARAM15MIN; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 15 min"); } } - public DanaRS_Packet_APS_Basal_Set_Temporary_Basal(int percent, boolean fifteenMinutes, boolean thirtyMinutes ) { + public DanaRS_Packet_APS_Basal_Set_Temporary_Basal(int percent, boolean fifteenMinutes, boolean thirtyMinutes) { this(); setParams(percent, fifteenMinutes, thirtyMinutes); } @@ -57,11 +59,11 @@ public class DanaRS_Packet_APS_Basal_Set_Temporary_Basal extends DanaRS_Packet { temporaryBasalRatio = percent; if (thirtyMinutes && percent <= 200) { // 30 min is allowed up to 200% temporaryBasalDuration = PARAM30MIN; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 30 min"); } else { temporaryBasalDuration = PARAM15MIN; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 15 min"); } } @@ -80,10 +82,11 @@ public class DanaRS_Packet_APS_Basal_Set_Temporary_Basal extends DanaRS_Packet { int result = byteArrayToInt(getBytes(data, DATA_START, 1)); if (result != 0) { failed = true; - log.error("Set APS temp basal start result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set APS temp basal start result: " + result + " FAILED!!!"); } else { failed = false; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set APS temp basal start result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_History_Events.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_History_Events.java index b8c8aaf2b4..60e640bc77 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_History_Events.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_History_Events.java @@ -16,13 +16,14 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventPumpStatusChanged; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_APS_History_Events.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int year = 0; private int month = 0; @@ -32,7 +33,6 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { private int sec = 0; public static boolean done; - private static int totalCount; public static long lastEventTimeLoaded = 0; @@ -40,7 +40,6 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS; done = false; - totalCount = 0; } public DanaRS_Packet_APS_History_Events(long from) { @@ -56,7 +55,8 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { hour = cal.get(Calendar.HOUR_OF_DAY); min = cal.get(Calendar.MINUTE); sec = cal.get(Calendar.SECOND); - log.debug("Loading event history from: " + new Date(cal.getTimeInMillis()).toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Loading event history from: " + new Date(cal.getTimeInMillis()).toLocaleString()); } @Override @@ -78,7 +78,8 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { // Last record if (recordCode == (byte) 0xFF) { done = true; - log.debug("Last record received"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Last record received"); return; } @@ -95,10 +96,12 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime.getTime()); if (detailedBolusInfo == null) { - log.debug("Detailed bolus info not found for " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Detailed bolus info not found for " + datetime.toLocaleString()); detailedBolusInfo = new DetailedBolusInfo(); } else { - log.debug("Detailed bolus info found: " + detailedBolusInfo); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Detailed bolus info found: " + detailedBolusInfo); } detailedBolusInfo.date = datetime.getTime(); detailedBolusInfo.source = Source.PUMP; @@ -108,73 +111,86 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { switch (recordCode) { case DanaRPump.TEMPSTART: - log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); temporaryBasal.percentRate = param1; temporaryBasal.durationInMinutes = param2; TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); status = "TEMPSTART " + DateUtil.timeString(datetime); break; case DanaRPump.TEMPSTOP: - log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); status = "TEMPSTOP " + DateUtil.timeString(datetime); break; case DanaRPump.EXTENDEDSTART: - log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); extendedBolus.insulin = param1 / 100d; extendedBolus.durationInMinutes = param2; TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "EXTENDEDSTART " + DateUtil.timeString(datetime); break; case DanaRPump.EXTENDEDSTOP: - log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "EXTENDEDSTOP " + DateUtil.timeString(datetime); break; case DanaRPump.BOLUS: detailedBolusInfo.insulin = param1 / 100d; boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); - log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); DetailedBolusInfoStorage.remove(detailedBolusInfo.date); status = "BOLUS " + DateUtil.timeString(datetime); break; case DanaRPump.DUALBOLUS: detailedBolusInfo.insulin = param1 / 100d; newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); - log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); DetailedBolusInfoStorage.remove(detailedBolusInfo.date); status = "DUALBOLUS " + DateUtil.timeString(datetime); break; case DanaRPump.DUALEXTENDEDSTART: - log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); extendedBolus.insulin = param1 / 100d; extendedBolus.durationInMinutes = param2; TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "DUALEXTENDEDSTART " + DateUtil.timeString(datetime); break; case DanaRPump.DUALEXTENDEDSTOP: - log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime); break; case DanaRPump.SUSPENDON: - log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); status = "SUSPENDON " + DateUtil.timeString(datetime); break; case DanaRPump.SUSPENDOFF: - log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString()); status = "SUSPENDOFF " + DateUtil.timeString(datetime); break; case DanaRPump.REFILL: - log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); status = "REFILL " + DateUtil.timeString(datetime); break; case DanaRPump.PRIME: - log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); status = "PRIME " + DateUtil.timeString(datetime); break; case DanaRPump.PROFILECHANGE: - log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h"); status = "PROFILECHANGE " + DateUtil.timeString(datetime); break; case DanaRPump.CARBS: @@ -184,15 +200,18 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { emptyCarbsInfo.source = Source.PUMP; emptyCarbsInfo.pumpId = datetime.getTime(); newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(emptyCarbsInfo, false); - log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); status = "CARBS " + DateUtil.timeString(datetime); break; case DanaRPump.PRIMECANNULA: - log.debug("EVENT PRIMECANNULA(" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT PRIMECANNULA(" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); status = "PRIMECANNULA " + DateUtil.timeString(datetime); break; default: - log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); status = "UNKNOWN " + DateUtil.timeString(datetime); break; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Set_Event_History.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Set_Event_History.java index 84ead83665..2a5e9eade6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Set_Event_History.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_APS_Set_Event_History.java @@ -8,16 +8,16 @@ import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.GregorianCalendar; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.utils.DateUtil; public class DanaRS_Packet_APS_Set_Event_History extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_APS_Set_Event_History.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int type; private long time; - public int param1; - public int param2; + private int param1; + private int param2; public DanaRS_Packet_APS_Set_Event_History() { super(); @@ -31,7 +31,7 @@ public class DanaRS_Packet_APS_Set_Event_History extends DanaRS_Packet { this.time = time; this.param1 = param1; this.param2 = param2; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set history entry: " + DateUtil.dateAndTimeString(time) + " type: " + type + " param1: " + param1 + " param2: " + param2); } @@ -66,9 +66,10 @@ public class DanaRS_Packet_APS_Set_Event_History extends DanaRS_Packet { int result = intFromBuff(data, 0, 1); if (result != 0) { failed = true; - log.error("Set history entry result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.error("Set history entry result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set history entry result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Basal_Rate.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Basal_Rate.java index f3fef0d49d..a067d2976d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Basal_Rate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Basal_Rate.java @@ -1,27 +1,27 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import com.cozmo.danar.util.BleCommandUtil; - public class DanaRS_Packet_Basal_Get_Basal_Rate extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Basal_Get_Basal_Rate() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_BASAL_RATE; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Requesting basal rates"); } } @@ -45,7 +45,7 @@ public class DanaRS_Packet_Basal_Get_Basal_Rate extends DanaRS_Packet { dataSize = 2; pump.pumpProfiles[pump.activeProfile][i] = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Max basal: " + pump.maxBasal + " U"); log.debug("Basal step: " + pump.basalStep + " U"); for (int index = 0; index < 24; index++) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.java index 8eadb8298d..8cc73ac3a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_Rate.java @@ -1,14 +1,15 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Basal_Get_Profile_Basal_Rate extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Get_Profile_Basal_Rate.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int profileNumber; @@ -21,7 +22,7 @@ public class DanaRS_Packet_Basal_Get_Profile_Basal_Rate extends DanaRS_Packet { public DanaRS_Packet_Basal_Get_Profile_Basal_Rate(int profileNumber) { this(); this.profileNumber = profileNumber; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Requesting basal rates for profile " + profileNumber); } } @@ -47,7 +48,7 @@ public class DanaRS_Packet_Basal_Get_Profile_Basal_Rate extends DanaRS_Packet { dataIndex += dataSize; dataSize = 2; } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { for (int index = 0; index < 24; index++) log.debug("Basal " + String.format("%02d", index) + "h: " + pump.pumpProfiles[profileNumber][index]); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.java index 39e230a29e..1beadfd705 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.java @@ -1,19 +1,20 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Basal_Get_Profile_Number extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Get_Profile_Number.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Basal_Get_Profile_Number() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Requesting active profile"); } } @@ -25,7 +26,7 @@ public class DanaRS_Packet_Basal_Get_Profile_Number extends DanaRS_Packet { int dataIndex = DATA_START; int dataSize = 1; pump.activeProfile = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Active profile: " + pump.activeProfile); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.java index dbf917874d..c6f434d1ba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.java @@ -2,22 +2,23 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; import android.support.annotation.NonNull; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Get_Temporary_Basal_State.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Basal_Get_Temporary_Basal_State() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__TEMPORARY_BASAL_STATE; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Requesting temporary basal status"); } } @@ -53,7 +54,7 @@ public class DanaRS_Packet_Basal_Get_Temporary_Basal_State extends DanaRS_Packet int tempBasalRemainingMin = (pump.tempBasalTotalSec - runningMin * 60) / 60; Date tempBasalStart = pump.isTempBasalInProgress ? getDateFromTempBasalSecAgo(runningMin * 60) : new Date(0); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Error code: " + error); log.debug("Is temp basal running: " + pump.isTempBasalInProgress); log.debug("Is APS temp basal running: " + isAPSTempBasalInProgress); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Basal_Rate.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Basal_Rate.java index a64da24bf3..19b53ba53c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Basal_Rate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Basal_Rate.java @@ -3,12 +3,12 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import com.cozmo.danar.util.BleCommandUtil; public class DanaRS_Packet_Basal_Set_Basal_Rate extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Basal_Rate.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private double[] profileBasalRate; @@ -20,7 +20,7 @@ public class DanaRS_Packet_Basal_Set_Basal_Rate extends DanaRS_Packet { public DanaRS_Packet_Basal_Set_Basal_Rate(double[] profileBasalRate) { this(); this.profileBasalRate = profileBasalRate; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Setting new basal rates"); } } @@ -39,7 +39,7 @@ public class DanaRS_Packet_Basal_Set_Basal_Rate extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.java index 538750a45b..e8a288a258 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.java @@ -1,19 +1,19 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__CANCEL_TEMPORARY_BASAL; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Canceling temp basal"); } } @@ -21,7 +21,7 @@ public class DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal extends DanaRS_Packe @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.java index 66d0e7b4bb..004e9d69b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Basal_Rate.java @@ -1,13 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Basal_Set_Profile_Basal_Rate extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Profile_Basal_Rate.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int profileNumber; // 0 - 4 private double[] profileBasalRate; @@ -21,7 +22,7 @@ public class DanaRS_Packet_Basal_Set_Profile_Basal_Rate extends DanaRS_Packet { this(); this.profileNumber = profileNumber; this.profileBasalRate = profileBasalRate; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Setting new basal rates for profile " + profileNumber); } } @@ -41,7 +42,7 @@ public class DanaRS_Packet_Basal_Set_Profile_Basal_Rate extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Number.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Number.java index 69f7eae8dd..613c3d6f8b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Number.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Profile_Number.java @@ -1,48 +1,49 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Basal_Set_Profile_Number extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Profile_Number.class); - private int profileNumber; + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + private int profileNumber; - public DanaRS_Packet_Basal_Set_Profile_Number() { + public DanaRS_Packet_Basal_Set_Profile_Number() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_PROFILE_NUMBER; } - public DanaRS_Packet_Basal_Set_Profile_Number(int profileNumber) { - this(); - this.profileNumber = profileNumber; - if (Config.logDanaMessageDetail) { - log.debug("Setting profile number " + profileNumber); - } - } - @Override - public byte[] getRequestParams() { - byte[] request = new byte[1]; - request[0] = (byte) (profileNumber & 0xff); - return request; - } + public DanaRS_Packet_Basal_Set_Profile_Number(int profileNumber) { + this(); + this.profileNumber = profileNumber; + if (L.isEnabled(L.PUMPCOMM)) { + log.debug("Setting profile number " + profileNumber); + } + } @Override - public void handleMessage(byte[] data) { - int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { - if (result == 0) - log.debug("Result OK"); - else - log.error("Result Error: " + result); - } - } + public byte[] getRequestParams() { + byte[] request = new byte[1]; + request[0] = (byte) (profileNumber & 0xff); + return request; + } - @Override - public String getFriendlyName() { - return "BASAL__SET_PROFILE_NUMBER"; - } + @Override + public void handleMessage(byte[] data) { + int result = intFromBuff(data, 0, 1); + if (L.isEnabled(L.PUMPCOMM)) { + if (result == 0) + log.debug("Result OK"); + else + log.error("Result Error: " + result); + } + } + + @Override + public String getFriendlyName() { + return "BASAL__SET_PROFILE_NUMBER"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_Off.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_Off.java index 4c78038162..2c4c46eb2e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_Off.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_Off.java @@ -1,18 +1,19 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Basal_Set_Suspend_Off extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Suspend_Off.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Basal_Set_Suspend_Off() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_OFF; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Turning off suspend"); } } @@ -20,7 +21,7 @@ public class DanaRS_Packet_Basal_Set_Suspend_Off extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_On.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_On.java index 75a2a5fada..25d55968a9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_On.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Suspend_On.java @@ -1,18 +1,19 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Basal_Set_Suspend_On extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Suspend_On.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Basal_Set_Suspend_On() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__SET_SUSPEND_ON; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Turning on suspend"); } } @@ -20,7 +21,7 @@ public class DanaRS_Packet_Basal_Set_Suspend_On extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.java index d2f68ff864..15de10f742 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Basal_Set_Temporary_Basal.java @@ -1,13 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Basal_Set_Temporary_Basal extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Basal_Set_Temporary_Basal.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int temporaryBasalRatio; private int temporaryBasalDuration; @@ -21,7 +22,7 @@ public class DanaRS_Packet_Basal_Set_Temporary_Basal extends DanaRS_Packet { this(); this.temporaryBasalRatio = temporaryBasalRatio; this.temporaryBasalDuration = temporaryBasalDuration; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Setting temporary basal of " + temporaryBasalRatio + "% for " + temporaryBasalDuration + " hours"); } } @@ -37,7 +38,7 @@ public class DanaRS_Packet_Basal_Set_Temporary_Basal extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.java index 69c2f75ba6..e2c5d5fae6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_Option.java @@ -1,24 +1,26 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Bolus_Option extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Bolus_Option.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Bolus_Option() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_OPTION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -108,7 +110,7 @@ public class DanaRS_Packet_Bolus_Get_Bolus_Option extends DanaRS_Packet { MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)); } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Extended bolus enabled: " + pump.isExtendedBolusEnabled); log.debug("Missed bolus config: " + pump.missedBolusConfig); log.debug("missedBolus01StartHour: " + missedBolus01StartHour); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.java index b8a86cc078..2a834806f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_CIR_CF_Array.java @@ -1,21 +1,22 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_CIR_CF_Array extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_CIR_CF_Array.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_CIR_CF_Array() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_CIR_CF_ARRAY; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -118,7 +119,7 @@ public class DanaRS_Packet_Bolus_Get_CIR_CF_Array extends DanaRS_Packet { pump.nightCF = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Language: " + language); log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL")); log.debug("Current pump morning CIR: " + pump.morningCIR); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.java index f5acedf3ba..67768df866 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Calculation_Information.java @@ -1,20 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Calculation_Information extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Calculation_Information.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Calculation_Information() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_CALCULATION_INFORMATION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -58,7 +59,7 @@ public class DanaRS_Packet_Bolus_Get_Calculation_Information extends DanaRS_Pack pump.currentTarget = pump.currentTarget / 100d; currentBG = currentBG / 100d; } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL")); log.debug("Current BG: " + currentBG); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.java index c581320c54..ba93dde999 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.java @@ -1,20 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_CARBOHYDRATE_CALCULATION_INFORMATION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -33,7 +34,7 @@ public class DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information extend dataSize = 2; pump.currentCIR = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); log.debug("Carbs: " + carbs); log.debug("Current CIR: " + pump.currentCIR); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.java index bd7a0b9ee6..230a9d2480 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.java @@ -1,18 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Dual_Bolus extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Dual_Bolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Dual_Bolus() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -39,7 +42,7 @@ public class DanaRS_Packet_Bolus_Get_Dual_Bolus extends DanaRS_Packet { dataSize = 1; double bolusIncrement = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); log.debug("Bolus step: " + pump.bolusStep + " U"); log.debug("Extended bolus running: " + pump.extendedBolusAbsoluteRate + " U/h"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.java index 682d9b14bb..695f21c0a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.java @@ -1,20 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Extended_Bolus extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Extended_Bolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Extended_Bolus() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -37,7 +38,7 @@ public class DanaRS_Packet_Bolus_Get_Extended_Bolus extends DanaRS_Packet { dataSize = 1; pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); log.debug("Extended bolus running: " + pump.extendedBolusAbsoluteRate + " U/h"); log.debug("Max bolus: " + pump.maxBolus + " U"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.java index b22a9dfb47..95c96ea322 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.java @@ -1,20 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Extended_Bolus_State extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Extended_Bolus_State.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Extended_Bolus_State() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -45,7 +46,7 @@ public class DanaRS_Packet_Bolus_Get_Extended_Bolus_State extends DanaRS_Packet dataSize = 2; pump.extendedBolusDeliveredSoFar = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); log.debug("Is extended bolus running: " + pump.isExtendedInProgress); log.debug("Extended bolus running: " + pump.extendedBolusAbsoluteRate + " U/h"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.java index 5a7ca55e30..fda8778d08 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.java @@ -1,20 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_MENU_OPTION_STATE; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -29,7 +30,7 @@ public class DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State extends DanaRS_P dataSize = 1; pump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("extendedMenuOption: " + extendedMenuOption); log.debug("Is extended bolus running: " + pump.isExtendedInProgress); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.java index 58fa4674ad..d52bd50ea1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Initial_Bolus.java @@ -1,17 +1,20 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Get_Initial_Bolus extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Initial_Bolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Initial_Bolus() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_BOLUS_RATE; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -31,7 +34,7 @@ public class DanaRS_Packet_Bolus_Get_Initial_Bolus extends DanaRS_Packet { dataIndex += dataSize; dataSize = 2; double initialBolusValue04 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Initial bolus amount 01: " + initialBolusValue01); log.debug("Initial bolus amount 02: " + initialBolusValue02); log.debug("Initial bolus amount 03: " + initialBolusValue03); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.java index 6166f7b0fb..ce38e0ba28 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.java @@ -1,20 +1,23 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Step_Bolus_Information.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Get_Step_Bolus_Information() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -54,7 +57,7 @@ public class DanaRS_Packet_Bolus_Get_Step_Bolus_Information extends DanaRS_Packe dataSize = 1; pump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); log.debug("BolusType: " + bolusType); log.debug("Initial bolus amount: " + pump.initialBolusAmount + " U"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.java index 103bac3ecf..4f53ba9632 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Bolus_Option.java @@ -1,13 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_Bolus_Option extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Bolus_Option.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int extendedBolusOptionOnOff; private int bolusCalculationOption; @@ -75,7 +76,7 @@ public class DanaRS_Packet_Bolus_Set_Bolus_Option extends DanaRS_Packet { this.missedBolus04EndHour = missedBolus04EndHour; this.missedBolus04EndMin = missedBolus04EndMin; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Setting bolus options"); } } @@ -112,7 +113,7 @@ public class DanaRS_Packet_Bolus_Set_Bolus_Option extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.java index 062ae00712..23581d4d0c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_CIR_CF_Array.java @@ -1,13 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_CIR_CF_Array extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_CIR_CF_Array.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int cir01; private int cir02; @@ -45,6 +46,8 @@ public class DanaRS_Packet_Bolus_Set_CIR_CF_Array extends DanaRS_Packet { this.cf05 = cf05; this.cf06 = cf06; this.cf07 = cf07; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -84,7 +87,7 @@ public class DanaRS_Packet_Bolus_Set_CIR_CF_Array extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.java index e769bea195..8953ce020e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Dual_Bolus.java @@ -1,13 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_Dual_Bolus extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Dual_Bolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private double amount; private double extendedAmount; @@ -24,7 +25,7 @@ public class DanaRS_Packet_Bolus_Set_Dual_Bolus extends DanaRS_Packet { this.extendedAmount = extendedAmount; this.extendedBolusDurationInHalfHours = extendedBolusDurationInHalfHours; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Dual bolus start : " + amount + " U extended: " + extendedAmount + " U halfhours: " + extendedBolusDurationInHalfHours); } @@ -45,7 +46,7 @@ public class DanaRS_Packet_Bolus_Set_Dual_Bolus extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.java index 887a9d852a..fb899b73d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.java @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_Extended_Bolus extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Extended_Bolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private double extendedAmount; private int extendedBolusDurationInHalfHours; @@ -23,7 +23,7 @@ public class DanaRS_Packet_Bolus_Set_Extended_Bolus extends DanaRS_Packet { this.extendedAmount = extendedAmount; this.extendedBolusDurationInHalfHours = extendedBolusDurationInHalfHours; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Extended bolus start : " + extendedAmount + " U halfhours: " + extendedBolusDurationInHalfHours); } @@ -41,7 +41,7 @@ public class DanaRS_Packet_Bolus_Set_Extended_Bolus extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.java index 132de649cf..ab887c0fab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.java @@ -1,26 +1,27 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS_CANCEL; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Cancel extended bolus"); } @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.java index a174d39b53..faaf505293 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Initial_Bolus.java @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_Initial_Bolus extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Initial_Bolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int bolusRate01; private int bolusRate02; @@ -26,6 +26,8 @@ public class DanaRS_Packet_Bolus_Set_Initial_Bolus extends DanaRS_Packet { this.bolusRate02 = (int) (bolusRate02 / 100d); this.bolusRate03 = (int) (bolusRate03 / 100d); this.bolusRate04 = (int) (bolusRate04 / 100d); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -45,7 +47,7 @@ public class DanaRS_Packet_Bolus_Set_Initial_Bolus extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java index 44e5d308dc..2d423eb7ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Start.java @@ -5,14 +5,12 @@ import com.cozmo.danar.util.BleCommandUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Step_Bolus_Start.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private double amount; private int speed; @@ -35,7 +33,7 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { this.amount = amount; this.speed = speed; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Bolus start : " + amount + " speed: " + speed); } @@ -52,7 +50,7 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Start extends DanaRS_Packet { @Override public void handleMessage(byte[] data) { errorCode = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (errorCode == 0) { log.debug("Result OK"); failed = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java index 78548ecab3..eef9afe0e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java @@ -3,17 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; public class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Treatment t; private static Double amount; @@ -31,12 +31,14 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop extends DanaRS_Packet { this.amount = amount; forced = false; stopped = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Stop bolus: amount: " + amount + " treatment: " + t.toString()); } @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Keep_Connection.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Keep_Connection.java index d30be3abf8..071ca66410 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Keep_Connection.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Keep_Connection.java @@ -3,16 +3,18 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import com.cozmo.danar.util.BleCommandUtil; public class DanaRS_Packet_Etc_Keep_Connection extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Etc_Keep_Connection.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Etc_Keep_Connection() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_ETC__KEEP_CONNECTION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -20,7 +22,7 @@ public class DanaRS_Packet_Etc_Keep_Connection extends DanaRS_Packet { int dataIndex = DATA_START; int dataSize = 1; int error = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Set_History_Save.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Set_History_Save.java index 6538b77932..a7ace37421 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Set_History_Save.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Etc_Set_History_Save.java @@ -3,12 +3,12 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import com.cozmo.danar.util.BleCommandUtil; public class DanaRS_Packet_Etc_Set_History_Save extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Etc_Set_History_Save.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int historyType; private int historyYear; @@ -36,6 +36,8 @@ public class DanaRS_Packet_Etc_Set_History_Save extends DanaRS_Packet { this.historySecond = historySecond; this.historyCode = historyCode; this.historyValue = historyValue; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -59,7 +61,7 @@ public class DanaRS_Packet_Etc_Set_History_Save extends DanaRS_Packet { int dataIndex = DATA_START; int dataSize = 1; int error = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Result: " + error); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Delivery_Status.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Delivery_Status.java index d9e2599eb2..f505f9c619 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Delivery_Status.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Delivery_Status.java @@ -1,18 +1,20 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_General_Delivery_Status extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Delivery_Status.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_General_Delivery_Status() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DELIVERY_STATUS; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -20,7 +22,7 @@ public class DanaRS_Packet_General_Delivery_Status extends DanaRS_Packet { int dataIndex = DATA_START; int dataSize = 1; int status = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Status: " + status); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_More_Information.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_More_Information.java index cd2de4094f..24bfc4b8a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_More_Information.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_More_Information.java @@ -1,45 +1,48 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import com.cozmo.danar.util.BleCommandUtil; public class DanaRS_Packet_General_Get_More_Information extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_More_Information.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_General_Get_More_Information() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION; - } + public DanaRS_Packet_General_Get_More_Information() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } - @Override - public void handleMessage(byte[] data) { - DanaRPump pump = DanaRPump.getInstance(); + @Override + public void handleMessage(byte[] data) { + DanaRPump pump = DanaRPump.getInstance(); - int dataIndex = DATA_START; - int dataSize = 2; - pump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + int dataIndex = DATA_START; + int dataSize = 2; + pump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 2; - pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; + dataIndex += dataSize; + dataSize = 2; + pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - dataIndex += dataSize; - dataSize = 1; - pump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01; + dataIndex += dataSize; + dataSize = 1; + pump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01; - dataIndex += dataSize; - dataSize = 2; - pump.extendedBolusRemainingMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 2; + pump.extendedBolusRemainingMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 2; - double remainRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; + dataIndex += dataSize; + dataSize = 2; + double remainRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; Date lastBolusTime = new Date(); // it doesn't provide day only hour+min, workaround: expecting today dataIndex += dataSize; @@ -50,21 +53,21 @@ public class DanaRS_Packet_General_Get_More_Information extends DanaRS_Packet { dataSize = 1; lastBolusTime.setMinutes(byteArrayToInt(getBytes(data, dataIndex, dataSize))); - dataIndex += dataSize; - dataSize = 2; - pump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 2; + pump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Daily total units: " + pump.dailyTotalUnits + " U"); log.debug("Is extended in progress: " + pump.isExtendedInProgress); log.debug("Extended bolus remaining minutes: " + pump.extendedBolusRemainingMinutes); log.debug("Last bolus time: " + lastBolusTime.toLocaleString()); log.debug("Last bolus amount: " + pump.lastBolusAmount); } - } + } - @Override - public String getFriendlyName() { - return "REVIEW__GET_MORE_INFORMATION"; - } + @Override + public String getFriendlyName() { + return "REVIEW__GET_MORE_INFORMATION"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Password.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Password.java index 0d250db919..276653ff0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Password.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Password.java @@ -1,20 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_General_Get_Password extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_Password.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_General_Get_Password() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_PASSWORD; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -24,7 +25,7 @@ public class DanaRS_Packet_General_Get_Password extends DanaRS_Packet { int pass = ((data[DATA_START + 1] & 0x000000FF) << 8) + (data[DATA_START + 0] & 0x000000FF); pass = pass ^ 3463; pump.rs_password = Integer.toHexString(pass); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Pump password: " + pump.rs_password); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Pump_Check.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Pump_Check.java index bdc5ab8d9b..618ea29ed0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Pump_Check.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Pump_Check.java @@ -5,19 +5,21 @@ import com.cozmo.danar.util.BleCommandUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_General_Get_Pump_Check extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_Pump_Check.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_General_Get_Pump_Check() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_PUMP_CHECK; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -36,7 +38,7 @@ public class DanaRS_Packet_General_Get_Pump_Check extends DanaRS_Packet { dataSize = 1; pump.productCode = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Model: " + String.format("%02X ", pump.model)); log.debug("Protocol: " + String.format("%02X ", pump.protocol)); log.debug("Product Code: " + String.format("%02X ", pump.productCode)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.java index 2cf9b1f124..fe7f9b40ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.java @@ -1,46 +1,48 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import com.cozmo.danar.util.BleCommandUtil; - public class DanaRS_Packet_General_Get_Shipping_Information extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_General_Get_Shipping_Information() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION; - } + public DanaRS_Packet_General_Get_Shipping_Information() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } - @Override - public void handleMessage(byte[] data) { - DanaRPump pump = DanaRPump.getInstance(); + @Override + public void handleMessage(byte[] data) { + DanaRPump pump = DanaRPump.getInstance(); - int dataIndex = DATA_START; - int dataSize = 10; - pump.serialNumber = stringFromBuff(data, dataIndex, dataSize); + int dataIndex = DATA_START; + int dataSize = 10; + pump.serialNumber = stringFromBuff(data, dataIndex, dataSize); - dataIndex += dataSize; - dataSize = 3; - pump.shippingDate = dateFromBuff(data, dataIndex); + dataIndex += dataSize; + dataSize = 3; + pump.shippingDate = dateFromBuff(data, dataIndex); - dataIndex += dataSize; - dataSize = 3; - pump.shippingCountry = asciiStringFromBuff(data, dataIndex, dataSize); + dataIndex += dataSize; + dataSize = 3; + pump.shippingCountry = asciiStringFromBuff(data, dataIndex, dataSize); - if (Config.logDanaMessageDetail) { - log.debug("Serial number: " + pump.serialNumber); - log.debug("Shipping date: " + pump.shippingDate); - log.debug("Shipping country: " + pump.shippingCountry); - } - } + if (L.isEnabled(L.PUMPCOMM)) { + log.debug("Serial number: " + pump.serialNumber); + log.debug("Shipping date: " + pump.shippingDate); + log.debug("Shipping country: " + pump.shippingCountry); + } + } - @Override - public String getFriendlyName() { - return "REVIEW__GET_SHIPPING_INFORMATION"; - } + @Override + public String getFriendlyName() { + return "REVIEW__GET_SHIPPING_INFORMATION"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.java index a40d572611..aa686aaa05 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.java @@ -1,47 +1,48 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_General_Get_Today_Delivery_Total extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_Today_Delivery_Total.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_General_Get_Today_Delivery_Total() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL; - } + public DanaRS_Packet_General_Get_Today_Delivery_Total() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } - @Override - public void handleMessage(byte[] data) { - DanaRPump pump = DanaRPump.getInstance(); + @Override + public void handleMessage(byte[] data) { + DanaRPump pump = DanaRPump.getInstance(); - int dataIndex = DATA_START; - int dataSize = 2; - pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; + int dataIndex = DATA_START; + int dataSize = 2; + pump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - dataIndex += dataSize; - dataSize = 2; - pump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; + dataIndex += dataSize; + dataSize = 2; + pump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - dataIndex += dataSize; - dataSize = 2; - pump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; + dataIndex += dataSize; + dataSize = 2; + pump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { - log.debug("Daily total: " + pump.dailyTotalUnits + " U"); - log.debug("Daily total bolus: " + pump.dailyTotalBolusUnits + " U"); - log.debug("Daily total basal: " + pump.dailyTotalBasalUnits + " U"); - } - } + if (L.isEnabled(L.PUMPCOMM)) { + log.debug("Daily total: " + pump.dailyTotalUnits + " U"); + log.debug("Daily total bolus: " + pump.dailyTotalBolusUnits + " U"); + log.debug("Daily total basal: " + pump.dailyTotalBasalUnits + " U"); + } + } - @Override - public String getFriendlyName() { - return "REVIEW__GET_TODAY_DELIVERY_TOTAL"; - } + @Override + public String getFriendlyName() { + return "REVIEW__GET_TODAY_DELIVERY_TOTAL"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.java index 695e3eace4..156c5acc4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Get_User_Time_Change_Flag.java @@ -1,17 +1,20 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_General_Get_User_Time_Change_Flag extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Get_User_Time_Change_Flag.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_General_Get_User_Time_Change_Flag() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_USER_TIME_CHANGE_FLAG; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -20,7 +23,7 @@ public class DanaRS_Packet_General_Get_User_Time_Change_Flag extends DanaRS_Pack int dataSize = 1; int userTimeChangeFlag = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("UserTimeChangeFlag: " + userTimeChangeFlag); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.java index d05777d20d..6b8f569c6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.java @@ -1,21 +1,22 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; - +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_General_Initial_Screen_Information extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Bolus_Get_Step_Bolus_Information.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_General_Initial_Screen_Information() { super(); type = BleCommandUtil.DANAR_PACKET__TYPE_RESPONSE; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -63,7 +64,7 @@ public class DanaRS_Packet_General_Initial_Screen_Information extends DanaRS_Pac dataSize = 2; pump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Pump suspended: " + pump.pumpSuspended); log.debug("Temp basal in progress: " + pump.isTempBasalInProgress); log.debug("Extended in progress: " + pump.isExtendedInProgress); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_History_Upload_Mode.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_History_Upload_Mode.java index 878cfd64dd..cd5a843336 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_History_Upload_Mode.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_History_Upload_Mode.java @@ -1,13 +1,14 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_General_Set_History_Upload_Mode extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Set_History_Upload_Mode.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int mode; @@ -19,6 +20,8 @@ public class DanaRS_Packet_General_Set_History_Upload_Mode extends DanaRS_Packet public DanaRS_Packet_General_Set_History_Upload_Mode(int mode) { this(); this.mode = mode; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: mode: " + mode); } @Override @@ -32,7 +35,7 @@ public class DanaRS_Packet_General_Set_History_Upload_Mode extends DanaRS_Packet @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.java index 3917f31050..07403d6908 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.java @@ -1,24 +1,26 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override public void handleMessage(byte[] data) { int result = intFromBuff(data, 0, 1); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (result == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_.java index 6bae4ab8c1..70fece9864 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import com.cozmo.danar.util.BleCommandUtil; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -11,12 +9,13 @@ import java.util.GregorianCalendar; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DanaRHistoryRecord; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.utils.DateUtil; public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_History_.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int year = 0; private int month = 0; @@ -47,7 +46,8 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { hour = cal.get(Calendar.HOUR_OF_DAY); min = cal.get(Calendar.MINUTE); sec = cal.get(Calendar.SECOND); - log.debug("Loading event history from: " + new Date(cal.getTimeInMillis()).toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Loading event history from: " + new Date(cal.getTimeInMillis()).toLocaleString()); } @Override @@ -71,7 +71,8 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { int dataSize = 1; error = byteArrayToInt(getBytes(data, dataIndex, dataSize)); done = true; - log.debug("History end. Code: " + error + " Success: " + (error == 0x00)); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("History end. Code: " + error + " Success: " + (error == 0x00)); } else if (data.length == 5) { int dataIndex = DATA_START; int dataSize = 1; @@ -81,11 +82,12 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { dataIndex += dataSize; dataSize = 2; totalCount = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - log.debug("History end. Code: " + error + " Success: " + (error == 0x00) + " Toatal count: " + totalCount); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("History end. Code: " + error + " Success: " + (error == 0x00) + " Toatal count: " + totalCount); } else { int recordCode = byteArrayToInt(getBytes(data, DATA_START, 1)); int historyYear = byteArrayToInt(getBytes(data, DATA_START + 1, 1)); - int historyMonth = byteArrayToInt(getBytes(data, DATA_START +2 , 1)); + int historyMonth = byteArrayToInt(getBytes(data, DATA_START + 2, 1)); int historyDay = byteArrayToInt(getBytes(data, DATA_START + 3, 1)); int historyHour = byteArrayToInt(getBytes(data, DATA_START + 4, 1)); double dailyBasal = (((data[DATA_START + 4] & 0xFF) << 8) + (data[DATA_START + 5] & 0xFF)) * 0.01d; @@ -103,7 +105,8 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { int value = ((data[DATA_START + 8] & 0xFF) << 8) + (data[DATA_START + 9] & 0xFF); - log.debug("History packet: " + recordCode + " Date: " + datetimewihtsec.toLocaleString() + " Code: " + historyCode + " Value: " + value); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("History packet: " + recordCode + " Date: " + datetimewihtsec.toLocaleString() + " Code: " + historyCode + " Value: " + value); EventDanaRSyncStatus ev = new EventDanaRSyncStatus(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Alarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Alarm.java index 5fe57fefe4..541091954f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Alarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Alarm.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Alarm extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Alarm() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Alarm extends DanaRS_Packet_History_ { public DanaRS_Packet_History_Alarm(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_All_History.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_All_History.java index a514d4eac7..1bf2bd302a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_All_History.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_All_History.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_All_History extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_All_History() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_All_History extends DanaRS_Packet_History_ { public DanaRS_Packet_History_All_History(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Basal.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Basal.java index 4aec1d0352..917e3956f4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Basal.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Basal.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Basal extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Basal() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Basal extends DanaRS_Packet_History_ { public DanaRS_Packet_History_Basal(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Blood_Glucose.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Blood_Glucose.java index 22bb3b5c2e..176d92b1fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Blood_Glucose.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Blood_Glucose.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Blood_Glucose extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Blood_Glucose() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Blood_Glucose extends DanaRS_Packet_History_ public DanaRS_Packet_History_Blood_Glucose(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Bolus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Bolus.java index 7451f921be..e1b8ac1010 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Bolus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Bolus.java @@ -1,23 +1,31 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Bolus extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_History_Bolus() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS; - } + public DanaRS_Packet_History_Bolus() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS; + } - public DanaRS_Packet_History_Bolus(Date from) { - super(from); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS; - } + public DanaRS_Packet_History_Bolus(Date from) { + super(from); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } - @Override - public String getFriendlyName() { - return "REVIEW__BOLUS"; - } + @Override + public String getFriendlyName() { + return "REVIEW__BOLUS"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Carbohydrate.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Carbohydrate.java index df2f5c762d..47a9b8fe11 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Carbohydrate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Carbohydrate.java @@ -1,23 +1,31 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Carbohydrate extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_History_Carbohydrate() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE; - } + public DanaRS_Packet_History_Carbohydrate() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE; + } - public DanaRS_Packet_History_Carbohydrate(Date from) { - super(from); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE; - } + public DanaRS_Packet_History_Carbohydrate(Date from) { + super(from); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } - @Override - public String getFriendlyName() { - return "REVIEW__CARBOHYDRATE"; - } + @Override + public String getFriendlyName() { + return "REVIEW__CARBOHYDRATE"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Daily.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Daily.java index b55754ba2f..12b7abc35b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Daily.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Daily.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Daily extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Daily() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Daily extends DanaRS_Packet_History_ { public DanaRS_Packet_History_Daily(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Prime.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Prime.java index b5dbf7ff93..6a5de90813 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Prime.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Prime.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Prime extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Prime() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Prime extends DanaRS_Packet_History_ { public DanaRS_Packet_History_Prime(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Refill.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Refill.java index 66094e3fb6..4566bb54b3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Refill.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Refill.java @@ -1,23 +1,31 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Refill extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_History_Refill() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL; - } + public DanaRS_Packet_History_Refill() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL; + } - public DanaRS_Packet_History_Refill(Date from) { - super(from); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL; - } + public DanaRS_Packet_History_Refill(Date from) { + super(from); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); + } - @Override - public String getFriendlyName() { - return "REVIEW__REFILL"; - } + @Override + public String getFriendlyName() { + return "REVIEW__REFILL"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Suspend.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Suspend.java index 20f1c3d6ff..5d83f48a65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Suspend.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Suspend.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Suspend extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Suspend() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Suspend extends DanaRS_Packet_History_ { public DanaRS_Packet_History_Suspend(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Temporary.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Temporary.java index 7d63e1bfff..ce362574eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Temporary.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_History_Temporary.java @@ -1,10 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; -import java.util.Date; - import com.cozmo.danar.util.BleCommandUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Date; + +import info.nightscout.androidaps.logging.L; + public class DanaRS_Packet_History_Temporary extends DanaRS_Packet_History_ { + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_History_Temporary() { super(); @@ -14,6 +20,8 @@ public class DanaRS_Packet_History_Temporary extends DanaRS_Packet_History_ { public DanaRS_Packet_History_Temporary(Date from) { super(from); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Alarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Alarm.java index 04737f0bdc..58f362f1ad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Alarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Alarm.java @@ -1,18 +1,17 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; - -import com.cozmo.danar.util.BleCommandUtil; - -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; public class DanaRS_Packet_Notify_Alarm extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Alarm.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int alarmCode; @@ -20,6 +19,8 @@ public class DanaRS_Packet_Notify_Alarm extends DanaRS_Packet { super(); type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__ALARM; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -76,7 +77,7 @@ public class DanaRS_Packet_Notify_Alarm extends DanaRS_Packet { break; } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Error detected: " + errorString); NSUpload.uploadError(errorString); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java index 2598c5efc9..836a52cb65 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java @@ -1,19 +1,18 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; - -import com.cozmo.danar.util.BleCommandUtil; - -import info.nightscout.androidaps.plugins.Treatments.Treatment; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; +import info.nightscout.androidaps.plugins.Treatments.Treatment; public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Delivery_Complete.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Treatment t; private static double amount; @@ -30,6 +29,8 @@ public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet { this.amount = amount; this.t = t; done = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: amount: " + amount + " treatment: " + t.toString()); } @Override @@ -46,7 +47,7 @@ public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet { MainApp.bus().post(bolusingEvent); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Delivered insulin: " + deliveredInsulin); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java index 34621d07ee..30d7eeaf46 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java @@ -1,17 +1,18 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import com.cozmo.danar.util.BleCommandUtil; -import info.nightscout.androidaps.plugins.Treatments.Treatment; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; +import info.nightscout.androidaps.plugins.Treatments.Treatment; public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Delivery_Rate_Display.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private static Treatment t; private static double amount; @@ -29,6 +30,8 @@ public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet { this.amount = amount; this.t = t; lastReceive = System.currentTimeMillis(); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: amount: " + amount + " treatment: " + t.toString()); } @Override @@ -45,7 +48,7 @@ public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet { MainApp.bus().post(bolusingEvent); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Delivered insulin so far: " + deliveredInsulin); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.java index 3af0c209b5..7110d8425c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Missed_Bolus_Alarm.java @@ -1,19 +1,21 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Notify_Missed_Bolus_Alarm extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Missed_Bolus_Alarm.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Notify_Missed_Bolus_Alarm() { super(); type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__MISSED_BOLUS_ALARM; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -38,7 +40,7 @@ public class DanaRS_Packet_Notify_Missed_Bolus_Alarm extends DanaRS_Packet { dataIndex += dataSize; dataSize = 1; endMin = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Start hour: " + startHour); log.debug("Start min: " + startMin); log.debug("End hour: " + endHour); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.java index 4bfebb5211..aacf859ef3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.java @@ -1,21 +1,22 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Option_Get_Pump_Time extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Get_Pump_Time.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Option_Get_Pump_Time() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__GET_PUMP_TIME; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Requesting pump time"); } } @@ -49,7 +50,7 @@ public class DanaRS_Packet_Option_Get_Pump_Time extends DanaRS_Packet { Date time = new Date(100 + year, month - 1, day, hour, min, sec); DanaRPump.getInstance().pumpTime = time; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Pump time " + time.toLocaleString()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_User_Option.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_User_Option.java index b4df373f9c..4873775e86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_User_Option.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Get_User_Option.java @@ -1,114 +1,115 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; -import com.cozmo.danar.util.BleCommandUtil; public class DanaRS_Packet_Option_Get_User_Option extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Get_User_Option.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); - public DanaRS_Packet_Option_Get_User_Option() { - super(); - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION; - if (Config.logDanaMessageDetail) { - log.debug("Requesting user settings"); - } - } + public DanaRS_Packet_Option_Get_User_Option() { + super(); + opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__GET_USER_OPTION; + if (L.isEnabled(L.PUMPCOMM)) { + log.debug("Requesting user settings"); + } + } - @Override - public void handleMessage(byte[] data) { - DanaRPump pump = DanaRPump.getInstance(); + @Override + public void handleMessage(byte[] data) { + DanaRPump pump = DanaRPump.getInstance(); - int dataIndex = DATA_START; - int dataSize = 1; - pump.timeDisplayType = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + int dataIndex = DATA_START; + int dataSize = 1; + pump.timeDisplayType = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.buttonScrollOnOff = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.buttonScrollOnOff = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.beepAndAlarm = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.beepAndAlarm = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.lcdOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.lcdOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.backlightOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.backlightOnTimeSec = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.selectedLanguage = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.selectedLanguage = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.units = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.shutdownHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.shutdownHour = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - pump.lowReservoirRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + pump.lowReservoirRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 2; - pump.cannulaVolume = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 2; + pump.cannulaVolume = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 2; - pump.refillAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 2; + pump.refillAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - int selectableLanguage1 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + int selectableLanguage1 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - int selectableLanguage2 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + int selectableLanguage2 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - int selectableLanguage3 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + int selectableLanguage3 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - int selectableLanguage4 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + int selectableLanguage4 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - dataIndex += dataSize; - dataSize = 1; - int selectableLanguage5 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); + dataIndex += dataSize; + dataSize = 1; + int selectableLanguage5 = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { - log.debug("timeDisplayType: " + pump.timeDisplayType); - log.debug("buttonScrollOnOff: " + pump.buttonScrollOnOff); - log.debug("beepAndAlarm: " + pump.beepAndAlarm); - log.debug("lcdOnTimeSec: " + pump.lcdOnTimeSec); - log.debug("backlightOnTimeSec: " + pump.backlightOnTimeSec); - log.debug("selectedLanguage: " + pump.selectedLanguage); - log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL")); - log.debug("shutdownHour: " + pump.shutdownHour); - log.debug("lowReservoirRate: " + pump.lowReservoirRate); - log.debug("refillAmount: " + pump.refillAmount); - log.debug("selectableLanguage1: " + selectableLanguage1); - log.debug("selectableLanguage2: " + selectableLanguage2); - log.debug("selectableLanguage3: " + selectableLanguage3); - log.debug("selectableLanguage4: " + selectableLanguage4); - log.debug("selectableLanguage5: " + selectableLanguage5); - } - } + if (L.isEnabled(L.PUMPCOMM)) { + log.debug("timeDisplayType: " + pump.timeDisplayType); + log.debug("buttonScrollOnOff: " + pump.buttonScrollOnOff); + log.debug("beepAndAlarm: " + pump.beepAndAlarm); + log.debug("lcdOnTimeSec: " + pump.lcdOnTimeSec); + log.debug("backlightOnTimeSec: " + pump.backlightOnTimeSec); + log.debug("selectedLanguage: " + pump.selectedLanguage); + log.debug("Pump units: " + (pump.units == DanaRPump.UNITS_MGDL ? "MGDL" : "MMOL")); + log.debug("shutdownHour: " + pump.shutdownHour); + log.debug("lowReservoirRate: " + pump.lowReservoirRate); + log.debug("refillAmount: " + pump.refillAmount); + log.debug("selectableLanguage1: " + selectableLanguage1); + log.debug("selectableLanguage2: " + selectableLanguage2); + log.debug("selectableLanguage3: " + selectableLanguage3); + log.debug("selectableLanguage4: " + selectableLanguage4); + log.debug("selectableLanguage5: " + selectableLanguage5); + } + } - @Override - public String getFriendlyName() { - return "OPTION__GET_USER_OPTION"; - } + @Override + public String getFriendlyName() { + return "OPTION__GET_USER_OPTION"; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.java index 007623afca..5f92036ef1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.java @@ -1,16 +1,16 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Option_Set_Pump_Time extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Set_Pump_Time.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private Date date; public int error; @@ -22,7 +22,7 @@ public class DanaRS_Packet_Option_Set_Pump_Time extends DanaRS_Packet { public DanaRS_Packet_Option_Set_Pump_Time(Date date) { this(); this.date = date; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Setting pump time " + date.toLocaleString()); } } @@ -44,7 +44,7 @@ public class DanaRS_Packet_Option_Set_Pump_Time extends DanaRS_Packet { int dataIndex = DATA_START; int dataSize = 1; error = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (error == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_User_Option.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_User_Option.java index 40577aaa5d..3e11aa93fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_User_Option.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Option_Set_User_Option.java @@ -1,21 +1,22 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; public class DanaRS_Packet_Option_Set_User_Option extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Option_Set_User_Option.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private int error; public DanaRS_Packet_Option_Set_User_Option() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Setting user settings"); } } @@ -23,14 +24,15 @@ public class DanaRS_Packet_Option_Set_User_Option extends DanaRS_Packet { @Override public byte[] getRequestParams() { DanaRPump pump = DanaRPump.getInstance(); - log.debug("UserOptions:"+(System.currentTimeMillis() - pump.lastConnection)/1000+" s ago" - +"\ntimeDisplayType:"+pump.timeDisplayType - +"\nbuttonScroll:"+pump.buttonScrollOnOff - +"\ntimeDisplayType:"+pump.timeDisplayType - +"\nlcdOnTimeSec:"+pump.lcdOnTimeSec - +"\nbacklight:"+pump.backlightOnTimeSec - +"\npumpUnits:"+pump.units - +"\nlowReservoir:"+pump.lowReservoirRate); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("UserOptions:" + (System.currentTimeMillis() - pump.lastConnection) / 1000 + " s ago" + + "\ntimeDisplayType:" + pump.timeDisplayType + + "\nbuttonScroll:" + pump.buttonScrollOnOff + + "\ntimeDisplayType:" + pump.timeDisplayType + + "\nlcdOnTimeSec:" + pump.lcdOnTimeSec + + "\nbacklight:" + pump.backlightOnTimeSec + + "\npumpUnits:" + pump.units + + "\nlowReservoir:" + pump.lowReservoirRate); byte[] request = new byte[13]; request[0] = (byte) (pump.timeDisplayType & 0xff); request[1] = (byte) (pump.buttonScrollOnOff & 0xff); @@ -53,7 +55,7 @@ public class DanaRS_Packet_Option_Set_User_Option extends DanaRS_Packet { int dataIndex = DATA_START; int dataSize = 1; error = byteArrayToInt(getBytes(data, dataIndex, dataSize)); - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { if (error == 0) log.debug("Result OK"); else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Review_Bolus_Avg.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Review_Bolus_Avg.java index e8440b12d2..6c43908309 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Review_Bolus_Avg.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Review_Bolus_Avg.java @@ -1,18 +1,20 @@ package info.nightscout.androidaps.plugins.PumpDanaRS.comm; +import com.cozmo.danar.util.BleCommandUtil; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; - -import com.cozmo.danar.util.BleCommandUtil; +import info.nightscout.androidaps.logging.L; public class DanaRS_Packet_Review_Bolus_Avg extends DanaRS_Packet { - private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Review_Bolus_Avg.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public DanaRS_Packet_Review_Bolus_Avg() { super(); opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS_AVG; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -36,7 +38,7 @@ public class DanaRS_Packet_Review_Bolus_Avg extends DanaRS_Packet { dataIndex += dataSize; dataSize = 2; double bolusAvg28 = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100d; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Bolus average 3d: " + bolusAvg03 + " U"); log.debug("Bolus average 7d: " + bolusAvg07 + " U"); log.debug("Bolus average 14d: " + bolusAvg14 + " U"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java index 9df2ebc0a1..be241dbbfd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/BLEComm.java @@ -25,6 +25,7 @@ import java.util.concurrent.ScheduledFuture; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventPumpStatusChanged; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; @@ -34,7 +35,7 @@ import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRSMessageHashTable import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet; import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSPacket; import info.nightscout.androidaps.plugins.PumpDanaRS.events.EventDanaRSPairingSuccess; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; /** @@ -42,12 +43,12 @@ import info.nightscout.utils.SP; */ public class BLEComm { - private static Logger log = LoggerFactory.getLogger(BLEComm.class); + private Logger log = LoggerFactory.getLogger(L.PUMPBTCOMM); - private static final long WRITE_DELAY_MILLIS = 50; + private final long WRITE_DELAY_MILLIS = 50; - private static String UART_READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb"; - private static String UART_WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb"; + private String UART_READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb"; + private String UART_WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb"; private final byte PACKET_START_BYTE = (byte) 0xA5; private final byte PACKET_END_BYTE = (byte) 0x5A; @@ -83,19 +84,20 @@ public class BLEComm { } private boolean initialize() { - log.debug("Initializing BLEComm."); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Initializing BLEComm."); if (mBluetoothManager == null) { mBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)); if (mBluetoothManager == null) { - log.debug("Unable to initialize BluetoothManager."); + log.error("Unable to initialize BluetoothManager."); return false; } } mBluetoothAdapter = mBluetoothManager.getAdapter(); if (mBluetoothAdapter == null) { - log.debug("Unable to obtain a BluetoothAdapter."); + log.error("Unable to obtain a BluetoothAdapter."); return false; } @@ -128,7 +130,7 @@ public class BLEComm { } if (address == null) { - log.debug("unspecified address."); + log.error("unspecified address."); return false; } @@ -136,11 +138,12 @@ public class BLEComm { BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); if (device == null) { - log.debug("Device not found. Unable to connect from: " + from); + log.error("Device not found. Unable to connect from: " + from); return false; } - log.debug("Trying to create a new connection from: " + from); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Trying to create a new connection from: " + from); mBluetoothGatt = device.connectGatt(service.getApplicationContext(), false, mGattCallback); setCharacteristicNotification(getUARTReadBTGattChar(), true); mBluetoothDeviceName = device.getName(); @@ -151,8 +154,9 @@ public class BLEComm { isConnecting = false; } - public void disconnect(String from) { - log.debug("disconnect from: " + from); + public synchronized void disconnect(String from) { + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("disconnect from: " + from); // cancel previous scheduled disconnection to prevent closing upcomming connection if (scheduledDisconnection != null) @@ -160,8 +164,8 @@ public class BLEComm { scheduledDisconnection = null; if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.debug("disconnect not possible: (mBluetoothAdapter == null) " + (mBluetoothAdapter == null)); - log.debug("disconnect not possible: (mBluetoothGatt == null) " + (mBluetoothGatt == null)); + log.error("disconnect not possible: (mBluetoothAdapter == null) " + (mBluetoothAdapter == null)); + log.error("disconnect not possible: (mBluetoothGatt == null) " + (mBluetoothGatt == null)); return; } setCharacteristicNotification(getUARTReadBTGattChar(), false); @@ -171,7 +175,8 @@ public class BLEComm { } public synchronized void close() { - log.debug("BluetoothAdapter close"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("BluetoothAdapter close"); if (mBluetoothGatt == null) { return; } @@ -187,21 +192,12 @@ public class BLEComm { private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - log.debug("onConnectionStateChange"); - - if (newState == BluetoothProfile.STATE_CONNECTED) { - mBluetoothGatt.discoverServices(); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - close(); - isConnected = false; - isConnecting = false; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); - log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected - } + onConnectionStateChangeSynchronized(gatt, status, newState); // call it synchronized } public void onServicesDiscovered(BluetoothGatt gatt, int status) { - log.debug("onServicesDiscovered"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("onServicesDiscovered"); if (status == BluetoothGatt.GATT_SUCCESS) { findCharacteristic(); } @@ -210,19 +206,22 @@ public class BLEComm { } public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - log.debug("onCharacteristicRead" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("onCharacteristicRead" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); addToReadBuffer(characteristic.getValue()); readDataParsing(); } public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { - log.debug("onCharacteristicChanged" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("onCharacteristicChanged" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); addToReadBuffer(characteristic.getValue()); new Thread(() -> readDataParsing()).start(); } public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); new Thread(() -> { synchronized (mSendQueue) { // after message sent, check if there is the rest of the message waiting and send it @@ -237,9 +236,10 @@ public class BLEComm { }; private synchronized void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { - log.debug("setCharacteristicNotification"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("setCharacteristicNotification"); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.debug("BluetoothAdapter not initialized_ERROR"); + log.error("BluetoothAdapter not initialized_ERROR"); isConnecting = false; isConnected = false; return; @@ -248,9 +248,10 @@ public class BLEComm { } public synchronized void readCharacteristic(BluetoothGattCharacteristic characteristic) { - log.debug("readCharacteristic"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("readCharacteristic"); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.debug("BluetoothAdapter not initialized_ERROR"); + log.error("BluetoothAdapter not initialized_ERROR"); isConnecting = false; isConnected = false; return; @@ -263,7 +264,7 @@ public class BLEComm { SystemClock.sleep(WRITE_DELAY_MILLIS); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.debug("BluetoothAdapter not initialized_ERROR"); + log.error("BluetoothAdapter not initialized_ERROR"); isConnecting = false; isConnected = false; return; @@ -271,7 +272,8 @@ public class BLEComm { characteristic.setValue(data); characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); - log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data)); mBluetoothGatt.writeCharacteristic(characteristic); }).start(); } @@ -291,9 +293,10 @@ public class BLEComm { } private List getSupportedGattServices() { - log.debug("getSupportedGattServices"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("getSupportedGattServices"); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.debug("BluetoothAdapter not initialized_ERROR"); + log.error("BluetoothAdapter not initialized_ERROR"); isConnecting = false; isConnected = false; return null; @@ -325,6 +328,22 @@ public class BLEComm { } } + private synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) { + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("onConnectionStateChange"); + + if (newState == BluetoothProfile.STATE_CONNECTED) { + mBluetoothGatt.discoverServices(); + } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + close(); + isConnected = false; + isConnecting = false; + MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected + } + } + private final byte[] readBuffer = new byte[1024]; private int bufferLength = 0; @@ -356,7 +375,8 @@ public class BLEComm { if ((readBuffer[idxStartByte] == PACKET_START_BYTE) && (readBuffer[idxStartByte + 1] == PACKET_START_BYTE)) { if (idxStartByte > 0) { // if buffer doesn't start with signature remove the leading trash - log.debug("Shifting the input buffer by " + idxStartByte + " bytes"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Shifting the input buffer by " + idxStartByte + " bytes"); System.arraycopy(readBuffer, idxStartByte, readBuffer, 0, bufferLength - idxStartByte); bufferLength -= idxStartByte; } @@ -386,7 +406,7 @@ public class BLEComm { try { System.arraycopy(readBuffer, length + 7, readBuffer, 0, bufferLength - (length + 7)); } catch (Exception e) { - log.debug("length: " + length + "bufferLength: " + bufferLength); + log.error("length: " + length + "bufferLength: " + bufferLength); throw e; } bufferLength -= (length + 7); @@ -399,7 +419,7 @@ public class BLEComm { inputBuffer = BleCommandUtil.getInstance().getDecryptedPacket(inputBuffer); if (inputBuffer == null) { - log.debug("Null decryptedInputBuffer"); + log.error("Null decryptedInputBuffer"); return; } @@ -410,14 +430,17 @@ public class BLEComm { // 1st packet case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK: if (inputBuffer.length == 4 && inputBuffer[2] == 'O' && inputBuffer[3] == 'K') { - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(inputBuffer)); // Grab pairing key from preferences if exists String pairingKey = SP.getString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, null); - log.debug("Using stored pairing key: " + pairingKey); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Using stored pairing key: " + pairingKey); if (pairingKey != null) { byte[] encodedPairingKey = DanaRS_Packet.hexToBytes(pairingKey); byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY, encodedPairingKey, null); - log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes)); writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); } else { // Stored pairing key does not exists, request pairing @@ -425,19 +448,22 @@ public class BLEComm { } } else if (inputBuffer.length == 6 && inputBuffer[2] == 'P' && inputBuffer[3] == 'U' && inputBuffer[4] == 'M' && inputBuffer[5] == 'P') { - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer)); mSendQueue.clear(); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumperror))); NSUpload.uploadError(MainApp.gs(R.string.pumperror)); Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT); MainApp.bus().post(new EventNewNotification(n)); } else if (inputBuffer.length == 6 && inputBuffer[2] == 'B' && inputBuffer[3] == 'U' && inputBuffer[4] == 'S' && inputBuffer[5] == 'Y') { - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer)); mSendQueue.clear(); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumpbusy))); } else { // ERROR in response, wrong serial number - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer)); mSendQueue.clear(); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.connectionerror))); SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName); @@ -447,7 +473,8 @@ public class BLEComm { break; // 2nd packet, pairing key case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY: - log.debug("<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(inputBuffer)); if (inputBuffer[2] == (byte) 0x00) { // Paring is not requested, sending time info SendTimeInfo(); @@ -457,35 +484,41 @@ public class BLEComm { } break; case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST: - log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer)); if (inputBuffer[2] != (byte) 0x00) { disconnect("passkey request failed"); } break; // Paring response, OK button on pump pressed case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN: - log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer)); // Paring is successfull, sending time info MainApp.bus().post(new EventDanaRSPairingSuccess()); SendTimeInfo(); byte[] pairingKey = {inputBuffer[2], inputBuffer[3]}; // store pairing key to preferences SP.putString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, DanaRS_Packet.bytesToHex(pairingKey)); - log.debug("Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey)); break; // time and user password information. last packet in handshake case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION: - log.debug("<<<<< " + "ENCRYPTION__TIME_INFORMATION " + /*message.getMessageName() + " " + */ DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + "ENCRYPTION__TIME_INFORMATION " + /*message.getMessageName() + " " + */ DanaRS_Packet.toHexString(inputBuffer)); int size = inputBuffer.length; int pass = ((inputBuffer[size - 1] & 0x000000FF) << 8) + ((inputBuffer[size - 2] & 0x000000FF)); pass = pass ^ 3463; DanaRPump.getInstance().rs_password = Integer.toHexString(pass); - log.debug("Pump user password: " + Integer.toHexString(pass)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Pump user password: " + Integer.toHexString(pass)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED)); isConnected = true; isConnecting = false; - log.debug("RS connected and status read"); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("RS connected and status read"); break; } break; @@ -503,7 +536,8 @@ public class BLEComm { message = DanaRSMessageHashTable.findMessage(receivedCommand); } if (message != null) { - log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer)); // process received data message.handleMessage(inputBuffer); message.setReceived(); @@ -540,7 +574,8 @@ public class BLEComm { byte[] command = {(byte) message.getType(), (byte) message.getOpCode()}; byte[] params = message.getRequestParams(); - log.debug(">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)); byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(message.getOpCode(), params, null); // If there is another message not completely sent, add to queue only if (mSendQueue.size() > 0) { @@ -620,20 +655,23 @@ public class BLEComm { MainApp.instance().startActivity(i); byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null); - log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes)); writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); } private void SendPumpCheck() { // 1st message sent to pump after connect byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, getConnectDeviceName()); - log.debug(">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes)); writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); } private void SendTimeInfo() { byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, null, null); - log.debug(">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes)); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes)); writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java index fae0430adc..932c9c747e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/services/DanaRSService.java @@ -13,7 +13,6 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -24,7 +23,9 @@ import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; 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.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; @@ -78,12 +79,12 @@ import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.T; public class DanaRSService extends Service { - private static Logger log = LoggerFactory.getLogger(DanaRSService.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); private BLEComm bleComm = BLEComm.getInstance(this); @@ -142,7 +143,7 @@ public class DanaRSService extends Service { danaRPump.lastConnection = System.currentTimeMillis(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); @@ -156,10 +157,12 @@ public class DanaRSService extends Service { bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time()); long timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 3) { - if (Math.abs(timeDiff) > 60*60*1.5) { - log.debug("Pump time difference: " + timeDiff + " seconds - large difference"); + if (Math.abs(timeDiff) > 60 * 60 * 1.5) { + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Pump time difference: " + timeDiff + " seconds - large difference"); //If time-diff is very large, warn user until we can synchronize history readings properly Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); i.putExtra("soundid", R.raw.error); @@ -179,7 +182,8 @@ public class DanaRSService extends Service { bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(new Date(DateUtil.now() + T.secs(10).msecs()))); bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time()); timeDiff = (danaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Pump time difference: " + timeDiff + " seconds"); } } @@ -203,8 +207,9 @@ public class DanaRSService extends Service { MainApp.bus().post(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { - log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); - if(System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Approaching daily limit: " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits); + if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + danaRPump.dailyTotalUnits + "/" + danaRPump.maxDailyTotalUnits + "U"); @@ -214,12 +219,13 @@ public class DanaRSService extends Service { } catch (Exception e) { log.error("Unhandled exception", e); } - log.debug("Pump status loaded"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Pump status loaded"); } public PumpEnactResult loadEvents() { - if(!MainApp.getSpecificPlugin(DanaRSPlugin.class).isInitialized()){ + if (!MainApp.getSpecificPlugin(DanaRSPlugin.class).isInitialized()) { PumpEnactResult result = new PumpEnactResult().success(false); result.comment = "pump not initialized"; return result; @@ -230,10 +236,12 @@ public class DanaRSService extends Service { DanaRS_Packet_APS_History_Events msg; if (lastHistoryFetched == 0) { msg = new DanaRS_Packet_APS_History_Events(0); - log.debug("Loading complete event history"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Loading complete event history"); } else { msg = new DanaRS_Packet_APS_History_Events(lastHistoryFetched); - log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString()); } bleComm.sendMessage(msg); while (!msg.done && bleComm.isConnected()) { @@ -243,7 +251,8 @@ public class DanaRSService extends Service { lastHistoryFetched = DanaRS_Packet_APS_History_Events.lastEventTimeLoaded - T.mins(1).msecs(); else lastHistoryFetched = 0; - log.debug("Events loaded"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Events loaded"); danaRPump.lastConnection = System.currentTimeMillis(); return new PumpEnactResult().success(true); } @@ -290,7 +299,8 @@ public class DanaRSService extends Service { if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm stop.stopped = true; stop.forced = true; - log.debug("Communication stopped"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Communication stopped"); } } } @@ -335,7 +345,7 @@ public class DanaRSService extends Service { } public void bolusStop() { - if (Config.logDanaBTComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin)); DanaRS_Packet_Bolus_Set_Step_Bolus_Stop stop = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(); stop.forced = true; @@ -433,7 +443,7 @@ public class DanaRSService extends Service { public boolean updateBasalsInPump(Profile profile) { if (!isConnected()) return false; MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); - double[] basal = DanaRPump.buildDanaRProfileRecord(profile); + double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(0, basal); bleComm.sendMessage(msgSet); DanaRS_Packet_Basal_Set_Profile_Number msgActivate = new DanaRS_Packet_Basal_Set_Profile_Number(0); @@ -512,11 +522,11 @@ public class DanaRSService extends Service { @Subscribe public void onStatusEvent(EventAppExit event) { - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received"); stopSelf(); - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit finished"); } @@ -526,7 +536,7 @@ public class DanaRSService extends Service { long timeToWholeMinute = (60000 - time % 60000); if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int)(timeToWholeMinute / 1000)))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); SystemClock.sleep(Math.min(timeToWholeMinute, 100)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java index e83f9d9435..1f1dc90eb1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/DanaRv2Plugin.java @@ -11,9 +11,6 @@ import android.support.v7.app.AlertDialog; import com.squareup.otto.Subscribe; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -23,6 +20,7 @@ import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpDescription; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.PumpDanaR.AbstractDanaRPlugin; @@ -51,7 +49,6 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { private DanaRv2Plugin() { pluginDescription.description(R.string.description_pump_dana_r_v2); - log = LoggerFactory.getLogger(DanaRv2Plugin.class); useExtendedBoluses = false; pumpDescription.isBolusCapable = true; @@ -107,12 +104,14 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { - log.debug("Service is disconnected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is disconnected"); sExecutionService = null; } public void onServiceConnected(ComponentName name, IBinder service) { - log.debug("Service is connected"); + if (L.isEnabled(L.PUMP)) + log.debug("Service is connected"); DanaRv2ExecutionService.LocalBinder mLocalBinder = (DanaRv2ExecutionService.LocalBinder) service; sExecutionService = mLocalBinder.getServiceInstance(); } @@ -157,13 +156,15 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.invoke(); SP.putBoolean("allow_hardware_pump", true); - log.debug("First time HW pump allowed!"); + if (L.isEnabled(L.PUMP)) + log.debug("First time HW pump allowed!"); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { pluginSwitcher.cancel(); - log.debug("User does not allow switching to HW pump!"); + if (L.isEnabled(L.PUMP)) + log.debug("User does not allow switching to HW pump!"); } }); builder.create().show(); @@ -214,7 +215,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStartWithSpeed.errorCode); else result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); // remove carbs because it's get from history seprately return result; @@ -258,7 +259,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { if (doTempOff) { // If temp in progress if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) { - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)"); return cancelTempBasal(false); } @@ -267,7 +268,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.percent = 100; result.isPercent = true; result.isTempCancel = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: doTempOff OK"); return result; } @@ -290,14 +291,14 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.duration = activeTemp.getPlannedRemainingMinutes(); result.isPercent = true; result.isTempCancel = false; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); return result; } } } // Convert duration from minutes to hours - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); if (percentRate == 0 && durationInMinutes > 30) { result = setTempBasalPercent(percentRate, durationInMinutes, profile, false); @@ -309,7 +310,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { log.error("setTempBasalAbsolute: Failed to set hightemp basal"); return result; } - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalAbsolute: hightemp basal set ok"); return result; } @@ -344,7 +345,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent: Correct value already set"); return result; } @@ -363,7 +364,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setTempBasalPercent: OK"); return result; } @@ -385,7 +386,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.duration = pump.tempBasalRemainingMin; result.percent = pump.tempBasalPercent; result.isPercent = true; - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("setHighTempBasalPercent: OK"); return result; } @@ -409,7 +410,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { result.success = true; result.isTempCancel = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpActions) + if (L.isEnabled(L.PUMP)) log.debug("cancelRealTempBasal: OK"); return result; } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java index a12e2085aa..61047a8d5a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java @@ -10,7 +10,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread; @@ -21,7 +21,7 @@ import info.nightscout.utils.CRC; * Created by mike on 17.07.2016. */ public class SerialIOThread extends AbstractSerialIOThread { - private static Logger log = LoggerFactory.getLogger(SerialIOThread.class); + private static Logger log = LoggerFactory.getLogger(L.PUMPBTCOMM); private InputStream mInputStream = null; private OutputStream mOutputStream = null; @@ -72,7 +72,7 @@ public class SerialIOThread extends AbstractSerialIOThread { message = MessageHashTable_v2.findMessage(command); } - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff)); // process the message content @@ -84,7 +84,7 @@ public class SerialIOThread extends AbstractSerialIOThread { } } } catch (Exception e) { - if (Config.logDanaSerialEngine && e.getMessage().indexOf("bt socket closed") < 0) + if (e.getMessage().indexOf("bt socket closed") < 0) log.error("Thread exception: ", e); mKeepRunning = false; } @@ -148,7 +148,7 @@ public class SerialIOThread extends AbstractSerialIOThread { processedMessage = message; byte[] messageBytes = message.getRawMessageBytes(); - if (Config.logDanaSerialEngine) + if (L.isEnabled(L.PUMPBTCOMM)) log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes)); try { @@ -167,10 +167,10 @@ public class SerialIOThread extends AbstractSerialIOThread { SystemClock.sleep(200); if (!message.received) { - log.warn("Reply not received " + message.getMessageName()); + log.error("Reply not received " + message.getMessageName()); if (message.getCommand() == 0xF0F1) { DanaRPump.getInstance().isNewPump = false; - log.debug("Old firmware detected"); + log.error("Old firmware detected"); } } } @@ -181,24 +181,29 @@ public class SerialIOThread extends AbstractSerialIOThread { try { mInputStream.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { mOutputStream.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { mRfCommSocket.close(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } try { System.runFinalization(); } catch (Exception e) { - if (Config.logDanaSerialEngine) log.debug(e.getMessage()); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug(e.getMessage()); } - if (Config.logDanaSerialEngine) log.debug("Disconnected: " + reason); + if (L.isEnabled(L.PUMPBTCOMM)) + log.debug("Disconnected: " + reason); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java index 8d1cd12be1..c95a800128 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java @@ -1,8 +1,5 @@ package info.nightscout.androidaps.plugins.PumpDanaRv2.comm; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.HashMap; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; @@ -13,8 +10,6 @@ import info.nightscout.androidaps.plugins.PumpDanaR.comm.*; * Created by mike on 28.05.2016. */ public class MessageHashTable_v2 { - private static Logger log = LoggerFactory.getLogger(MessageHashTable_v2.class); - public static HashMap messages = null; static { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgCheckValue_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgCheckValue_v2.java index 0869844a1c..8810edb815 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgCheckValue_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgCheckValue_v2.java @@ -3,11 +3,11 @@ package info.nightscout.androidaps.plugins.PumpDanaRv2.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -21,10 +21,12 @@ import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; * Created by mike on 30.06.2016. */ public class MsgCheckValue_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgCheckValue_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgCheckValue_v2() { SetCommand(0xF0F1); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -32,7 +34,8 @@ public class MsgCheckValue_v2 extends MessageBase { DanaRPump pump = DanaRPump.getInstance(); pump.isNewPump = true; - log.debug("New firmware confirmed"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New firmware confirmed"); pump.model = intFromBuff(bytes, 0, 1); pump.protocol = intFromBuff(bytes, 1, 1); @@ -42,7 +45,7 @@ public class MsgCheckValue_v2 extends MessageBase { Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model"); - log.debug("Wrong model selected. Switching to Korean DanaR"); + log.error("Wrong model selected. Switching to Korean DanaR"); MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, true); MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setFragmentVisible(PluginType.PUMP, true); MainApp.getSpecificPlugin(DanaRPlugin.class).setPluginEnabled(PluginType.PUMP, false); @@ -67,7 +70,7 @@ public class MsgCheckValue_v2 extends MessageBase { Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL); MainApp.bus().post(new EventNewNotification(notification)); DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model"); - log.debug("Wrong model selected. Switching to non APS DanaR"); + log.error("Wrong model selected. Switching to non APS DanaR"); (MainApp.getSpecificPlugin(DanaRv2Plugin.class)).setPluginEnabled(PluginType.PUMP, false); (MainApp.getSpecificPlugin(DanaRv2Plugin.class)).setFragmentVisible(PluginType.PUMP, false); (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PUMP, true); @@ -84,7 +87,7 @@ public class MsgCheckValue_v2 extends MessageBase { ConfigBuilderPlugin.getCommandQueue().readStatus("PumpDriverChange", null); // force new connection return; } - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Model: " + String.format("%02X ", pump.model)); log.debug("Protocol: " + String.format("%02X ", pump.protocol)); log.debug("Product Code: " + String.format("%02X ", pump.productCode)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java index 91c01ba38c..04eb6a1a78 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgHistoryEvents_v2.java @@ -13,6 +13,7 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventPumpStatusChanged; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; @@ -20,7 +21,7 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; public class MsgHistoryEvents_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgHistoryEvents_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public boolean done; public static long lastEventTimeLoaded = 0; @@ -31,6 +32,8 @@ public class MsgHistoryEvents_v2 extends MessageBase { gfrom.setTimeInMillis(from); AddParamDate(gfrom); done = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public MsgHistoryEvents_v2() { @@ -41,6 +44,8 @@ public class MsgHistoryEvents_v2 extends MessageBase { AddParamByte((byte) 0); AddParamByte((byte) 0); done = false; + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } @Override @@ -69,10 +74,12 @@ public class MsgHistoryEvents_v2 extends MessageBase { DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(datetime.getTime()); if (detailedBolusInfo == null) { - log.debug("Detailed bolus info not found for " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Detailed bolus info not found for " + datetime.toLocaleString()); detailedBolusInfo = new DetailedBolusInfo(); } else { - log.debug("Detailed bolus info found: " + detailedBolusInfo); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Detailed bolus info found: " + detailedBolusInfo); } detailedBolusInfo.date = datetime.getTime(); detailedBolusInfo.source = Source.PUMP; @@ -82,73 +89,86 @@ public class MsgHistoryEvents_v2 extends MessageBase { switch (recordCode) { case DanaRPump.TEMPSTART: - log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT TEMPSTART (" + recordCode + ") " + datetime.toLocaleString() + " Ratio: " + param1 + "% Duration: " + param2 + "min"); temporaryBasal.percentRate = param1; temporaryBasal.durationInMinutes = param2; TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); status = "TEMPSTART " + DateUtil.timeString(datetime); break; case DanaRPump.TEMPSTOP: - log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT TEMPSTOP (" + recordCode + ") " + datetime.toLocaleString()); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal); status = "TEMPSTOP " + DateUtil.timeString(datetime); break; case DanaRPump.EXTENDEDSTART: - log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT EXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); extendedBolus.insulin = param1 / 100d; extendedBolus.durationInMinutes = param2; TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "EXTENDEDSTART " + DateUtil.timeString(datetime); break; case DanaRPump.EXTENDEDSTOP: - log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT EXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "EXTENDEDSTOP " + DateUtil.timeString(datetime); break; case DanaRPump.BOLUS: detailedBolusInfo.insulin = param1 / 100d; boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); - log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug((newRecord ? "**NEW** " : "") + "EVENT BOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); DetailedBolusInfoStorage.remove(detailedBolusInfo.date); status = "BOLUS " + DateUtil.timeString(datetime); break; case DanaRPump.DUALBOLUS: detailedBolusInfo.insulin = param1 / 100d; newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); - log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug((newRecord ? "**NEW** " : "") + "EVENT DUALBOLUS (" + recordCode + ") " + datetime.toLocaleString() + " Bolus: " + (param1 / 100d) + "U Duration: " + param2 + "min"); DetailedBolusInfoStorage.remove(detailedBolusInfo.date); status = "DUALBOLUS " + DateUtil.timeString(datetime); break; case DanaRPump.DUALEXTENDEDSTART: - log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT DUALEXTENDEDSTART (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + (param1 / 100d) + "U Duration: " + param2 + "min"); extendedBolus.insulin = param1 / 100d; extendedBolus.durationInMinutes = param2; TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "DUALEXTENDEDSTART " + DateUtil.timeString(datetime); break; case DanaRPump.DUALEXTENDEDSTOP: - log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + datetime.toLocaleString() + " Delivered: " + (param1 / 100d) + "U RealDuration: " + param2 + "min"); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime); break; case DanaRPump.SUSPENDON: - log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT SUSPENDON (" + recordCode + ") " + datetime.toLocaleString()); status = "SUSPENDON " + DateUtil.timeString(datetime); break; case DanaRPump.SUSPENDOFF: - log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString()); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT SUSPENDOFF (" + recordCode + ") " + datetime.toLocaleString()); status = "SUSPENDOFF " + DateUtil.timeString(datetime); break; case DanaRPump.REFILL: - log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT REFILL (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); status = "REFILL " + DateUtil.timeString(datetime); break; case DanaRPump.PRIME: - log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT PRIME (" + recordCode + ") " + datetime.toLocaleString() + " Amount: " + param1 / 100d + "U"); status = "PRIME " + DateUtil.timeString(datetime); break; case DanaRPump.PROFILECHANGE: - log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("EVENT PROFILECHANGE (" + recordCode + ") " + datetime.toLocaleString() + " No: " + param1 + " CurrentRate: " + (param2 / 100d) + "U/h"); status = "PROFILECHANGE " + DateUtil.timeString(datetime); break; case DanaRPump.CARBS: @@ -158,11 +178,13 @@ public class MsgHistoryEvents_v2 extends MessageBase { emptyCarbsInfo.source = Source.PUMP; emptyCarbsInfo.pumpId = datetime.getTime(); newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(emptyCarbsInfo, false); - log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug((newRecord ? "**NEW** " : "") + "EVENT CARBS (" + recordCode + ") " + datetime.toLocaleString() + " Carbs: " + param1 + "g"); status = "CARBS " + DateUtil.timeString(datetime); break; default: - log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Event: " + recordCode + " " + datetime.toLocaleString() + " Param1: " + param1 + " Param2: " + param2); status = "UNKNOWN " + DateUtil.timeString(datetime); break; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetAPSTempBasalStart_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetAPSTempBasalStart_v2.java index 6b6e3045de..42964a64c6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetAPSTempBasalStart_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetAPSTempBasalStart_v2.java @@ -3,11 +3,11 @@ package info.nightscout.androidaps.plugins.PumpDanaRv2.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgSetAPSTempBasalStart_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetAPSTempBasalStart_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); protected final int PARAM30MIN = 160; protected final int PARAM15MIN = 150; @@ -19,6 +19,8 @@ public class MsgSetAPSTempBasalStart_v2 extends MessageBase { public MsgSetAPSTempBasalStart_v2(int percent) { this(); setParams(percent); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message: percent: " + percent); } protected void setParams(int percent) { @@ -29,11 +31,11 @@ public class MsgSetAPSTempBasalStart_v2 extends MessageBase { AddParamInt(percent); if (percent < 100) { AddParamByte((byte) PARAM30MIN); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 30 min"); } else { AddParamByte((byte) PARAM15MIN); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 15 min"); } } @@ -51,11 +53,11 @@ public class MsgSetAPSTempBasalStart_v2 extends MessageBase { AddParamInt(percent); if (thirtyMinutes && percent <= 200) { // 30 min is allowed up to 200% AddParamByte((byte) PARAM30MIN); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 30 min"); } else { AddParamByte((byte) PARAM15MIN); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("APS Temp basal start percent: " + percent + " duration 15 min"); } } @@ -64,10 +66,11 @@ public class MsgSetAPSTempBasalStart_v2 extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set APS temp basal start result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set APS temp basal start result: " + result + " FAILED!!!"); } else { failed = false; - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set APS temp basal start result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetHistoryEntry_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetHistoryEntry_v2.java index abeb656f03..0c55b29a3f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetHistoryEntry_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgSetHistoryEntry_v2.java @@ -6,11 +6,11 @@ import org.slf4j.LoggerFactory; import java.util.Date; import java.util.GregorianCalendar; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgSetHistoryEntry_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgSetHistoryEntry_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgSetHistoryEntry_v2() { SetCommand(0xE004); @@ -25,7 +25,7 @@ public class MsgSetHistoryEntry_v2 extends MessageBase { AddParamDateTime(gtime); AddParamInt(param1); AddParamInt(param2); - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set history entry: type: " + type + " date: " + new Date(time).toString() + " param1: " + param1 + " param2: " + param2); } @@ -34,9 +34,10 @@ public class MsgSetHistoryEntry_v2 extends MessageBase { int result = intFromBuff(bytes, 0, 1); if (result != 1) { failed = true; - log.debug("Set history entry result: " + result + " FAILED!!!"); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("Set history entry result: " + result + " FAILED!!!"); } else { - if (Config.logDanaMessageDetail) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set history entry result: " + result); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusAPS_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusAPS_v2.java index c2f87ee36a..5d0238f2f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusAPS_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusAPS_v2.java @@ -3,15 +3,17 @@ package info.nightscout.androidaps.plugins.PumpDanaRv2.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgStatusAPS_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgStatusAPS_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgStatusAPS_v2() { SetCommand(0xE001); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -21,7 +23,7 @@ public class MsgStatusAPS_v2 extends MessageBase { DanaRPump pump = DanaRPump.getInstance(); pump.iob = iob; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Delivered so far: " + deliveredSoFar); log.debug("Current pump IOB: " + iob); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusBolusExtended_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusBolusExtended_v2.java index f695f6a792..c9a2446cd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusBolusExtended_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusBolusExtended_v2.java @@ -7,18 +7,17 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgStatusBolusExtended_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgStatusBolusExtended_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgStatusBolusExtended_v2() { SetCommand(0x0207); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -46,7 +45,7 @@ public class MsgStatusBolusExtended_v2 extends MessageBase { pump.extendedBolusStart = extendedBolusStart; pump.extendedBolusRemainingMinutes = extendedBolusRemainingMinutes; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Is extended bolus running: " + isExtendedInProgress); log.debug("Extended bolus min: " + extendedBolusMinutes); log.debug("Extended bolus amount: " + extendedBolusAmount); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusTempBasal_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusTempBasal_v2.java index 256fa4cd8a..992b15e9ca 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusTempBasal_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MsgStatusTempBasal_v2.java @@ -7,18 +7,17 @@ import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.interfaces.TreatmentsInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase; public class MsgStatusTempBasal_v2 extends MessageBase { - private static Logger log = LoggerFactory.getLogger(MsgStatusTempBasal_v2.class); + private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); public MsgStatusTempBasal_v2() { SetCommand(0x0205); + if (L.isEnabled(L.PUMPCOMM)) + log.debug("New message"); } public void handleMessage(byte[] bytes) { @@ -41,7 +40,7 @@ public class MsgStatusTempBasal_v2 extends MessageBase { pump.tempBasalTotalSec = tempBasalTotalSec; pump.tempBasalStart = tempBasalStart; - if (Config.logDanaMessageDetail) { + if (L.isEnabled(L.PUMPCOMM)) { log.debug("Is temp basal running: " + isTempBasalInProgress); log.debug("Is APS temp basal running: " + isAPSTempBasalInProgress); log.debug("Current temp basal percent: " + tempBasalPercent); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java index 1229f23f4e..1e1147c849 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/services/DanaRv2ExecutionService.java @@ -8,12 +8,9 @@ import android.os.SystemClock; import com.squareup.otto.Subscribe; -import org.slf4j.LoggerFactory; - import java.io.IOException; import java.util.Date; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -25,7 +22,9 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; 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.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; @@ -72,7 +71,7 @@ import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.T; @@ -81,7 +80,6 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { private long lastHistoryFetched = 0; public DanaRv2ExecutionService() { - log = LoggerFactory.getLogger(DanaRv2ExecutionService.class); mBinder = new LocalBinder(); registerBus(); @@ -105,7 +103,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Subscribe public void onStatusEvent(EventAppExit event) { - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received"); if (mSerialIOThread != null) @@ -114,7 +112,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { MainApp.instance().getApplicationContext().unregisterReceiver(receiver); stopSelf(); - if (Config.logFunctionCalls) + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit finished"); } @@ -126,7 +124,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public void connect() { if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) { - if(System.currentTimeMillis() > lastWrongPumpPassword + 30 * 1000) { + if (System.currentTimeMillis() > lastWrongPumpPassword + 30 * 1000) { Notification notification = new Notification(Notification.WRONG_PUMP_PASSWORD, MainApp.gs(R.string.wrongpumppassword), Notification.URGENT); notification.soundId = R.raw.error; lastWrongPumpPassword = System.currentTimeMillis(); @@ -195,7 +193,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { mDanaRPump.lastConnection = System.currentTimeMillis(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = MainApp.getConfigBuilder().getActivePump(); if (profile != null && Math.abs(mDanaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); @@ -208,10 +206,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 3) { - if (Math.abs(timeDiff) > 60*60*1.5) { - log.debug("Pump time difference: " + timeDiff + " seconds - large difference"); + if (Math.abs(timeDiff) > 60 * 60 * 1.5) { + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds - large difference"); //If time-diff is very large, warn user until we can synchronize history readings properly Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); i.putExtra("soundid", R.raw.error); @@ -231,7 +231,8 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSetTime(new Date(DateUtil.now() + T.secs(10).msecs()))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; - log.debug("Pump time difference: " + timeDiff + " seconds"); + if (L.isEnabled(L.PUMP)) + log.debug("Pump time difference: " + timeDiff + " seconds"); } } @@ -258,8 +259,9 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { MainApp.bus().post(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { - log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); - if(System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { + if (L.isEnabled(L.PUMP)) + log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); + if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT); MainApp.bus().post(new EventNewNotification(reportFail)); NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U"); @@ -315,7 +317,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { SystemClock.sleep(500); } MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); - mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(percent, durationInMinutes == 15, durationInMinutes == 30)); + mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(percent, durationInMinutes == 15, durationInMinutes == 30)); mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2()); loadEvents(); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); @@ -389,7 +391,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm stop.stopped = true; stop.forced = true; - log.debug("Communication stopped"); + log.error("Communication stopped"); } } } @@ -434,7 +436,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } public void bolusStop() { - if (Config.logDanaBTComm) + if (L.isEnabled(L.PUMP)) log.debug("bolusStop >>>>> @ " + (mBolusingTreatment == null ? "" : mBolusingTreatment.insulin)); MsgBolusStop stop = new MsgBolusStop(); stop.forced = true; @@ -461,23 +463,25 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public PumpEnactResult loadEvents() { - if(!MainApp.getSpecificPlugin(DanaRv2Plugin.class).isInitialized()){ + if (!MainApp.getSpecificPlugin(DanaRv2Plugin.class).isInitialized()) { PumpEnactResult result = new PumpEnactResult().success(false); result.comment = "pump not initialized"; return result; } - - + + if (!isConnected()) return new PumpEnactResult().success(false); SystemClock.sleep(300); MsgHistoryEvents_v2 msg; if (lastHistoryFetched == 0) { msg = new MsgHistoryEvents_v2(); - log.debug("Loading complete event history"); + if (L.isEnabled(L.PUMP)) + log.debug("Loading complete event history"); } else { msg = new MsgHistoryEvents_v2(lastHistoryFetched); - log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString()); + if (L.isEnabled(L.PUMP)) + log.debug("Loading event history from: " + new Date(lastHistoryFetched).toLocaleString()); } mSerialIOThread.sendMessage(msg); while (!msg.done && mRfcommSocket.isConnected()) { @@ -495,7 +499,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { if (!isConnected()) return false; MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); - double[] basal = DanaRPump.buildDanaRProfileRecord(profile); + double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); mSerialIOThread.sendMessage(msgSet); MsgSetActivateBasalProfile msgActivate = new MsgSetActivateBasalProfile((byte) 0); @@ -512,7 +516,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { long timeToWholeMinute = (60000 - time % 60000); if (timeToWholeMinute > 59800 || timeToWholeMinute < 3000) break; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int)(timeToWholeMinute / 1000)))); + MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); SystemClock.sleep(Math.min(timeToWholeMinute, 100)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java index 5fd8e25f26..2f9d5d21dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java @@ -31,7 +31,9 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; @@ -51,7 +53,7 @@ import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem; import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import sugar.free.sightparser.applayer.descriptors.ActiveBolus; import sugar.free.sightparser.applayer.descriptors.ActiveBolusType; @@ -460,7 +462,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai log.debug("Failure to deliver treatment"); } - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result); updateGui(); @@ -556,7 +558,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); updateGui(); - if (Config.logPumpComm) log.debug("Set temp basal " + percent + "% for " + durationInMinutes + "m"); + if (L.isEnabled(L.PUMPCOMM)) log.debug("Set temp basal " + percent + "% for " + durationInMinutes + "m"); connector.requestHistorySync(5000); connector.tryToGetPumpStatusAgain(); return new PumpEnactResult().success(true).enacted(true).percent(percent); @@ -574,7 +576,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai cancelExtendedBolus(); realTBRCancel(); updateGui(); - if (Config.logPumpComm) log.debug("Canceling temp basal"); + if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling temp basal"); connector.requestHistorySync(5000); connector.tryToGetPumpStatusAgain(); return new PumpEnactResult().success(true).enacted(true).isTempCancel(true); @@ -611,7 +613,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai updateGui(); connector.requestHistorySync(30000); connector.tryToGetPumpStatusAgain(); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting extended bolus: " + insulin + " mins:" + durationInMinutes); return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin); } catch (Exception e) { @@ -632,7 +634,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai exStop.source = Source.USER; TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop); } - if (Config.logPumpComm) log.debug("Cancel extended bolus:"); + if (L.isEnabled(L.PUMPCOMM)) log.debug("Cancel extended bolus:"); if (bolusId != null) connector.requestHistorySync(5000); connector.tryToGetPumpStatusAgain(); updateGui(); @@ -670,7 +672,7 @@ public class InsightPlugin extends PluginBase implements PumpInterface, Constrai status.put("timestamp", DateUtil.toISOString(connector.getLastContactTime())); extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); try { - extended.put("ActiveProfile", MainApp.getConfigBuilder().getProfileName()); + extended.put("ActiveProfile", ProfileFunctions.getInstance().getProfileName()); } catch (Exception e) { } TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java index 2c2235bf47..87e427737b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java @@ -6,7 +6,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.TDD; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import org.json.JSONException; import org.json.JSONObject; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java index fb41a72e88..209d24d193 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpMDI/MDIPlugin.java @@ -8,7 +8,6 @@ import org.slf4j.LoggerFactory; import java.util.Date; import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -19,6 +18,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; @@ -149,7 +149,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting temp basal absolute: " + result); return result; } @@ -159,7 +159,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Settings temp basal percent: " + result); return result; } @@ -169,7 +169,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting extended bolus: " + result); return result; } @@ -179,7 +179,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Cancel temp basal: " + result); return result; } @@ -189,7 +189,7 @@ public class MDIPlugin extends PluginBase implements PumpInterface { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.pumperror); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling extended basal: " + result); return result; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java index 12977b89bf..a72c1313d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpPlugin.java @@ -24,13 +24,15 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.PumpVirtual.events.EventVirtualPumpUpdateGui; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; /** @@ -190,7 +192,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { @Override public double getBaseBasalRate() { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile != null) return profile.getBasal(); else @@ -222,7 +224,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { bolusingEvent.percent = 100; MainApp.bus().post(bolusingEvent); SystemClock.sleep(1000); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); lastDataTime = new Date(); @@ -250,7 +252,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { result.duration = durationInMinutes; result.comment = MainApp.gs(R.string.virtualpump_resultok); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting temp basal absolute: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); lastDataTime = new Date(); @@ -278,7 +280,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { result.duration = durationInMinutes; result.comment = MainApp.gs(R.string.virtualpump_resultok); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Settings temp basal percent: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); lastDataTime = new Date(); @@ -302,7 +304,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { result.duration = durationInMinutes; result.comment = MainApp.gs(R.string.virtualpump_resultok); TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting extended bolus: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); lastDataTime = new Date(); @@ -320,7 +322,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { TemporaryBasal tempStop = new TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop); //tempBasal = null; - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling temp basal: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); } @@ -340,7 +342,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { result.enacted = true; result.isTempCancel = true; result.comment = MainApp.gs(R.string.virtualpump_resultok); - if (Config.logPumpComm) + if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling extended basal: " + result); MainApp.bus().post(new EventVirtualPumpUpdateGui()); lastDataTime = new Date(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java index 1d96eeff6b..9f72f1b119 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/AbstractSensitivityPlugin.java @@ -7,24 +7,26 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.SensitivityInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; +import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.utils.Round; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; public abstract class AbstractSensitivityPlugin extends PluginBase implements SensitivityInterface { - private static final Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static final Logger log = LoggerFactory.getLogger(L.AUTOSENS); public AbstractSensitivityPlugin(PluginDescription pluginDescription) { super(pluginDescription); } @Override - public abstract AutosensResult detectSensitivity(long fromTime, long toTime); + public abstract AutosensResult detectSensitivity(IobCobCalculatorPlugin plugin, long fromTime, long toTime); - public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, - String ratioLimit, String sensResult, int deviationsArraySize) { + AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, + String ratioLimit, String sensResult, int deviationsArraySize) { return this.fillResult(ratio, carbsAbsorbed, pastSensitivity, ratioLimit, sensResult, deviationsArraySize, SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_min, "0.7")), @@ -32,8 +34,8 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se } public AutosensResult fillResult(double ratio, double carbsAbsorbed, String pastSensitivity, - String ratioLimit, String sensResult, int deviationsArraySize, - double ratioMin, double ratioMax) { + String ratioLimit, String sensResult, int deviationsArraySize, + double ratioMin, double ratioMax) { double rawRatio = ratio; ratio = Math.max(ratio, ratioMin); ratio = Math.min(ratio, ratioMax); @@ -51,7 +53,8 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se if (ratio != rawRatio) { ratioLimit += "Ratio limited from " + rawRatio + " to " + ratio; - log.debug(ratioLimit); + if (L.isEnabled(L.AUTOSENS)) + log.debug(ratioLimit); } AutosensResult output = new AutosensResult(); @@ -64,5 +67,4 @@ public abstract class AbstractSensitivityPlugin extends PluginBase implements Se } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java index e5ca522a51..993a51edf8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityAAPSPlugin.java @@ -10,13 +10,14 @@ import java.util.Arrays; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; @@ -28,7 +29,7 @@ import info.nightscout.utils.SP; */ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); static SensitivityAAPSPlugin plugin = null; @@ -49,8 +50,8 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); String age = SP.getString(R.string.key_age, ""); int defaultHours = 24; @@ -59,21 +60,23 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { if (age.equals(MainApp.gs(R.string.key_child))) defaultHours = 4; int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { - log.debug("No profile"); + log.error("No profile"); return new AutosensResult(); } if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -131,7 +134,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { String ratioLimit = ""; String sensResult = ""; - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); @@ -148,13 +151,13 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { sensResult = "Sensitivity normal"; } - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(sensResult); AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, deviationsArray.size()); - if (Config.logAutosensData) { + if (L.isEnabled(L.AUTOSENS)) { log.debug("Sensitivity to: {}, percentile: {} ratio: {} mealCOB: ", new Date(toTime).toLocaleString(), percentile, output.ratio, ratio, current.cob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java index c9086dbfbd..de0e9c9c0c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref0Plugin.java @@ -10,13 +10,14 @@ import java.util.Arrays; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; @@ -27,7 +28,7 @@ import info.nightscout.utils.DateUtil; */ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); static SensitivityOref0Plugin plugin = null; @@ -48,27 +49,29 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); int hoursForDetection = 24; long now = System.currentTimeMillis(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { - log.debug("No profile"); + log.error("No profile"); return new AutosensResult(); } if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -126,14 +129,14 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { String ratioLimit = ""; String sensResult = ""; - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); for (double i = 0.9; i > 0.1; i = i - 0.02) { if (IobCobCalculatorPlugin.percentile(deviations, (i + 0.02)) >= 0 && IobCobCalculatorPlugin.percentile(deviations, i) < 0) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(Math.round(100 * i) + "% of non-meal deviations negative (target 45%-50%)"); } } @@ -152,7 +155,7 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { sensResult = "Sensitivity normal"; } - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(sensResult); ratio = 1 + (basalOff / profile.getMaxDailyBasal()); @@ -160,7 +163,7 @@ public class SensitivityOref0Plugin extends AbstractSensitivityPlugin { AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, deviationsArray.size()); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Sensitivity to: {} ratio: {} mealCOB: {}", new Date(toTime).toLocaleString(), output.ratio, current.cob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java index 29787b14c0..06656617c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityOref1Plugin.java @@ -10,13 +10,14 @@ import java.util.Arrays; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; @@ -27,7 +28,7 @@ import info.nightscout.utils.DateUtil; */ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); static SensitivityOref1Plugin plugin = null; @@ -48,27 +49,29 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular // dependency, this should be avoided - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { - log.debug("No profile"); + log.error("No profile"); return new AutosensResult(); } if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } // the current - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -120,10 +123,12 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { // when we have less than 8h worth of deviation data, add up to 90m of zero deviations // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely - log.debug("Using most recent " + deviationsArray.size() + " deviations"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Using most recent " + deviationsArray.size() + " deviations"); if (deviationsArray.size() < 96) { int pad = Math.round((1 - deviationsArray.size() / 96) * 18); - log.debug("Adding " + pad + " more zero deviations"); + if (L.isEnabled(L.AUTOSENS)) + log.debug("Adding " + pad + " more zero deviations"); for (int d = 0; d < pad; d++) { //process.stderr.write("."); deviationsArray.add(0d); @@ -139,18 +144,18 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { String ratioLimit = ""; String sensResult = ""; - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); for (double i = 0.9; i > 0.1; i = i - 0.01) { if (IobCobCalculatorPlugin.percentile(deviations, (i + 0.01)) >= 0 && IobCobCalculatorPlugin.percentile(deviations, i) < 0) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(Math.round(100 * i) + "% of non-meal deviations negative (>50% = sensitivity)"); } if (IobCobCalculatorPlugin.percentile(deviations, (i + 0.01)) > 0 && IobCobCalculatorPlugin.percentile(deviations, i) <= 0) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(Math.round(100 * i) + "% of non-meal deviations negative (>50% = resistance)"); } } @@ -169,7 +174,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { sensResult = "Sensitivity normal"; } - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(sensResult); ratio = 1 + (basalOff / profile.getMaxDailyBasal()); @@ -177,7 +182,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, deviationsArray.size()); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Sensitivity to: {} ratio: {} mealCOB: {}", new Date(toTime).toLocaleString(), output.ratio, current.cob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java index 0200838d39..95b027a86c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Sensitivity/SensitivityWeightedAveragePlugin.java @@ -8,13 +8,14 @@ import org.slf4j.LoggerFactory; import java.util.Date; import java.util.List; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; @@ -26,7 +27,7 @@ import info.nightscout.utils.SP; */ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { - private static Logger log = LoggerFactory.getLogger("AUTOSENS"); + private static Logger log = LoggerFactory.getLogger(L.AUTOSENS); private static SensitivityWeightedAveragePlugin plugin = null; @@ -47,8 +48,8 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin } @Override - public AutosensResult detectSensitivity(long fromTime, long toTime) { - LongSparseArray autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable(); + public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); String age = SP.getString(R.string.key_age, ""); int defaultHours = 24; @@ -58,21 +59,22 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin int hoursForDetection = SP.getInt(R.string.key_openapsama_autosens_period, defaultHours); if (autosensDataTable == null || autosensDataTable.size() < 4) { - log.debug("No autosens data available. lastDataTime=" + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. lastDataTime=" + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - AutosensData current = IobCobCalculatorPlugin.getPlugin().getAutosensData(toTime); // this is running inside lock already + AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - if (Config.logAutosensData) - log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + IobCobCalculatorPlugin.getPlugin().lastDataTime()); + if (L.isEnabled(L.AUTOSENS)) + log.debug("No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("No profile available"); return new AutosensResult(); } @@ -130,11 +132,11 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin } if (data.size() == 0) { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); return new AutosensResult(); } else { - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); } @@ -159,7 +161,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin String ratioLimit = ""; String sensResult; - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Records: " + index + " " + pastSensitivity); double average = weightedsum / weights; @@ -174,13 +176,13 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin sensResult = "Sensitivity normal"; } - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug(sensResult); AutosensResult output = fillResult(ratio, current.cob, pastSensitivity, ratioLimit, sensResult, data.size()); - if (Config.logAutosensData) + if (L.isEnabled(L.AUTOSENS)) log.debug("Sensitivity to: {} weightedaverage: {} ratio: {} mealCOB: {}", new Date(toTime).toLocaleString(), average, output.ratio, current.cob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java index 847ead4482..dd663ec1be 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.SmsCommunicator; import android.content.Intent; import android.content.pm.ResolveInfo; +import android.os.Bundle; import android.os.SystemClock; import android.telephony.SmsManager; import android.telephony.SmsMessage; @@ -20,7 +21,8 @@ import java.util.List; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.IobTotal; @@ -39,13 +41,12 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; -import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS; import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.SafeParse; import info.nightscout.utils.T; @@ -165,10 +166,11 @@ public class SmsCommunicatorPlugin extends PluginBase { return false; } - @Subscribe - public void onStatusEvent(final EventNewSMS ev) { + public void handleNewData(Intent intent) { + Bundle bundle = intent.getExtras(); + if (bundle == null) return; - Object[] pdus = (Object[]) ev.bundle.get("pdus"); + Object[] pdus = (Object[]) bundle.get("pdus"); if (pdus != null) { // For every SMS message received for (Object pdu : pdus) { @@ -206,7 +208,7 @@ public class SmsCommunicatorPlugin extends PluginBase { BgReading actualBG = DatabaseHelper.actualBg(); BgReading lastBG = DatabaseHelper.lastBg(); - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); if (actualBG != null) { reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", "; @@ -377,7 +379,7 @@ public class SmsCommunicatorPlugin extends PluginBase { } } else { tempBasal = SafeParse.stringToDouble(splited[1]); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { reply = MainApp.gs(R.string.noprofile); sendSMS(new Sms(receivedSms.phoneNumber, reply, new Date())); @@ -470,7 +472,7 @@ public class SmsCommunicatorPlugin extends PluginBase { } else if (tempBasalWaitingForConfirmation != null && !tempBasalWaitingForConfirmation.processed && tempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - tempBasalWaitingForConfirmation.date.getTime() < Constants.SMS_CONFIRM_TIMEOUT) { tempBasalWaitingForConfirmation.processed = true; - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile != null) ConfigBuilderPlugin.getCommandQueue().tempBasalAbsolute(tempBasalWaitingForConfirmation.tempBasal, 30, true, profile, new Callback() { @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventNewSMS.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventNewSMS.java deleted file mode 100644 index dfaebb3942..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventNewSMS.java +++ /dev/null @@ -1,15 +0,0 @@ -package info.nightscout.androidaps.plugins.SmsCommunicator.events; - -import android.os.Bundle; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 13.07.2016. - */ -public class EventNewSMS extends Event { - public Bundle bundle; - public EventNewSMS(Bundle bundle) { - this.bundle = bundle; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/BGSourceFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/BGSourceFragment.java index 3e9a79d459..cdd77ca1b2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/BGSourceFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/BGSourceFragment.java @@ -27,7 +27,7 @@ import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.utils.DateUtil; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; /** * Created by mike on 16.10.2017. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java index af040c8c90..46d138c73d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java @@ -1,17 +1,32 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; +import info.nightscout.utils.SP; /** * Created by mike on 28.11.2017. */ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(L.BGSOURCE); private static SourceDexcomG5Plugin plugin = null; @@ -37,4 +52,43 @@ public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterfac public boolean advancedFilteringSupported() { return true; } + + @Override + public void handleNewData(Intent intent) { + // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + String data = bundle.getString("data"); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received Dexcom Data", data); + + try { + JSONArray jsonArray = new JSONArray(data); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received Dexcom Data size:" + jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + bgReading.value = json.getInt("m_value"); + bgReading.direction = json.getString("m_trend"); + bgReading.date = json.getLong("m_time") * 1000L; + bgReading.raw = 0; + boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5"); + if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + NSUpload.uploadBg(bgReading); + } + if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { + NSUpload.sendToXdrip(bgReading); + } + } + + } catch (JSONException e) { + log.error("Exception: ", e); + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java index 38b891ff65..07fdba51ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceGlimpPlugin.java @@ -1,15 +1,26 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.BundleLogger; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 05.08.2016. */ public class SourceGlimpPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(L.BGSOURCE); private static SourceGlimpPlugin plugin = null; @@ -32,4 +43,25 @@ public class SourceGlimpPlugin extends PluginBase implements BgSourceInterface { public boolean advancedFilteringSupported() { return false; } + + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received Glimp Data: " + BundleLogger.log(bundle)); + + BgReading bgReading = new BgReading(); + + bgReading.value = bundle.getDouble("mySGV"); + bgReading.direction = bundle.getString("myTrend"); + bgReading.date = bundle.getLong("myTimestamp"); + bgReading.raw = 0; + + MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP"); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java index 041b084efd..8bc6811ef4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceMM640gPlugin.java @@ -1,15 +1,29 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +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.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 05.08.2016. */ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(L.BGSOURCE); + private static SourceMM640gPlugin plugin = null; public static SourceMM640gPlugin getPlugin() { @@ -31,4 +45,49 @@ public class SourceMM640gPlugin extends PluginBase implements BgSourceInterface public boolean advancedFilteringSupported() { return false; } + + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + final String collection = bundle.getString("collection"); + if (collection == null) return; + + if (collection.equals("entries")) { + final String data = bundle.getString("data"); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received MM640g Data: ", data); + + if ((data != null) && (data.length() > 0)) { + try { + final JSONArray json_array = new JSONArray(data); + for (int i = 0; i < json_array.length(); i++) { + final JSONObject json_object = json_array.getJSONObject(i); + final String type = json_object.getString("type"); + switch (type) { + case "sgv": + BgReading bgReading = new BgReading(); + + bgReading.value = json_object.getDouble("sgv"); + bgReading.direction = json_object.getString("direction"); + bgReading.date = json_object.getLong("date"); + bgReading.raw = json_object.getDouble("sgv"); + + MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g"); + break; + default: + if (L.isEnabled(L.BGSOURCE)) + log.debug("Unknown entries type: " + type); + } + } + } catch (JSONException e) { + log.error("Exception: ", e); + } + } + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java index c99fbcb9bb..eb901ca1b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceNSClientPlugin.java @@ -1,16 +1,32 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; +import info.nightscout.utils.JsonHelper; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. */ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(L.BGSOURCE); private static SourceNSClientPlugin plugin = null; @@ -39,6 +55,50 @@ public class SourceNSClientPlugin extends PluginBase implements BgSourceInterfac return isAdvancedFilteringEnabled; } + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE) && !SP.getBoolean(R.string.key_ns_autobackfill, true)) + return; + + Bundle bundles = intent.getExtras(); + + try { + if (bundles.containsKey("sgv")) { + String sgvstring = bundles.getString("sgv"); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received NS Data: " + sgvstring); + + JSONObject sgvJson = new JSONObject(sgvstring); + storeSgv(sgvJson); + } + + if (bundles.containsKey("sgvs")) { + String sgvstring = bundles.getString("sgvs"); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received NS Data: " + sgvstring); + JSONArray jsonArray = new JSONArray(sgvstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject sgvJson = jsonArray.getJSONObject(i); + storeSgv(sgvJson); + } + } + } catch (Exception e) { + log.error("Unhandled exception", e); + } + + // Objectives 0 + ObjectivesPlugin.bgIsAvailableInNS = true; + ObjectivesPlugin.saveProgress(); + } + + private void storeSgv(JSONObject sgvJson) { + NSSgv nsSgv = new NSSgv(sgvJson); + BgReading bgReading = new BgReading(nsSgv); + MainApp.getDbHelper().createIfNotExists(bgReading, "NS"); + SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills")); + } + public void detectSource(String source, long timeStamp) { if (timeStamp > lastBGTimeStamp) { if (source.contains("G5 Native") || source.contains("AndroidAPS-DexcomG5")) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java index 13cb99d392..4cdd8dd810 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourcePoctechPlugin.java @@ -1,16 +1,33 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; +import info.nightscout.utils.JsonHelper; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; +import info.nightscout.utils.SP; /** * Created by mike on 05.08.2016. */ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(L.BGSOURCE); private static SourcePoctechPlugin plugin = null; @@ -36,4 +53,44 @@ public class SourcePoctechPlugin extends PluginBase implements BgSourceInterface return false; } + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + BgReading bgReading = new BgReading(); + + String data = bundle.getString("data"); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received Poctech Data", data); + + try { + JSONArray jsonArray = new JSONArray(data); + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received Poctech Data size:" + jsonArray.length()); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + bgReading.value = json.getDouble("current"); + bgReading.direction = json.getString("direction"); + bgReading.date = json.getLong("date"); + bgReading.raw = json.getDouble("raw"); + if (JsonHelper.safeGetString(json, "units", Constants.MGDL).equals("mmol/L")) + bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL; + boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech"); + if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) { + NSUpload.uploadBg(bgReading); + } + if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { + NSUpload.sendToXdrip(bgReading); + } + } + + } catch (JSONException e) { + log.error("Exception: ", e); + } + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java index fa61c9ea61..eeffa87324 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceXdripPlugin.java @@ -1,18 +1,30 @@ package info.nightscout.androidaps.plugins.Source; +import android.content.Intent; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.services.Intents; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.interfaces.BgSourceInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.BundleLogger; /** * Created by mike on 05.08.2016. */ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { + private static Logger log = LoggerFactory.getLogger(L.BGSOURCE); private static SourceXdripPlugin plugin = null; - + boolean advancedFiltering; public static SourceXdripPlugin getPlugin() { @@ -35,6 +47,28 @@ public class SourceXdripPlugin extends PluginBase implements BgSourceInterface { return advancedFiltering; } + @Override + public void handleNewData(Intent intent) { + + if (!isEnabled(PluginType.BGSOURCE)) return; + + Bundle bundle = intent.getExtras(); + if (bundle == null) return; + + if (L.isEnabled(L.BGSOURCE)) + log.debug("Received xDrip data: " + BundleLogger.log(intent.getExtras())); + + BgReading bgReading = new BgReading(); + + bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE); + bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME); + bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP); + bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW); + String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified"); + SourceXdripPlugin.getPlugin().setSource(source); + MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP"); + } + public void setSource(String source) { this.advancedFiltering = source.contains("G5 Native"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java index 73423c0eab..401d808e60 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/Treatment.java @@ -29,8 +29,6 @@ import info.nightscout.utils.JsonHelper; @DatabaseTable(tableName = Treatment.TABLE_TREATMENTS) public class Treatment implements DataPointWithLabelInterface { - private static Logger log = LoggerFactory.getLogger(Treatment.class); - public static final String TABLE_TREATMENTS = "Treatments"; @DatabaseField(id = true) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java index e701986e89..ab2e6b4e87 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentService.java @@ -37,6 +37,7 @@ import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.utils.JsonHelper; @@ -46,7 +47,7 @@ import info.nightscout.utils.JsonHelper; */ public class TreatmentService extends OrmLiteBaseService { - private static Logger log = LoggerFactory.getLogger(TreatmentService.class); + private static Logger log = LoggerFactory.getLogger(L.DATATREATMENTS); private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledTreatmentEventPost = null; @@ -102,7 +103,8 @@ public class TreatmentService extends OrmLiteBaseService { public void onCreate() { super.onCreate(); try { - log.info("onCreate"); + if (L.isEnabled(L.DATATREATMENTS)) + log.info("onCreate"); TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); } catch (SQLException e) { log.error("Can't create database", e); @@ -121,7 +123,8 @@ public class TreatmentService extends OrmLiteBaseService { throw new RuntimeException(e); } } else { - log.info("onUpgrade"); + if (L.isEnabled(L.DATATREATMENTS)) + log.info("onUpgrade"); // this.resetFood(); } } @@ -161,10 +164,14 @@ public class TreatmentService extends OrmLiteBaseService { class PostRunnable implements Runnable { public void run() { - log.debug("Firing EventFoodChange"); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Firing EventReloadTreatmentData"); MainApp.bus().post(event); - if (DatabaseHelper.earliestDataChange != null) + if (DatabaseHelper.earliestDataChange != null) { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Firing EventNewHistoryData"); MainApp.bus().post(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); + } DatabaseHelper.earliestDataChange = null; callback.setPost(null); } @@ -252,13 +259,14 @@ public class TreatmentService extends OrmLiteBaseService { if (existingTreatment != null) { boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment); boolean sameSource = existingTreatment.source == treatment.source; - if(!equalRePumpHistory) { + if (!equalRePumpHistory) { // another treatment exists. Update it with the treatment coming from the pump - log.debug("TREATMENT: Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); long oldDate = existingTreatment.date; //preserve carbs - if(existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0){ + if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { treatment.carbs = existingTreatment.carbs; } @@ -278,13 +286,14 @@ public class TreatmentService extends OrmLiteBaseService { boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment); boolean sameSource = existingTreatment.source == treatment.source; long oldDate = existingTreatment.date; - log.debug("TREATMENT: Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); //preserve carbs - if(existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0){ + if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { treatment.carbs = existingTreatment.carbs; } - + getDao().delete(existingTreatment); // need to delete/create because date may change too existingTreatment.copyFrom(treatment); getDao().create(existingTreatment); @@ -294,7 +303,8 @@ public class TreatmentService extends OrmLiteBaseService { return new UpdateReturn(equalRePumpHistory || sameSource, false); } getDao().create(treatment); - log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment); return new UpdateReturn(true, true); @@ -308,7 +318,8 @@ public class TreatmentService extends OrmLiteBaseService { getDao().delete(old); // need to delete/create because date may change too old.copyFrom(treatment); getDao().create(old); - log.debug("TREATMENT: Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); if (historyChange) { DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(old.date); @@ -328,7 +339,8 @@ public class TreatmentService extends OrmLiteBaseService { getDao().delete(old); // need to delete/create because date may change too old.copyFrom(treatment); getDao().create(old); - log.debug("TREATMENT: Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); if (historyChange) { DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(old.date); @@ -339,14 +351,16 @@ public class TreatmentService extends OrmLiteBaseService { } } getDao().create(treatment); - log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment); return new UpdateReturn(true, true); } if (treatment.source == Source.USER) { getDao().create(treatment); - log.debug("TREATMENT: New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment); return new UpdateReturn(true, true); @@ -357,8 +371,10 @@ public class TreatmentService extends OrmLiteBaseService { return new UpdateReturn(false, false); } - /** Returns the record for the given id, null if none, throws RuntimeException - * if multiple records with the same pump id exist. */ + /** + * Returns the record for the given id, null if none, throws RuntimeException + * if multiple records with the same pump id exist. + */ @Nullable public Treatment getPumpRecordById(long pumpId) { try { @@ -368,9 +384,12 @@ public class TreatmentService extends OrmLiteBaseService { PreparedQuery preparedQuery = queryBuilder.prepare(); List result = getDao().query(preparedQuery); switch (result.size()) { - case 0: return null; - case 1: return result.get(0); - default: throw new RuntimeException("Multiple records with the same pump id found: " + result.toString()); + case 0: + return null; + case 1: + return result.get(0); + default: + throw new RuntimeException("Multiple records with the same pump id found: " + result.toString()); } } catch (SQLException e) { throw new RuntimeException(e); @@ -393,7 +412,8 @@ public class TreatmentService extends OrmLiteBaseService { private void deleteByNSId(String _id) { Treatment stored = findByNSId(_id); if (stored != null) { - log.debug("TREATMENT: Removing Treatment record from database: " + stored.toString()); + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("Removing Treatment record from database: " + stored.toString()); delete(stored); DatabaseHelper.updateEarliestDataChange(stored.date); scheduleTreatmentChange(null); @@ -480,10 +500,11 @@ public class TreatmentService extends OrmLiteBaseService { } public class UpdateReturn { - public UpdateReturn(boolean success, boolean newRecord){ + public UpdateReturn(boolean success, boolean newRecord) { this.success = success; this.newRecord = newRecord; } + boolean newRecord; boolean success; } 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 index ea75dfad6a..550522313d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/TreatmentsFragment.java @@ -27,8 +27,6 @@ import info.nightscout.androidaps.plugins.Treatments.fragments.TreatmentsTempora import info.nightscout.utils.FabricPrivacy; public class TreatmentsFragment extends SubscriberFragment implements View.OnClickListener { - private static Logger log = LoggerFactory.getLogger(TreatmentsFragment.class); - TextView treatmentsTab; TextView extendedBolusesTab; TextView tempBasalsTab; 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 b701f66afc..6e99f28c12 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 @@ -37,7 +37,9 @@ 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.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; @@ -47,7 +49,7 @@ import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.T; @@ -55,7 +57,7 @@ import info.nightscout.utils.T; * Created by mike on 05.08.2016. */ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { - private static Logger log = LoggerFactory.getLogger(TreatmentsPlugin.class); + private Logger log = LoggerFactory.getLogger(L.DATATREATMENTS); private static TreatmentsPlugin treatmentsPlugin; @@ -109,9 +111,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTreatmentData() { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("initializeTreatmentData"); double dia = Constants.defaultDIA; - if (MainApp.getConfigBuilder() != null && MainApp.getConfigBuilder().getProfile() != null) - dia = MainApp.getConfigBuilder().getProfile().getDia(); + if (MainApp.getConfigBuilder() != null && ProfileFunctions.getInstance().getProfile() != null) + dia = ProfileFunctions.getInstance().getProfile().getDia(); long fromMills = (long) (System.currentTimeMillis() - 60 * 60 * 1000L * (24 + dia)); synchronized (treatments) { treatments.clear(); @@ -120,9 +124,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTempBasalData() { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("initializeTempBasalData"); double dia = Constants.defaultDIA; - if (MainApp.getConfigBuilder() != null && MainApp.getConfigBuilder().getProfile() != null) - dia = MainApp.getConfigBuilder().getProfile().getDia(); + if (MainApp.getConfigBuilder() != null && ProfileFunctions.getInstance().getProfile() != null) + dia = ProfileFunctions.getInstance().getProfile().getDia(); long fromMills = (long) (System.currentTimeMillis() - 60 * 60 * 1000L * (24 + dia)); synchronized (tempBasals) { @@ -132,9 +138,11 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeExtendedBolusData() { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("initializeExtendedBolusData"); double dia = Constants.defaultDIA; - if (MainApp.getConfigBuilder() != null && MainApp.getConfigBuilder().getProfile() != null) - dia = MainApp.getConfigBuilder().getProfile().getDia(); + if (MainApp.getConfigBuilder() != null && ProfileFunctions.getInstance().getProfile() != null) + dia = ProfileFunctions.getInstance().getProfile().getDia(); long fromMills = (long) (System.currentTimeMillis() - 60 * 60 * 1000L * (24 + dia)); synchronized (extendedBoluses) { @@ -144,6 +152,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeTempTargetData() { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("initializeTempTargetData"); synchronized (tempTargets) { long fromMills = System.currentTimeMillis() - 60 * 60 * 1000L * 24; tempTargets.reset().add(MainApp.getDbHelper().getTemptargetsDataFromTime(fromMills, false)); @@ -151,6 +161,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface } private void initializeProfileSwitchData() { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("initializeProfileSwitchData"); synchronized (profiles) { profiles.reset().add(MainApp.getDbHelper().getProfileSwitchData(false)); } @@ -165,7 +177,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public IobTotal getCalculationToTimeTreatments(long time) { IobTotal total = new IobTotal(time); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return total; @@ -213,7 +225,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public MealData getMealData() { MealData result = new MealData(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return result; long now = System.currentTimeMillis(); @@ -294,6 +306,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface last = t.date; } } + if (L.isEnabled(L.DATATREATMENTS)) log.debug("Last bolus time: " + new Date(last).toLocaleString()); return last; } @@ -322,6 +335,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Subscribe public void onStatusEvent(final EventReloadTreatmentData ev) { + if (L.isEnabled(L.DATATREATMENTS)) log.debug("EventReloadTreatmentData"); initializeTreatmentData(); initializeExtendedBolusData(); @@ -332,6 +346,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Subscribe @SuppressWarnings("unused") public void onStatusEvent(final EventReloadTempBasalData ev) { + if (L.isEnabled(L.DATATREATMENTS)) log.debug("EventReloadTempBasalData"); initializeTempBasalData(); updateTotalIOBTempBasals(); @@ -396,7 +411,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override public void updateTotalIOBTempBasals() { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile != null) lastTempBasalsCalculation = getCalculationToTimeTempBasals(DateUtil.now(), profile); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java index 5f758c8a06..c2263d81b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java @@ -31,8 +31,6 @@ public class ProfileViewerDialog extends DialogFragment { private long time; - private static Logger log = LoggerFactory.getLogger(ProfileViewDialog.class); - @BindView(R.id.profileview_noprofile) TextView noProfile; @BindView(R.id.profileview_invalidprofile) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java index 0faceb2382..c9b744e86d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsBolusFragment.java @@ -20,14 +20,12 @@ import android.widget.TextView; import com.crashlytics.android.answers.CustomEvent; import com.squareup.otto.Subscribe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.Source; @@ -40,14 +38,12 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import static info.nightscout.utils.DateUtil.now; public class TreatmentsBolusFragment extends SubscriberFragment implements View.OnClickListener { - private static Logger log = LoggerFactory.getLogger(TreatmentsBolusFragment.class); - RecyclerView recyclerView; LinearLayoutManager llm; @@ -74,7 +70,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. @Override public void onBindViewHolder(TreatmentsViewHolder holder, int position) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return; Treatment t = treatments.get(position); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsCareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsCareportalFragment.java index 7e69883a3d..56709963f7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsCareportalFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsCareportalFragment.java @@ -22,13 +22,13 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.utils.DateUtil; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; import info.nightscout.utils.Translator; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java index 05e18bfdc3..037a1a0023 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -18,9 +18,6 @@ import android.widget.TextView; import com.crashlytics.android.answers.CustomEvent; import com.squareup.otto.Subscribe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Intervals; @@ -35,12 +32,10 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { - private static Logger log = LoggerFactory.getLogger(TreatmentsExtendedBolusesFragment.class); - RecyclerView recyclerView; LinearLayoutManager llm; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java index 307f9c8ee6..2449dff52e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -24,7 +24,8 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; @@ -33,7 +34,7 @@ import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; /** @@ -64,7 +65,7 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen @Override public void onBindViewHolder(ProfileSwitchViewHolder holder, int position) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return; ProfileSwitch profileSwitch = profileSwitchList.get(position); holder.ph.setVisibility(profileSwitch.source == Source.PUMP ? View.VISIBLE : View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java index df67349839..d60dfc9e4c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTempTargetFragment.java @@ -21,7 +21,8 @@ import com.squareup.otto.Subscribe; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; @@ -31,7 +32,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.utils.SP; /** @@ -65,7 +66,7 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements @Override public void onBindViewHolder(TempTargetsViewHolder holder, int position) { - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); TempTarget tempTarget = tempTargetList.getReversed(position); holder.ph.setVisibility(tempTarget.source == Source.PUMP ? View.VISIBLE : View.GONE); holder.ns.setVisibility(NSUpload.isIdValid(tempTarget._id) ? View.VISIBLE : View.GONE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 957c5c02f1..3185bd81ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -28,12 +28,13 @@ import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.plugins.Common.SubscriberFragment; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.utils.DateUtil; import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.FabricPrivacy; -import info.nightscout.utils.NSUpload; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { @@ -84,7 +85,7 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { } holder.duration.setText(DecimalFormatter.to0Decimal(tempBasal.durationInMinutes, " min")); if (tempBasal.isAbsolute) { - Profile profile = MainApp.getConfigBuilder().getProfile(tempBasal.date); + Profile profile = ProfileFunctions.getInstance().getProfile(tempBasal.date); if (profile != null) { holder.absolute.setText(DecimalFormatter.to0Decimal(tempBasal.tempBasalConvertedToAbsolute(tempBasal.date, profile), " U/h")); holder.percent.setText(""); @@ -99,7 +100,7 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { holder.realDuration.setText(DecimalFormatter.to0Decimal(tempBasal.getRealDuration(), " min")); long now = DateUtil.now(); IobTotal iob = new IobTotal(now); - Profile profile = MainApp.getConfigBuilder().getProfile(now); + Profile profile = ProfileFunctions.getInstance().getProfile(now); if (profile != null) iob = tempBasal.iobCalc(now, profile); holder.iob.setText(DecimalFormatter.to2Decimal(iob.basaliob, " U")); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java index fc4728c53c..84e32ca087 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/ActionStringHandler.java @@ -32,6 +32,7 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.APSResult; @@ -134,7 +135,7 @@ public class ActionStringHandler { ///////////////////////////////////////////////////////// TEMPTARGET boolean isMGDL = Boolean.parseBoolean(act[1]); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { sendError("No profile found!"); return; @@ -203,7 +204,7 @@ public class ActionStringHandler { boolean useTrend = SP.getBoolean(R.string.key_wearwizard_trend, false); int percentage = Integer.parseInt(act[2]); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { sendError("No profile found!"); return; @@ -363,7 +364,7 @@ public class ActionStringHandler { private static String generateTDDMessage(List historyList, List dummies) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { return "No profile loaded :("; @@ -517,7 +518,7 @@ public class ActionStringHandler { if (!Config.APS) { return "Targets only apply in APS mode!"; } - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { return "No profile set :("; } @@ -541,7 +542,7 @@ public class ActionStringHandler { if (!Config.APS) { return "Only apply in APS mode!"; } - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { return "No profile set :("; } @@ -651,7 +652,7 @@ public class ActionStringHandler { if (timeshift < 0 || timeshift > 23) { msg += String.format(MainApp.gs(R.string.valueoutofrange), "Profile-Timeshift") + "\n"; } - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { msg += MainApp.gs(R.string.notloadedplugins) + "\n"; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java index b5d30ad071..ce9b0e0f2f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/WatchUpdaterService.java @@ -37,6 +37,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Treatments.Treatment; @@ -223,7 +224,7 @@ public class WatchUpdaterService extends WearableListenerService implements } private DataMap dataMapSingleBG(BgReading lastBG, GlucoseStatus glucoseStatus) { - String units = MainApp.getConfigBuilder().getProfileUnits(); + String units = ProfileFunctions.getInstance().getProfileUnits(); Double lowLine = SafeParse.stringToDouble(mPrefs.getString("low_mark", "0")); Double highLine = SafeParse.stringToDouble(mPrefs.getString("high_mark", "0")); @@ -363,7 +364,7 @@ public class WatchUpdaterService extends WearableListenerService implements ArrayList predictions = new ArrayList<>(); - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) { return; @@ -383,7 +384,7 @@ public class WatchUpdaterService extends WearableListenerService implements if (tb1 != null) { tb_before = beginBasalValue; - Profile profileTB = MainApp.getConfigBuilder().getProfile(runningTime); + Profile profileTB = ProfileFunctions.getInstance().getProfile(runningTime); if (profileTB != null) { tb_amount = tb1.tempBasalConvertedToAbsolute(runningTime, profileTB); tb_start = runningTime; @@ -392,7 +393,7 @@ public class WatchUpdaterService extends WearableListenerService implements for (; runningTime < now; runningTime += 5 * 60 * 1000) { - Profile profileTB = MainApp.getConfigBuilder().getProfile(runningTime); + Profile profileTB = ProfileFunctions.getInstance().getProfile(runningTime); //basal rate endBasalValue = profile.getBasal(runningTime); if (endBasalValue != beginBasalValue) { @@ -444,7 +445,7 @@ public class WatchUpdaterService extends WearableListenerService implements temps.add(tempDatamap(tb_start, tb_before, now - 1 * 60 * 1000, endBasalValue, tb_amount)); } else { //express currently running temp by painting it a bit into the future - Profile profileNow = MainApp.getConfigBuilder().getProfile(now); + Profile profileNow = ProfileFunctions.getInstance().getProfile(now); double currentAmount = tb2.tempBasalConvertedToAbsolute(now, profileNow); if (currentAmount != tb_amount) { temps.add(tempDatamap(tb_start, tb_before, now, tb_amount, tb_amount)); @@ -457,7 +458,7 @@ public class WatchUpdaterService extends WearableListenerService implements tb2 = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); //use "now" to express current situation if (tb2 != null) { //onset at the end - Profile profileTB = MainApp.getConfigBuilder().getProfile(runningTime); + Profile profileTB = ProfileFunctions.getInstance().getProfile(runningTime); double currentAmount = tb2.tempBasalConvertedToAbsolute(runningTime, profileTB); temps.add(tempDatamap(now - 1 * 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)); } @@ -580,7 +581,7 @@ public class WatchUpdaterService extends WearableListenerService implements private void sendStatus() { if (googleApiClient.isConnected()) { - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); String status = MainApp.gs(R.string.noprofile); String iobSum, iobDetail, cobString, currentBasal, bgiString; iobSum = iobDetail = cobString = currentBasal = bgiString = ""; @@ -699,7 +700,7 @@ public class WatchUpdaterService extends WearableListenerService implements String basalStringResult; - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (profile == null) return ""; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java index d5ac60a626..bc879bc2a7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/XDripStatusline/StatuslinePlugin.java @@ -25,6 +25,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; @@ -93,7 +94,7 @@ public class StatuslinePlugin extends PluginBase { private void sendStatus() { String status = ""; // sent once on disable - Profile profile = MainApp.getConfigBuilder().getProfile(); + Profile profile = ProfileFunctions.getInstance().getProfile(); if (isEnabled(PluginType.GENERAL) && profile != null) { status = buildStatusString(profile); 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 47fe4acd6a..f98f86d8fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -20,7 +20,9 @@ import info.nightscout.androidaps.data.PumpEnactResult; 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.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressHelperActivity; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; @@ -75,10 +77,10 @@ import info.nightscout.androidaps.queue.commands.CommandTempBasalPercent; */ public class CommandQueue { - private static Logger log = LoggerFactory.getLogger(CommandQueue.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); private final LinkedList queue = new LinkedList<>(); - protected Command performing; + Command performing; private QueueThread thread = null; @@ -109,12 +111,14 @@ public class CommandQueue { private synchronized void inject(Command command) { // inject as a first command - log.debug("QUEUE: Adding as first: " + command.getClass().getSimpleName() + " - " + command.status()); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Adding as first: " + command.getClass().getSimpleName() + " - " + command.status()); queue.addFirst(command); } private synchronized void add(Command command) { - log.debug("QUEUE: Adding: " + command.getClass().getSimpleName() + " - " + command.status()); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Adding: " + command.getClass().getSimpleName() + " - " + command.status()); queue.add(command); } @@ -147,15 +151,18 @@ public class CommandQueue { // start thread again if not already running protected synchronized void notifyAboutNewCommand() { while (thread != null && thread.getState() != Thread.State.TERMINATED && thread.waitingForDisconnect) { - log.debug("QUEUE: Waiting for previous thread finish"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Waiting for previous thread finish"); SystemClock.sleep(500); } if (thread == null || thread.getState() == Thread.State.TERMINATED) { thread = new QueueThread(this); thread.start(); - log.debug("QUEUE: Starting new thread"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Starting new thread"); } else { - log.debug("QUEUE: Thread is already running"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Thread is already running"); } } @@ -164,8 +171,8 @@ public class CommandQueue { tempCommandQueue.readStatus(reason, callback); } - public synchronized boolean bolusInQueue(){ - if(isRunning(Command.CommandType.BOLUS)) return true; + public synchronized boolean bolusInQueue() { + if (isRunning(Command.CommandType.BOLUS)) return true; for (int i = 0; i < queue.size(); i++) { if (queue.get(i).commandType == Command.CommandType.BOLUS) { return true; @@ -180,17 +187,19 @@ public class CommandQueue { if (type == Command.CommandType.SMB_BOLUS) { if (isRunning(Command.CommandType.BOLUS) || bolusInQueue()) { - log.debug("Rejecting SMB since a bolus is queue/running"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Rejecting SMB since a bolus is queue/running"); return false; } if (detailedBolusInfo.lastKnownBolusTime < TreatmentsPlugin.getPlugin().getLastBolusTime()) { - log.debug("Rejecting bolus, another bolus was issued since request time"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Rejecting bolus, another bolus was issued since request time"); return false; } } - if(type.equals(Command.CommandType.BOLUS) && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0){ + if (type.equals(Command.CommandType.BOLUS) && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0) { type = Command.CommandType.CARBS_ONLY_TREATMENT; //Carbs only can be added in parallel as they can be "in the future". } else { @@ -213,7 +222,7 @@ public class CommandQueue { add(new CommandSMBBolus(detailedBolusInfo, callback)); } else { add(new CommandBolus(detailedBolusInfo, callback, type)); - if(type.equals(Command.CommandType.BOLUS)) { + if (type.equals(Command.CommandType.BOLUS)) { // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested, // not when the Bolus command is starting. The command closes the dialog upon completion). showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context); @@ -337,7 +346,8 @@ public class CommandQueue { // returns true if command is queued public boolean setProfile(Profile profile, Callback callback) { if (isThisProfileSet(profile)) { - log.debug("QUEUE: Correct profile already set"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Correct profile already set"); if (callback != null) callback.result(new PumpEnactResult().success(true).enacted(false)).run(); return false; @@ -381,7 +391,8 @@ public class CommandQueue { // returns true if command is queued public boolean readStatus(String reason, Callback callback) { if (isLastScheduled(Command.CommandType.READSTATUS)) { - log.debug("QUEUE: READSTATUS " + reason + " ignored as duplicated"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("READSTATUS " + reason + " ignored as duplicated"); if (callback != null) callback.result(executingNowError()).run(); return false; @@ -492,12 +503,14 @@ public class CommandQueue { public boolean isThisProfileSet(Profile profile) { PumpInterface activePump = ConfigBuilderPlugin.getActivePump(); - Profile current = MainApp.getConfigBuilder().getProfile(); + Profile current = ProfileFunctions.getInstance().getProfile(); if (activePump != null && current != null) { boolean result = activePump.isThisProfileSet(profile); if (!result) { - log.debug("Current profile: " + current.getData().toString()); - log.debug("New profile: " + profile.getData().toString()); + if (L.isEnabled(L.PUMPQUEUE)) { + log.debug("Current profile: " + current.toString()); + log.debug("New profile: " + profile.toString()); + } } return result; } else return true; diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index a5ad59ca0b..83414b23fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -11,13 +11,11 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning; -import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.queue.events.EventQueueChanged; import info.nightscout.utils.SP; @@ -26,7 +24,7 @@ import info.nightscout.utils.SP; */ public class QueueThread extends Thread { - private static Logger log = LoggerFactory.getLogger(QueueThread.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); private CommandQueue queue; @@ -54,7 +52,8 @@ public class QueueThread extends Thread { while (true) { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (pump == null) { - log.debug("QUEUE: pump == null"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("pump == null"); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.pumpNotInitialized))); SystemClock.sleep(1000); continue; @@ -64,15 +63,17 @@ public class QueueThread extends Thread { if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { MainApp.bus().post(new EventDismissBolusprogressIfRunning(null)); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout))); - log.debug("QUEUE: timed out"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("timed out"); pump.stopConnecting(); //BLUETOOTH-WATCHDOG boolean watchdog = SP.getBoolean(R.string.key_btwatchdog, false); long last_watchdog = SP.getLong(R.string.key_btwatchdog_lastbark, 0l); watchdog = watchdog && System.currentTimeMillis() - last_watchdog > (Constants.MIN_WATCHDOG_INTERVAL_IN_SECONDS * 1000); - if(watchdog) { - log.debug("BT watchdog - toggeling the phonest bluetooth"); + if (watchdog) { + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("BT watchdog - toggeling the phonest bluetooth"); //write time SP.putLong(R.string.key_btwatchdog_lastbark, System.currentTimeMillis()); //toggle BT @@ -91,7 +92,8 @@ public class QueueThread extends Thread { pump.connect("watchdog"); } else { queue.clear(); - log.debug("QUEUE: no connection possible"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("no connection possible"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); pump.disconnect("Queue empty"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); @@ -100,7 +102,8 @@ public class QueueThread extends Thread { } if (pump.isConnecting()) { - log.debug("QUEUE: connecting " + secondsElapsed); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("connecting " + secondsElapsed); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); SystemClock.sleep(1000); continue; @@ -108,7 +111,8 @@ public class QueueThread extends Thread { if (!pump.isConnected()) { - log.debug("QUEUE: connect"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("connect"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); pump.connect("Connection needed"); SystemClock.sleep(1000); @@ -118,12 +122,14 @@ public class QueueThread extends Thread { if (queue.performing() == null) { if (!connectLogged) { connectLogged = true; - log.debug("QUEUE: connection time " + secondsElapsed + "s"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("connection time " + secondsElapsed + "s"); } // Pickup 1st command and set performing variable if (queue.size() > 0) { queue.pickup(); - log.debug("QUEUE: performing " + queue.performing().status()); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("performing " + queue.performing().status()); MainApp.bus().post(new EventQueueChanged()); queue.performing().execute(); queue.resetPerforming(); @@ -138,14 +144,17 @@ public class QueueThread extends Thread { long secondsFromLastCommand = (System.currentTimeMillis() - lastCommandTime) / 1000; if (secondsFromLastCommand >= 5) { waitingForDisconnect = true; - log.debug("QUEUE: queue empty. disconnect"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("queue empty. disconnect"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); pump.disconnect("Queue empty"); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); - log.debug("QUEUE: disconnected"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("disconnected"); return; } else { - log.debug("QUEUE: waiting for disconnect"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("waiting for disconnect"); SystemClock.sleep(1000); } } @@ -154,6 +163,4 @@ public class QueueThread extends Thread { mWakeLock.release(); } } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java index 7156a72f25..7207f5b8d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/Command.java @@ -1,14 +1,20 @@ package info.nightscout.androidaps.queue.commands; +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.logging.L; import info.nightscout.androidaps.queue.Callback; /** * Created by mike on 09.11.2017. */ public abstract class Command { + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + public enum CommandType { BOLUS, SMB_BOLUS, @@ -33,6 +39,8 @@ public abstract class Command { PumpEnactResult result = new PumpEnactResult(); result.success = false; result.comment = MainApp.gs(R.string.connectiontimedout); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result cancel"); if (callback != null) callback.result(result).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java index 2be3831ace..7e17e831e9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java @@ -1,8 +1,12 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning; @@ -14,7 +18,9 @@ import info.nightscout.utils.DecimalFormatter; */ public class CommandBolus extends Command { - DetailedBolusInfo detailedBolusInfo; + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + + private DetailedBolusInfo detailedBolusInfo; public CommandBolus(DetailedBolusInfo detailedBolusInfo, Callback callback, CommandType type) { commandType = type; @@ -28,6 +34,8 @@ public class CommandBolus extends Command { BolusProgressDialog.bolusEnded = true; MainApp.bus().post(new EventDismissBolusprogressIfRunning(r)); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java index 536c2d876c..164a049647 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelExtendedBolus.java @@ -3,9 +3,8 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -14,7 +13,7 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandCancelExtendedBolus extends Command { - private static Logger log = LoggerFactory.getLogger(CommandCancelExtendedBolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); public CommandCancelExtendedBolus(Callback callback) { commandType = CommandType.EXTENDEDBOLUS; @@ -24,8 +23,8 @@ public class CommandCancelExtendedBolus extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().cancelExtendedBolus(); - if (Config.logCongigBuilderActions) - log.debug("cancelExtendedBolus success: " + r.success + " enacted: " + r.enacted); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java index d2496c871a..5daa0e38e4 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandCancelTempBasal.java @@ -1,7 +1,10 @@ package info.nightscout.androidaps.queue.commands; -import info.nightscout.androidaps.MainApp; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -10,7 +13,9 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandCancelTempBasal extends Command { - boolean enforceNew; + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + + private boolean enforceNew; public CommandCancelTempBasal(boolean enforceNew, Callback callback) { commandType = CommandType.TEMPBASAL; @@ -21,6 +26,8 @@ public class CommandCancelTempBasal extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().cancelTempBasal(enforceNew); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java index 0641d9139d..ea329c04d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandExtendedBolus.java @@ -3,9 +3,8 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -14,7 +13,7 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandExtendedBolus extends Command { - private static Logger log = LoggerFactory.getLogger(CommandExtendedBolus.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); private double insulin; private int durationInMinutes; @@ -29,8 +28,8 @@ public class CommandExtendedBolus extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setExtendedBolus(insulin, durationInMinutes); - if (Config.logCongigBuilderActions) - log.debug("setExtendedBolus rate: " + insulin + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result rate: " + insulin + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java index 2d6bc5b5fc..5cc954f5ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadEvents.java @@ -1,8 +1,12 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.DanaRInterface; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -11,6 +15,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandLoadEvents extends Command { + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + public CommandLoadEvents(Callback callback) { commandType = CommandType.LOADEVENTS; this.callback = callback; @@ -22,6 +28,8 @@ public class CommandLoadEvents extends Command { if (pump instanceof DanaRInterface) { DanaRInterface danaPump = (DanaRInterface) pump; PumpEnactResult r = danaPump.loadEvents(); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java index 16e9a18048..1259812676 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadHistory.java @@ -1,18 +1,23 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.DanaRInterface; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.queue.commands.Command; /** * Created by mike on 10.11.2017. */ public class CommandLoadHistory extends Command { - byte type; + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + + private byte type; public CommandLoadHistory(byte type, Callback callback) { commandType = CommandType.LOADHISTORY; @@ -26,6 +31,8 @@ public class CommandLoadHistory extends Command { if (pump instanceof DanaRInterface) { DanaRInterface danaPump = (DanaRInterface) pump; PumpEnactResult r = danaPump.loadHistory(type); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java index 363781a379..1212303e82 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandLoadTDDs.java @@ -1,7 +1,11 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -10,6 +14,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandLoadTDDs extends Command { + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + public CommandLoadTDDs(Callback callback) { commandType = CommandType.LOADHISTORY; //belongs to the history group of commands @@ -20,9 +26,11 @@ public class CommandLoadTDDs extends Command { public void execute() { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); PumpEnactResult r = pump.loadTDDs(); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); - } + } @Override public String status() { diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java index 44c778c5f7..b014b66969 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.java @@ -1,5 +1,9 @@ package info.nightscout.androidaps.queue.commands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.LocalAlertUtils; @@ -9,7 +13,9 @@ import info.nightscout.utils.LocalAlertUtils; */ public class CommandReadStatus extends Command { - String reason; + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + + private String reason; public CommandReadStatus(String reason, Callback callback) { commandType = CommandType.READSTATUS; @@ -21,6 +27,8 @@ public class CommandReadStatus extends Command { public void execute() { ConfigBuilderPlugin.getActivePump().getPumpStatus(); LocalAlertUtils.notifyPumpStatusRead(); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("CommandReadStatus executed. Reason: " + reason); if (callback != null) callback.result(null).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java index 46336f7d4b..affc7aed22 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.java @@ -3,12 +3,10 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.Overview.Dialogs.BolusProgressDialog; -import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.utils.DateUtil; @@ -20,8 +18,9 @@ import info.nightscout.utils.T; */ public class CommandSMBBolus extends Command { - private static Logger log = LoggerFactory.getLogger(CommandSMBBolus.class); - DetailedBolusInfo detailedBolusInfo; + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + + private DetailedBolusInfo detailedBolusInfo; public CommandSMBBolus(DetailedBolusInfo detailedBolusInfo, Callback callback) { commandType = CommandType.SMB_BOLUS; @@ -34,20 +33,25 @@ public class CommandSMBBolus extends Command { PumpEnactResult r; long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); if (lastBolusTime != 0 && lastBolusTime + T.mins(3).msecs() > DateUtil.now()) { - log.debug("SMB requsted but still in 3 min interval"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("SMB requsted but still in 3 min interval"); r = new PumpEnactResult().enacted(false).success(false).comment("SMB requsted but still in 3 min interval"); - } else if (detailedBolusInfo.deliverAt != 0 && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) + } else if (detailedBolusInfo.deliverAt != 0 && detailedBolusInfo.deliverAt + T.mins(1).msecs() > System.currentTimeMillis()) { r = ConfigBuilderPlugin.getActivePump().deliverTreatment(detailedBolusInfo); - else { + } else { r = new PumpEnactResult().enacted(false).success(false).comment("SMB request too old"); - log.debug("SMB bolus canceled. delivetAt=" + detailedBolusInfo.deliverAt + " now=" + System.currentTimeMillis()); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("SMB bolus canceled. delivetAt: " + DateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)); } + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); + if (callback != null) callback.result(r).run(); } public String status() { - return "SMBBOLUS " + DecimalFormatter.to1Decimal(detailedBolusInfo.insulin) + "U"; + return "SMBBOLUS " + DecimalFormatter.to2Decimal(detailedBolusInfo.insulin) + "U"; } } 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 03764dee0b..b62ef576d3 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 @@ -10,6 +10,7 @@ import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; @@ -20,7 +21,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandSetProfile extends Command { - private static Logger log = LoggerFactory.getLogger(CommandSetProfile.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + private Profile profile; public CommandSetProfile(Profile profile, Callback callback) { @@ -32,13 +34,16 @@ public class CommandSetProfile extends Command { @Override public void execute() { if (ConfigBuilderPlugin.getCommandQueue().isThisProfileSet(profile)) { - log.debug("QUEUE: Correct profile already set"); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Correct profile already set. profile: " + profile.toString()); if (callback != null) callback.result(new PumpEnactResult().success(true).enacted(false)).run(); return; } PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setNewBasalProfile(profile); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted + " profile: " + profile.toString()); if (callback != null) callback.result(r).run(); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java index f3d9fe2a4b..8a9ae21c70 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetUserSettings.java @@ -3,13 +3,11 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.queue.Callback; /** @@ -17,7 +15,8 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandSetUserSettings extends Command { - private static Logger log = LoggerFactory.getLogger(CommandSetUserSettings.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); + public CommandSetUserSettings(Callback callback) { commandType = CommandType.SETUSERSETTINGS; this.callback = callback; @@ -28,11 +27,9 @@ public class CommandSetUserSettings extends Command { PumpInterface pump = ConfigBuilderPlugin.getActivePump(); if (pump instanceof DanaRInterface) { DanaRInterface danaPump = (DanaRInterface) pump; - boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); - if(isDanaRv2){ - log.debug("MsgSetUserOptions detected for DanaRv2"); - } PumpEnactResult r = danaPump.setUserOptions(); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java index 35c2435558..a2787cabb6 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalAbsolute.java @@ -3,10 +3,9 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -15,12 +14,12 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandTempBasalAbsolute extends Command { - private static Logger log = LoggerFactory.getLogger(CommandTempBasalAbsolute.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - int durationInMinutes; - double absoluteRate; - boolean enforceNew; - Profile profile; + private int durationInMinutes; + private double absoluteRate; + private boolean enforceNew; + private Profile profile; public CommandTempBasalAbsolute(double absoluteRate, int durationInMinutes, boolean enforceNew, Profile profile, Callback callback) { commandType = CommandType.TEMPBASAL; @@ -34,8 +33,8 @@ public class CommandTempBasalAbsolute extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setTempBasalAbsolute(absoluteRate, durationInMinutes, profile, enforceNew); - if (Config.logCongigBuilderActions) - log.debug("setTempBasalAbsolute rate: " + absoluteRate + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result rate: " + absoluteRate + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java index bbb421e128..efdfca0a69 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandTempBasalPercent.java @@ -3,9 +3,9 @@ package info.nightscout.androidaps.queue.commands; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Config; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.queue.Callback; @@ -14,12 +14,12 @@ import info.nightscout.androidaps.queue.Callback; */ public class CommandTempBasalPercent extends Command { - private static Logger log = LoggerFactory.getLogger(CommandTempBasalPercent.class); + private Logger log = LoggerFactory.getLogger(L.PUMPQUEUE); - int durationInMinutes; - int percent; - boolean enforceNew; - Profile profile; + private int durationInMinutes; + private int percent; + private boolean enforceNew; + private Profile profile; public CommandTempBasalPercent(int percent, int durationInMinutes, boolean enforceNew, Profile profile, Callback callback) { commandType = CommandType.TEMPBASAL; @@ -33,8 +33,8 @@ public class CommandTempBasalPercent extends Command { @Override public void execute() { PumpEnactResult r = ConfigBuilderPlugin.getActivePump().setTempBasalPercent(percent, durationInMinutes, profile, enforceNew); - if (Config.logCongigBuilderActions) - log.debug("setTempBasalPercent percent: " + percent + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); + if (L.isEnabled(L.PUMPQUEUE)) + log.debug("Result percent: " + percent + " durationInMinutes: " + durationInMinutes + " success: " + r.success + " enacted: " + r.enacted); if (callback != null) callback.result(r).run(); } diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.java index aa767bb154..087cd3a5f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/DataReceiver.java @@ -7,15 +7,15 @@ import android.support.v4.content.WakefulBroadcastReceiver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.Services.DataService; -import info.nightscout.androidaps.Config; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.services.DataService; public class DataReceiver extends WakefulBroadcastReceiver { - private static Logger log = LoggerFactory.getLogger(DataReceiver.class); + private static Logger log = LoggerFactory.getLogger(L.DATASERVICE); @Override public void onReceive(Context context, Intent intent) { - if (Config.logFunctionCalls) + if (L.isEnabled(L.DATASERVICE)) log.debug("onReceive " + intent); startWakefulService(context, new Intent(context, DataService.class) .setAction(intent.getAction()) diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index d574b08f40..9268198aca 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -7,7 +7,6 @@ import android.content.Context; import android.content.Intent; import android.os.PowerManager; -import info.nightscout.utils.FabricPrivacy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,11 +14,14 @@ import java.util.Date; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.queue.commands.Command; +import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.LocalAlertUtils; @@ -27,7 +29,7 @@ import info.nightscout.utils.LocalAlertUtils; * Created by mike on 07.07.2016. */ public class KeepAliveReceiver extends BroadcastReceiver { - private static Logger log = LoggerFactory.getLogger(KeepAliveReceiver.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); public static final long STATUS_UPDATE_FREQUENCY = 15 * 60 * 1000L; public static void cancelAlarm(Context context) { @@ -48,13 +50,14 @@ public class KeepAliveReceiver extends BroadcastReceiver { checkPump(); FabricPrivacy.uploadDailyStats(); - log.debug("KeepAlive received"); + if (L.isEnabled(L.CORE)) + log.debug("KeepAlive received"); wl.release(); } private void checkPump() { final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); if (pump != null && profile != null) { Date lastConnection = pump.lastDataTime(); boolean isStatusOutdated = lastConnection.getTime() + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis(); diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/NSAlarmReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/NSAlarmReceiver.java index 95bb5e17b3..d167bb9510 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/NSAlarmReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/NSAlarmReceiver.java @@ -11,14 +11,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.Services.Intents; +import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSAlarm; -import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.services.Intents; public class NSAlarmReceiver extends BroadcastReceiver { - private static Logger log = LoggerFactory.getLogger(NSAlarmReceiver.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); @Override public void onReceive(Context context, Intent intent) { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java index a8bd49f430..9a3108e98c 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java @@ -15,10 +15,11 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.EventNetworkChange; +import info.nightscout.androidaps.logging.L; public class NetworkChangeReceiver extends BroadcastReceiver { - private static Logger log = LoggerFactory.getLogger(NetworkChangeReceiver.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); @Override public void onReceive(final Context context, final Intent intent) { @@ -44,17 +45,20 @@ public class NetworkChangeReceiver extends BroadcastReceiver { if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) { event.ssid = wifiInfo.getSSID(); } - log.debug("NETCHANGE: Wifi connected. SSID: " + event.ssid); + if (L.isEnabled(L.CORE)) + log.debug("NETCHANGE: Wifi connected. SSID: " + event.ssid); } } if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { event.mobileConnected = true; event.roaming = activeNetwork.isRoaming(); - log.debug("NETCHANGE: Mobile connected. Roaming: " + event.roaming); + if (L.isEnabled(L.CORE)) + log.debug("NETCHANGE: Mobile connected. Roaming: " + event.roaming); } } else { - log.debug("NETCHANGE: Disconnected."); + if (L.isEnabled(L.CORE)) + log.debug("NETCHANGE: Disconnected."); } return event; diff --git a/app/src/main/java/info/nightscout/androidaps/Services/AlarmSoundService.java b/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.java similarity index 81% rename from app/src/main/java/info/nightscout/androidaps/Services/AlarmSoundService.java rename to app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.java index f453b04d36..43fbae83eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/AlarmSoundService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.Services; +package info.nightscout.androidaps.services; import android.app.Service; import android.content.Context; @@ -15,9 +15,10 @@ import java.io.IOException; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.L; public class AlarmSoundService extends Service { - private static Logger log = LoggerFactory.getLogger(AlarmSoundService.class); + private static Logger log = LoggerFactory.getLogger(L.ALARM); MediaPlayer player; int resourceId = R.raw.error; @@ -34,13 +35,15 @@ public class AlarmSoundService extends Service { @Override public void onCreate() { super.onCreate(); - log.debug("onCreate"); + if (L.isEnabled(L.ALARM)) + log.debug("onCreate"); } public int onStartCommand(Intent intent, int flags, int startId) { if (player != null && player.isPlaying()) player.stop(); - log.debug("onStartCommand"); + if (L.isEnabled(L.ALARM)) + log.debug("onStartCommand"); if (intent != null && intent.hasExtra("soundid")) resourceId = intent.getIntExtra("soundid", R.raw.error); @@ -55,7 +58,7 @@ public class AlarmSoundService extends Service { log.error("Unhandled exception", e); } player.setLooping(true); // Set looping - AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE); + AudioManager manager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); if (manager == null || !manager.isMusicActive()) { player.setVolume(100, 100); } @@ -74,5 +77,7 @@ public class AlarmSoundService extends Service { public void onDestroy() { player.stop(); player.release(); + if (L.isEnabled(L.ALARM)) + log.debug("onDestroy"); } } diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java new file mode 100644 index 0000000000..c0cfe07370 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -0,0 +1,260 @@ +package info.nightscout.androidaps.services; + +import android.app.IntentService; +import android.content.Intent; +import android.os.Bundle; +import android.provider.Telephony; + +import org.json.JSONArray; +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.db.CareportalEvent; +import info.nightscout.androidaps.events.EventNsFood; +import info.nightscout.androidaps.events.EventNsTreatment; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg; +import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; +import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.Overview.notifications.Notification; +import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; +import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; +import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin; +import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; +import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin; +import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin; +import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin; +import info.nightscout.androidaps.plugins.Source.SourcePoctechPlugin; +import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin; +import info.nightscout.androidaps.receivers.DataReceiver; +import info.nightscout.androidaps.logging.BundleLogger; +import info.nightscout.utils.JsonHelper; +import info.nightscout.utils.SP; + + +public class DataService extends IntentService { + private Logger log = LoggerFactory.getLogger(L.DATASERVICE); + + public DataService() { + super("DataService"); + registerBus(); + } + + @Override + protected void onHandleIntent(final Intent intent) { + if (L.isEnabled(L.DATASERVICE)) { + log.debug("onHandleIntent " + intent); + log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras())); + } + + boolean acceptNSData = !SP.getBoolean(R.string.key_ns_upload_only, false); + Bundle bundles = intent.getExtras(); + if (bundles != null && bundles.containsKey("islocal")) { + acceptNSData = acceptNSData || bundles.getBoolean("islocal"); + } + + + final String action = intent.getAction(); + if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { + SourceXdripPlugin.getPlugin().handleNewData(intent); + } else if (Intents.NS_EMULATOR.equals(action)) { + SourceMM640gPlugin.getPlugin().handleNewData(intent); + } else if (Intents.GLIMP_BG.equals(action)) { + SourceGlimpPlugin.getPlugin().handleNewData(intent); + } else if (Intents.DEXCOMG5_BG.equals(action)) { + SourceDexcomG5Plugin.getPlugin().handleNewData(intent); + } else if (Intents.POCTECH_BG.equals(action)) { + SourcePoctechPlugin.getPlugin().handleNewData(intent); + } else if (Intents.ACTION_NEW_SGV.equals(action)) { + SourceNSClientPlugin.getPlugin().handleNewData(intent); + } else if (Intents.ACTION_NEW_PROFILE.equals(action)) { + // always handle Profile if NSProfile is enabled without looking at nsUploadOnly + NSProfilePlugin.getPlugin().handleNewData(intent); + } else if (Intents.ACTION_NEW_DEVICESTATUS.equals(action)) { + NSDeviceStatus.getInstance().handleNewData(intent); + } else if (Intents.ACTION_NEW_STATUS.equals(action)) { + NSSettingsStatus.getInstance().handleNewData(intent); + } else if (Intents.ACTION_NEW_FOOD.equals(action)) { + EventNsFood evt = new EventNsFood(EventNsFood.ADD, bundles); + MainApp.bus().post(evt); + } else if (Intents.ACTION_CHANGED_FOOD.equals(action)) { + EventNsFood evt = new EventNsFood(EventNsFood.UPDATE, bundles); + MainApp.bus().post(evt); + } else if (Intents.ACTION_REMOVED_FOOD.equals(action)) { + EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles); + MainApp.bus().post(evt); + } else if (acceptNSData && + (Intents.ACTION_NEW_TREATMENT.equals(action) || + Intents.ACTION_CHANGED_TREATMENT.equals(action) || + Intents.ACTION_REMOVED_TREATMENT.equals(action) || + Intents.ACTION_NEW_CAL.equals(action) || + Intents.ACTION_NEW_MBG.equals(action)) + ) { + handleNewDataFromNSClient(intent); + } else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) { + SmsCommunicatorPlugin.getPlugin().handleNewData(intent); + } + + if (L.isEnabled(L.DATASERVICE)) + log.debug("onHandleIntent exit " + intent); + DataReceiver.completeWakefulIntent(intent); + } + + @Override + public void onDestroy() { + super.onDestroy(); + MainApp.bus().unregister(this); + } + + private void registerBus() { + try { + MainApp.bus().unregister(this); + } catch (RuntimeException x) { + // Ignore + } + MainApp.bus().register(this); + } + + private void handleNewDataFromNSClient(Intent intent) { + Bundle bundles = intent.getExtras(); + if (bundles == null) return; + if (L.isEnabled(L.DATASERVICE)) + log.debug("Got intent: " + intent.getAction()); + + + if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) { + try { + if (bundles.containsKey("treatment")) { + JSONObject json = new JSONObject(bundles.getString("treatment")); + handleTreatmentFromNS(json, intent); + } + if (bundles.containsKey("treatments")) { + String trstring = bundles.getString("treatments"); + JSONArray jsonArray = new JSONArray(trstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + handleTreatmentFromNS(json, intent); + } + } + } catch (JSONException e) { + log.error("Unhandled exception", e); + } + } + + if (intent.getAction().equals(Intents.ACTION_REMOVED_TREATMENT)) { + try { + if (bundles.containsKey("treatment")) { + String trstring = bundles.getString("treatment"); + JSONObject json = new JSONObject(trstring); + handleRemovedTreatmentFromNS(json); + } + + if (bundles.containsKey("treatments")) { + String trstring = bundles.getString("treatments"); + JSONArray jsonArray = new JSONArray(trstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject json = jsonArray.getJSONObject(i); + handleRemovedTreatmentFromNS(json); + } + } + } catch (JSONException e) { + log.error("Unhandled exception", e); + } + } + + if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) { + try { + if (bundles.containsKey("mbg")) { + String mbgstring = bundles.getString("mbg"); + JSONObject mbgJson = new JSONObject(mbgstring); + storeMbg(mbgJson); + } + + if (bundles.containsKey("mbgs")) { + String sgvstring = bundles.getString("mbgs"); + JSONArray jsonArray = new JSONArray(sgvstring); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject mbgJson = jsonArray.getJSONObject(i); + storeMbg(mbgJson); + } + } + } catch (Exception e) { + log.error("Unhandled exception", e); + } + } + } + + private void handleRemovedTreatmentFromNS(JSONObject json) { + // new DB model + EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json); + MainApp.bus().post(evtTreatment); + // old DB model + String _id = JsonHelper.safeGetString(json, "_id"); + MainApp.getDbHelper().deleteTempTargetById(_id); + MainApp.getDbHelper().deleteTempBasalById(_id); + MainApp.getDbHelper().deleteExtendedBolusById(_id); + MainApp.getDbHelper().deleteCareportalEventById(_id); + MainApp.getDbHelper().deleteProfileSwitchById(_id); + } + + private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException { + // new DB model + int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE; + double insulin = JsonHelper.safeGetDouble(json, "insulin"); + double carbs = JsonHelper.safeGetDouble(json, "carbs"); + String eventType = JsonHelper.safeGetString(json, "eventType"); + if (insulin > 0 || carbs > 0) { + EventNsTreatment evtTreatment = new EventNsTreatment(mode, json); + MainApp.bus().post(evtTreatment); + } else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) { + // old DB model + MainApp.getDbHelper().updateDanaRHistoryRecordId(json); + } else if (eventType.equals(CareportalEvent.TEMPORARYTARGET)) { + MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.TEMPBASAL)) { + MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.COMBOBOLUS)) { + MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.PROFILESWITCH)) { + MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(json); + } else if (eventType.equals(CareportalEvent.SITECHANGE) || + eventType.equals(CareportalEvent.INSULINCHANGE) || + eventType.equals(CareportalEvent.SENSORCHANGE) || + eventType.equals(CareportalEvent.BGCHECK) || + eventType.equals(CareportalEvent.NOTE) || + eventType.equals(CareportalEvent.NONE) || + eventType.equals(CareportalEvent.ANNOUNCEMENT) || + eventType.equals(CareportalEvent.QUESTION) || + eventType.equals(CareportalEvent.EXERCISE) || + eventType.equals(CareportalEvent.OPENAPSOFFLINE) || + eventType.equals(CareportalEvent.PUMPBATTERYCHANGE)) { + MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json); + } + + if (eventType.equals(CareportalEvent.ANNOUNCEMENT)) { + long date = JsonHelper.safeGetLong(json, "mills"); + long now = System.currentTimeMillis(); + 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"))) { + Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60); + MainApp.bus().post(new EventNewNotification(announcement)); + } + } + } + + private void storeMbg(JSONObject mbgJson) { + 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.log()); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/Services/Intents.java b/app/src/main/java/info/nightscout/androidaps/services/Intents.java similarity index 98% rename from app/src/main/java/info/nightscout/androidaps/Services/Intents.java rename to app/src/main/java/info/nightscout/androidaps/services/Intents.java index 25485fb34d..6d3daf1ea9 100644 --- a/app/src/main/java/info/nightscout/androidaps/Services/Intents.java +++ b/app/src/main/java/info/nightscout/androidaps/services/Intents.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.Services; +package info.nightscout.androidaps.services; public interface Intents { // NSClient -> App 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 c1669b73d0..433c3927db 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java @@ -1,13 +1,8 @@ package info.nightscout.androidaps.setupwizard; import android.Manifest; -import android.content.ActivityNotFoundException; -import android.content.Context; import android.content.Intent; -import android.net.Uri; import android.os.Build; -import android.os.PowerManager; -import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import com.squareup.otto.Subscribe; @@ -21,7 +16,7 @@ import java.util.List; import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.PreferencesActivity; +import info.nightscout.androidaps.activities.PreferencesActivity; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; @@ -32,6 +27,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesFragment; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; @@ -59,7 +55,6 @@ import info.nightscout.utils.ImportExportPrefs; import info.nightscout.utils.LocaleHelper; import info.nightscout.utils.PasswordProtection; import info.nightscout.utils.SP; -import info.nightscout.utils.ToastUtils; public class SWDefinition { private static Logger log = LoggerFactory.getLogger(SWDefinition.class); @@ -312,8 +307,8 @@ public class SWDefinition { newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); newDialog.show(getActivity().getSupportFragmentManager(), "NewNSTreatmentDialog"); })) - .validator(() -> MainApp.getConfigBuilder().getProfile() != null) - .visibility(() -> MainApp.getConfigBuilder().getProfile() == null) + .validator(() -> ProfileFunctions.getInstance().getProfile() != null) + .visibility(() -> ProfileFunctions.getInstance().getProfile() == null) ) .add(new SWScreen(R.string.configbuilder_pump) .skippable(false) diff --git a/app/src/main/java/info/nightscout/androidaps/tabs/TabPageAdapter.java b/app/src/main/java/info/nightscout/androidaps/tabs/TabPageAdapter.java index 79037ebcd8..b22093bb17 100644 --- a/app/src/main/java/info/nightscout/androidaps/tabs/TabPageAdapter.java +++ b/app/src/main/java/info/nightscout/androidaps/tabs/TabPageAdapter.java @@ -3,12 +3,10 @@ package info.nightscout.androidaps.tabs; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; -import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.app.FragmentStatePagerAdapter; import android.view.ViewGroup; import org.slf4j.Logger; @@ -17,6 +15,7 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import info.nightscout.androidaps.interfaces.PluginBase; +import info.nightscout.androidaps.logging.L; /** * Created by mike on 30.05.2016. @@ -27,7 +26,7 @@ public class TabPageAdapter extends FragmentPagerAdapter { Context context; - private static Logger log = LoggerFactory.getLogger(TabPageAdapter.class); + private static Logger log = LoggerFactory.getLogger(L.CORE); public TabPageAdapter(FragmentManager fm, Context context) { super(fm); @@ -47,19 +46,19 @@ public class TabPageAdapter extends FragmentPagerAdapter { @Override public void finishUpdate(ViewGroup container) { - try{ + try { super.finishUpdate(container); - } catch (NullPointerException nullPointerException){ + } catch (NullPointerException nullPointerException) { System.out.println("Catch the NullPointerException in FragmentStatePagerAdapter.finishUpdate"); - } catch (IllegalStateException e){ - log.error(e.getMessage()); + } catch (IllegalStateException e) { + log.error("Unhandled exception", e); } } @Override public CharSequence getPageTitle(int position) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - if(preferences.getBoolean("short_tabtitles", false)){ + if (preferences.getBoolean("short_tabtitles", false)) { return visibleFragmentList.get(position).getNameShort(); } return visibleFragmentList.get(position).getName(); diff --git a/app/src/main/java/info/nightscout/utils/HardLimits.java b/app/src/main/java/info/nightscout/utils/HardLimits.java index 8e1a05db0d..1a36561b62 100644 --- a/app/src/main/java/info/nightscout/utils/HardLimits.java +++ b/app/src/main/java/info/nightscout/utils/HardLimits.java @@ -5,6 +5,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; /** * Created by mike on 22.02.2017. diff --git a/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java b/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java index 5556cae935..e41d1dd914 100644 --- a/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java +++ b/app/src/main/java/info/nightscout/utils/LocalAlertUtils.java @@ -13,7 +13,9 @@ import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.Loop.LoopPlugin; +import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.notifications.Notification; @@ -79,7 +81,7 @@ public class LocalAlertUtils { //TODO: persist the actual time the pump is read and simplify the whole logic when to alarm final PumpInterface pump = ConfigBuilderPlugin.getActivePump(); - final Profile profile = MainApp.getConfigBuilder().getProfile(); + final Profile profile = ProfileFunctions.getInstance().getProfile(); if (pump != null && profile != null) { Date lastConnection = pump.lastDataTime(); long earliestAlarmTime = lastConnection.getTime() + pumpUnreachableThreshold(); diff --git a/app/src/main/java/info/nightscout/utils/XdripCalibrations.java b/app/src/main/java/info/nightscout/utils/XdripCalibrations.java index 66ec6bd3df..18c066b1da 100644 --- a/app/src/main/java/info/nightscout/utils/XdripCalibrations.java +++ b/app/src/main/java/info/nightscout/utils/XdripCalibrations.java @@ -10,14 +10,13 @@ import android.support.v7.app.AlertDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Date; import java.util.List; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.Services.Intents; -import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; +import info.nightscout.androidaps.services.Intents; /** * Created by mike on 10.02.2017. @@ -47,7 +46,7 @@ public class XdripCalibrations { Context context = MainApp.instance().getApplicationContext(); Bundle bundle = new Bundle(); bundle.putDouble("glucose_number", bg); - bundle.putString("units", MainApp.getConfigBuilder().getProfileUnits().equals(Constants.MGDL) ? "mgdl" : "mmol"); + bundle.putString("units", ProfileFunctions.getInstance().getProfileUnits().equals(Constants.MGDL) ? "mgdl" : "mmol"); bundle.putLong("timestamp", System.currentTimeMillis()); Intent intent = new Intent(Intents.ACTION_REMOTE_CALIBRATION); intent.putExtras(bundle); diff --git a/app/src/main/res/layout/activity_agreement.xml b/app/src/main/res/layout/activity_agreement.xml index e5f5c8ddf1..9a17432930 100644 --- a/app/src/main/res/layout/activity_agreement.xml +++ b/app/src/main/res/layout/activity_agreement.xml @@ -4,7 +4,7 @@ android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizo android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" -tools:context="info.nightscout.androidaps.AgreementActivity"> +tools:context="info.nightscout.androidaps.activities.AgreementActivity"> + tools:context="info.nightscout.androidaps.activities.HistoryBrowseActivity"> - -