This commit is contained in:
Milos Kozak 2018-07-30 08:42:08 +02:00
commit 61ea87dd39
312 changed files with 3224 additions and 2935 deletions

View file

@ -40,17 +40,17 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".PreferencesActivity" /> <activity android:name=".activities.PreferencesActivity" />
<activity <activity
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity" android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity <activity
android:name=".plugins.Overview.Dialogs.ErrorHelperActivity" android:name=".plugins.Overview.Dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".AgreementActivity" /> <activity android:name=".activities.AgreementActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" /> <activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" />
<activity android:name=".TDDStatsActivity" /> <activity android:name=".activities.TDDStatsActivity" />
<activity android:name=".plugins.Overview.activities.QuickWizardListActivity"> <activity android:name=".plugins.Overview.activities.QuickWizardListActivity">
<intent-filter> <intent-filter>
<action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" /> <action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" />
@ -66,7 +66,7 @@
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" /> <activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" />
<activity android:name=".HistoryBrowseActivity" /> <activity android:name=".activities.HistoryBrowseActivity" />
<receiver <receiver
android:name=".receivers.DataReceiver" android:name=".receivers.DataReceiver"
@ -129,7 +129,7 @@
<!-- Service processing incomming data --> <!-- Service processing incomming data -->
<service <service
android:name=".Services.DataService" android:name=".services.DataService"
android:exported="false" /> android:exported="false" />
<service <service
android:name=".plugins.PumpDanaR.services.DanaRExecutionService" android:name=".plugins.PumpDanaR.services.DanaRExecutionService"
@ -159,7 +159,7 @@
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
android:name=".Services.AlarmSoundService" android:name=".services.AlarmSoundService"
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
@ -178,7 +178,7 @@
android:theme="@style/AppTheme.NoActionBar" android:theme="@style/AppTheme.NoActionBar"
android:label="@string/title_activity_setup_wizard" /> android:label="@string/title_activity_setup_wizard" />
<activity android:name=".SingleFragmentActivity" <activity android:name=".activities.SingleFragmentActivity"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
</application> </application>

View file

@ -10,8 +10,8 @@ import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.events.Event; 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. /** Logs events has they're being posted to and dispatched from the event bus.
* *
@ -19,7 +19,7 @@ import info.nightscout.androidaps.events.Event;
* after 10s (after startup) and then again every 60s. * after 10s (after startup) and then again every 60s.
* */ * */
public class LoggingBus extends Bus { public class LoggingBus extends Bus {
private static Logger log = LoggerFactory.getLogger(Constants.EVENTS); private static Logger log = LoggerFactory.getLogger(L.EVENTS);
private static long everyMinute = System.currentTimeMillis() + 10 * 1000; private static long everyMinute = System.currentTimeMillis() + 10 * 1000;
private Map<String, Set<String>> event2Receiver = new HashMap<>(); private Map<String, Set<String>> event2Receiver = new HashMap<>();

View file

@ -23,25 +23,7 @@ public class Config {
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER; public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean detailedLog = true; public static boolean logConfigBuilder = true;
public static final boolean logFunctionCalls = true; public static boolean logCongigBuilderActions = 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 logQueue = true;
public static final boolean logBgSource = true;
public static final boolean logOverview = true;
public static final boolean logNotification = true;
// DanaR specific
public static final boolean logDanaBTComm = true;
public static boolean logDanaMessageDetail = true;
public static final boolean logDanaSerialEngine = true;
} }

View file

@ -68,11 +68,4 @@ public class Constants {
//SMS Communicator //SMS Communicator
public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs();
// logging
public static final String AUTOSENS = "AUTOSENS";
public static final String EVENTS = "EVENTS";
public static final String QUEUE = "QUEUE";
public static final String BGSOURCE = "BGSOURCE";
public static final String OVERVIEW = "OVERVIEW";
public static final String NOTIFICATION = "NOTIFICATION";
} }

View file

@ -38,14 +38,19 @@ import com.squareup.otto.Subscribe;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
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.data.Profile;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventFeatureRunning; import info.nightscout.androidaps.events.EventFeatureRunning;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Food.FoodPlugin; import info.nightscout.androidaps.plugins.Food.FoodPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.setupwizard.SetupWizardActivity; import info.nightscout.androidaps.setupwizard.SetupWizardActivity;
import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.androidaps.tabs.TabPageAdapter;
@ -58,7 +63,7 @@ import info.nightscout.utils.PasswordProtection;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class MainActivity extends AppCompatActivity { 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; protected PowerManager.WakeLock mWakeLock;
@ -70,7 +75,7 @@ public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
if (Config.logFunctionCalls) if (L.isEnabled(L.CORE))
log.debug("onCreate"); log.debug("onCreate");
Iconify.with(new FontAwesomeModule()); Iconify.with(new FontAwesomeModule());
@ -130,6 +135,9 @@ public class MainActivity extends AppCompatActivity {
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
if (L.isEnabled(L.CORE))
log.debug("onResume");
if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) { if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) {
Intent intent = new Intent(this, SetupWizardActivity.class); Intent intent = new Intent(this, SetupWizardActivity.class);
startActivity(intent); startActivity(intent);
@ -149,6 +157,8 @@ public class MainActivity extends AppCompatActivity {
@Override @Override
public void onDestroy() { public void onDestroy() {
if (L.isEnabled(L.CORE))
log.debug("onDestroy");
if (mWakeLock != null) if (mWakeLock != null)
if (mWakeLock.isHeld()) if (mWakeLock.isHeld())
mWakeLock.release(); mWakeLock.release();
@ -400,7 +410,7 @@ public class MainActivity extends AppCompatActivity {
builder.setIcon(R.mipmap.blueowl); builder.setIcon(R.mipmap.blueowl);
String message = "Build: " + BuildConfig.BUILDVERSION + "\n"; String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\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) if (MainApp.engineeringMode)
message += "\n" + MainApp.gs(R.string.engineering_mode_enabled); message += "\n" + MainApp.gs(R.string.engineering_mode_enabled);
message += MainApp.gs(R.string.about_link_urls); message += MainApp.gs(R.string.about_link_urls);

View file

@ -10,7 +10,6 @@ import android.support.v4.content.LocalBroadcastManager;
import com.crashlytics.android.Crashlytics; import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers; import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.j256.ormlite.android.apptools.OpenHelperManager; import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.squareup.otto.Bus; import com.squareup.otto.Bus;
import com.squareup.otto.LoggingBus; import com.squareup.otto.LoggingBus;
@ -25,12 +24,12 @@ import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.LoggerContext;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.data.ConstraintChecker; import info.nightscout.androidaps.data.ConstraintChecker;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment; import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
@ -43,6 +42,7 @@ import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlu
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; 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.NSClientInternal.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
@ -77,13 +77,13 @@ import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Fabric;
public class MainApp extends Application { 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 KeepAliveReceiver keepAliveReceiver;
private static Bus sBus; private static Bus sBus;
@ -107,6 +107,8 @@ public class MainApp extends Application {
@Override @Override
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
if (L.isEnabled(L.CORE))
log.debug("onCreate");
sInstance = this; sInstance = this;
sResources = getResources(); sResources = getResources();
sConstraintsChecker = new ConstraintChecker(this); sConstraintsChecker = new ConstraintChecker(this);
@ -119,7 +121,7 @@ public class MainApp extends Application {
Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION); Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION);
} }
} catch (Exception e) { } catch (Exception e) {
android.util.Log.e("ANDROIDAPS", "Error with Fabric init! " + e); log.error("Error with Fabric init! " + e);
} }
JodaTimeAndroid.init(this); JodaTimeAndroid.init(this);
@ -133,7 +135,7 @@ public class MainApp extends Application {
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile(); engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
devBranch = BuildConfig.VERSION.contains("dev"); 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(); registerLocalBroadcastReceiver();
@ -395,6 +397,8 @@ public class MainApp extends Application {
@Override @Override
public void onTerminate() { public void onTerminate() {
if (L.isEnabled(L.CORE))
log.debug("onTerminate");
super.onTerminate(); super.onTerminate();
if (sDatabaseHelper != null) { if (sDatabaseHelper != null) {
sDatabaseHelper.close(); sDatabaseHelper.close();

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
@ -9,6 +9,8 @@ import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.R;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class AgreementActivity extends Activity { public class AgreementActivity extends Activity {

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock; import android.os.SystemClock;
@ -29,6 +29,8 @@ import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import butterknife.OnLongClick; import butterknife.OnLongClick;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished; import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
@ -11,6 +11,9 @@ import android.preference.PreferenceGroup;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.text.TextUtils; 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.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;

View file

@ -1,16 +1,17 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.content.Intent; import android.content.Intent;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; 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.interfaces.PluginBase;
import info.nightscout.androidaps.tabs.TabPageAdapter;
import info.nightscout.utils.PasswordProtection; import info.nightscout.utils.PasswordProtection;
public class SingleFragmentActivity extends AppCompatActivity { public class SingleFragmentActivity extends AppCompatActivity {

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps; package info.nightscout.androidaps.activities;
import android.app.Activity; import android.app.Activity;
import android.graphics.Color; import android.graphics.Color;
@ -33,14 +33,14 @@ import java.util.Date;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; 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.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;

View file

@ -142,7 +142,7 @@ public class BgReading implements DataPointWithLabelInterface {
return false; return false;
if (raw != other.raw) if (raw != other.raw)
return false; return false;
if (!direction.equals(other.direction)) if (!Objects.equals(direction, other.direction))
return false; return false;
if (!Objects.equals(_id, other._id)) if (!Objects.equals(_id, other._id))
return false; return false;

View file

@ -27,8 +27,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -43,12 +41,13 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; 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.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.utils.JsonHelper; import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PercentageSplitter; import info.nightscout.utils.PercentageSplitter;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -61,7 +60,7 @@ import info.nightscout.utils.ToastUtils;
* direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service. * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
*/ */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper { 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_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings"; public static final String DATABASE_BGREADINGS = "BgReadings";
@ -108,7 +107,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Override @Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try { try {
log.info("onCreate"); if (L.isEnabled(L.DATABASE))
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
@ -326,15 +326,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
BgReading old = getDaoBgReadings().queryForId(bgReading.date); BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) { if (old == null) {
getDaoBgReadings().create(bgReading); 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); scheduleBgChange(bgReading);
return true; return true;
} }
if (!old.isEqual(bgReading)) { 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); old.copyFrom(bgReading);
getDaoBgReadings().update(old); 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); scheduleBgChange(bgReading);
return false; return false;
} }
@ -356,7 +359,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleBgChange(@Nullable final BgReading bgReading) { private static void scheduleBgChange(@Nullable final BgReading bgReading) {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing EventNewBg"); if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
MainApp.bus().post(new EventNewBG(bgReading)); MainApp.bus().post(new EventNewBG(bgReading));
scheduledBgPost = null; scheduledBgPost = null;
} }
@ -388,7 +392,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
bgList = daoBgReadings.query(preparedQuery); bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) { } catch (SQLException e) {
log.debug(e.getMessage(), e); log.error("Unhandled exception", e);
} }
if (bgList != null && bgList.size() > 0) if (bgList != null && bgList.size() > 0)
return bgList.get(0); return bgList.get(0);
@ -596,7 +600,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(old); // need to delete/create because date may change too getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget); old.copyFrom(tempTarget);
getDaoTempTargets().create(old); 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(); scheduleTemporaryTargetChange();
return true; return true;
} }
@ -615,20 +620,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(old); // need to delete/create because date may change too getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget); old.copyFrom(tempTarget);
getDaoTempTargets().create(old); 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(); scheduleTemporaryTargetChange();
return true; return true;
} }
} }
} }
getDaoTempTargets().create(tempTarget); 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(); scheduleTemporaryTargetChange();
return true; return true;
} }
if (tempTarget.source == Source.USER) { if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget); 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(); scheduleTemporaryTargetChange();
return true; return true;
} }
@ -650,7 +658,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleTemporaryTargetChange() { private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing EventTempTargetChange"); if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange");
MainApp.bus().post(new EventTempTargetChange()); MainApp.bus().post(new EventTempTargetChange());
scheduledTemTargetPost = null; scheduledTemTargetPost = null;
} }
@ -770,7 +779,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} else if (list.size() == 1) { } else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0); DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) { 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")); log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id"); record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record); getDaoDanaRHistory().update(record);
@ -800,11 +809,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery); List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) { if (trList.size() > 0) {
// do nothing, pump history record cannot be changed // 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; return false;
} }
getDaoTemporaryBasal().create(tempBasal); 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); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
return true; return true;
@ -821,7 +832,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal); old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old); 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(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -843,7 +855,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal); old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old); 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(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -852,14 +865,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
getDaoTemporaryBasal().create(tempBasal); 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); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
return true; return true;
} }
if (tempBasal.source == Source.USER) { if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal); 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); updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
return true; return true;
@ -899,7 +914,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleTemporaryBasalChange() { private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { 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 EventReloadTempBasalData());
MainApp.bus().post(new EventTempBasalChange()); MainApp.bus().post(new EventTempBasalChange());
if (earliestDataChange != null) if (earliestDataChange != null)
@ -991,7 +1007,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteTempBasalById(String _id) { public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id); TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) { 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); delete(stored);
updateEarliestDataChange(stored.date); updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange(); scheduleTemporaryBasalChange();
@ -1037,7 +1054,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return false; return false;
} }
getDaoExtendedBolus().create(extendedBolus); 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); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
@ -1050,7 +1068,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus); old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old); 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(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1072,7 +1091,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus); old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old); 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(oldDate);
updateEarliestDataChange(old.date); updateEarliestDataChange(old.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1081,14 +1101,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
getDaoExtendedBolus().create(extendedBolus); 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); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
} }
if (extendedBolus.source == Source.USER) { if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus); 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); updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
return true; return true;
@ -1128,7 +1150,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteExtendedBolusById(String _id) { public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id); ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) { 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); delete(stored);
updateEarliestDataChange(stored.date); updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange(); scheduleExtendedBolusChange();
@ -1181,7 +1204,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleExtendedBolusChange() { private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing EventExtendedBolusChange"); if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange");
MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange())); MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null) if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
@ -1321,11 +1345,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (list.size() == 1) { if (list.size() == 1) {
CareportalEvent record = list.get(0); CareportalEvent record = list.get(0);
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Removing CareportalEvent record from database: " + record.log()); log.debug("Removing CareportalEvent record from database: " + record.log());
delete(record); delete(record);
} else { } else {
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("CareportalEvent not found database: " + _id); log.debug("CareportalEvent not found database: " + _id);
} }
} catch (SQLException e) { } catch (SQLException e) {
@ -1345,12 +1369,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (list.size() == 0) { if (list.size() == 0) {
careportalEvent = new CareportalEvent(); careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT; careportalEvent.source = Source.NIGHTSCOUT;
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Adding CareportalEvent record to database: " + trJson.toString()); log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add // Record does not exists. add
} else if (list.size() == 1) { } else if (list.size() == 1) {
careportalEvent = list.get(0); careportalEvent = list.get(0);
if (Config.logIncommingData) if (L.isEnabled(L.DATABASE))
log.debug("Updating CareportalEvent record in database: " + trJson.toString()); log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else { } else {
log.error("Something went wrong"); log.error("Something went wrong");
@ -1369,7 +1393,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleCareportalEventChange() { private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing scheduleCareportalEventChange"); if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange");
MainApp.bus().post(new EventCareportalEventChange()); MainApp.bus().post(new EventCareportalEventChange());
scheduledCareportalEventPost = null; scheduledCareportalEventPost = null;
} }
@ -1415,7 +1440,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch); 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(); scheduleProfileSwitchChange();
return true; return true;
} }
@ -1434,7 +1460,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch); old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old); 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(); scheduleProfileSwitchChange();
return true; return true;
} }
@ -1443,13 +1470,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// look for already added percentage from NS // look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName); profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
getDaoProfileSwitch().create(profileSwitch); 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(); scheduleProfileSwitchChange();
return true; return true;
} }
if (profileSwitch.source == Source.USER) { if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch); 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(); scheduleProfileSwitchChange();
return true; return true;
} }
@ -1471,7 +1500,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleProfileSwitchChange() { private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { 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 EventReloadProfileSwitchData());
MainApp.bus().post(new EventProfileSwitchChange()); MainApp.bus().post(new EventProfileSwitchChange());
scheduledProfileSwitchEventPost = null; scheduledProfileSwitchEventPost = null;
@ -1521,15 +1551,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
Profile profile = store.getSpecificProfile(profileSwitch.profileName); Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) { if (profile != null) {
profileSwitch.profileJson = profile.getData().toString(); 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 // Update data in NS
NSUpload.updateProfileSwitch(profileSwitch); NSUpload.updateProfileSwitch(profileSwitch);
} else { } 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; return;
} }
} else { } 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; return;
} }
} }
@ -1544,7 +1577,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteProfileSwitchById(String _id) { public void deleteProfileSwitchById(String _id) {
ProfileSwitch stored = findProfileSwitchById(_id); ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) { 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); delete(stored);
scheduleTemporaryTargetChange(); scheduleTemporaryTargetChange();
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.utils; package info.nightscout.androidaps.logging;
import android.os.Bundle; import android.os.Bundle;

View file

@ -0,0 +1,103 @@
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;
}
}
private static List<LogElement> 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 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";
private static void initialize() {
logElements = new ArrayList<>();
logElements.add(new LogElement(CORE, true));
logElements.add(new LogElement(AUTOSENS, false));
logElements.add(new LogElement(EVENTS, false, true));
logElements.add(new LogElement(BGSOURCE, true));
logElements.add(new LogElement(OVERVIEW, true));
logElements.add(new LogElement(NOTIFICATION, true));
logElements.add(new LogElement(ALARM, false));
logElements.add(new LogElement(DATASERVICE, true));
logElements.add(new LogElement(DATABASE, true));
logElements.add(new LogElement(DATAFOOD, true));
logElements.add(new LogElement(DATATREATMENTS, true));
logElements.add(new LogElement(NSCLIENT, true));
logElements.add(new LogElement(OBJECTIVES, false));
logElements.add(new LogElement(PUMP, true));
logElements.add(new LogElement(PUMPQUEUE, true));
logElements.add(new LogElement(PUMPCOMM, true));
logElements.add(new LogElement(PUMPBTCOMM, false));
logElements.add(new LogElement(APS, true));
logElements.add(new LogElement(PROFILE, true));
}
}

View file

@ -14,10 +14,10 @@ import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.Config; 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.MainApp;
import info.nightscout.androidaps.R; 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.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;

View file

@ -39,7 +39,7 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy; 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.NumberPicker;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;

View file

@ -55,7 +55,7 @@ import info.nightscout.utils.DefaultValueHelper;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.HardLimits; import info.nightscout.utils.HardLimits;
import info.nightscout.utils.JsonHelper; 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.NumberPicker;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;

View file

@ -26,7 +26,7 @@ import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import butterknife.Unbinder; import butterknife.Unbinder;
import info.nightscout.androidaps.MainApp; 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.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;

View file

@ -47,7 +47,7 @@ import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue; import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.FabricPrivacy; 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.SP;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -70,15 +70,9 @@ public class ConfigBuilderPlugin extends PluginBase {
private static ProfileInterface activeProfile; private static ProfileInterface activeProfile;
private static TreatmentsInterface activeTreatments; private static TreatmentsInterface activeTreatments;
private static APSInterface activeAPS; private static APSInterface activeAPS;
private static LoopPlugin activeLoop;
private static InsulinInterface activeInsulin; private static InsulinInterface activeInsulin;
private static SensitivityInterface activeSensitivity; 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<PluginBase> pluginList; private static ArrayList<PluginBase> pluginList;
private static CommandQueue commandQueue = new CommandQueue(); private static CommandQueue commandQueue = new CommandQueue();
@ -126,7 +120,7 @@ public class ConfigBuilderPlugin extends PluginBase {
public void storeSettings(String from) { public void storeSettings(String from) {
if (pluginList != null) { if (pluginList != null) {
if (Config.logPrefsChange) if (Config.logConfigBuilder)
log.debug("Storing settings from: " + from); log.debug("Storing settings from: " + from);
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
@ -158,7 +152,7 @@ public class ConfigBuilderPlugin extends PluginBase {
} }
private void loadSettings() { private void loadSettings() {
if (Config.logPrefsChange) if (Config.logConfigBuilder)
log.debug("Loading stored settings"); log.debug("Loading stored settings");
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
PluginType type = p.getType(); PluginType type = p.getType();
@ -195,7 +189,7 @@ public class ConfigBuilderPlugin extends PluginBase {
private void upgradeSettings() { private void upgradeSettings() {
if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled")) if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return; return;
if (Config.logPrefsChange) if (Config.logConfigBuilder)
log.debug("Upgrading stored settings"); log.debug("Upgrading stored settings");
for (PluginBase p : pluginList) { for (PluginBase p : pluginList) {
log.debug("Processing " + p.getName()); log.debug("Processing " + p.getName());
@ -337,9 +331,6 @@ public class ConfigBuilderPlugin extends PluginBase {
} }
this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP); this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
// PluginType.LOOP
activeLoop = this.determineActivePlugin(PluginType.LOOP);
// PluginType.TREATMENT // PluginType.TREATMENT
activeTreatments = this.determineActivePlugin(PluginType.TREATMENT); activeTreatments = this.determineActivePlugin(PluginType.TREATMENT);
} }

View file

@ -6,17 +6,17 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 08.08.2017. * Created by mike on 08.08.2017.
*/ */
public class DetailedBolusInfoStorage { public class DetailedBolusInfoStorage {
private static Logger log = LoggerFactory.getLogger(DetailedBolusInfoStorage.class); private static Logger log = LoggerFactory.getLogger(L.PUMP);
private static List<DetailedBolusInfo> store = new ArrayList<>(); private static List<DetailedBolusInfo> store = new ArrayList<>();
public static synchronized void add(DetailedBolusInfo detailedBolusInfo) { public static synchronized void add(DetailedBolusInfo detailedBolusInfo) {
@ -29,7 +29,8 @@ public class DetailedBolusInfoStorage {
DetailedBolusInfo found = null; DetailedBolusInfo found = null;
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; 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) { if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
found = store.get(i); found = store.get(i);
break; break;
@ -42,7 +43,8 @@ public class DetailedBolusInfoStorage {
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; long infoTime = store.get(i).date;
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { 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); store.remove(i);
break; break;
} }

View file

@ -1,18 +1,15 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives; package info.nightscout.androidaps.plugins.ConstraintsObjectives;
import android.animation.LayoutTransition;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.CardView; import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller; import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
import android.text.Html; import android.text.Html;
import android.util.DisplayMetrics;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -21,28 +18,15 @@ import android.widget.CheckBox;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
public class ObjectivesFragment extends SubscriberFragment { public class ObjectivesFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class);
RecyclerView recyclerView; RecyclerView recyclerView;
CheckBox enableFake; CheckBox enableFake;
TextView reset; TextView reset;

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved; import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective;
@ -32,7 +33,7 @@ import info.nightscout.utils.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface { 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; private static ObjectivesPlugin objectivesPlugin;
@ -94,7 +95,7 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface
SP.putBoolean("Objectives" + "bgIsAvailableInNS", bgIsAvailableInNS); SP.putBoolean("Objectives" + "bgIsAvailableInNS", bgIsAvailableInNS);
SP.putBoolean("Objectives" + "pumpStatusIsAvailableInNS", pumpStatusIsAvailableInNS); SP.putBoolean("Objectives" + "pumpStatusIsAvailableInNS", pumpStatusIsAvailableInNS);
SP.putString("Objectives" + "manualEnacts", Integer.toString(manualEnacts)); SP.putString("Objectives" + "manualEnacts", Integer.toString(manualEnacts));
if (Config.logPrefsChange) if (L.isEnabled(L.OBJECTIVES))
log.debug("Objectives stored"); log.debug("Objectives stored");
MainApp.bus().post(new EventObjectivesSaved()); MainApp.bus().post(new EventObjectivesSaved());
} }
@ -107,7 +108,7 @@ public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
if (Config.logPrefsChange) if (L.isEnabled(L.OBJECTIVES))
log.debug("Objectives loaded"); log.debug("Objectives loaded");
} }

View file

@ -33,7 +33,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SpinnerHelper; import info.nightscout.utils.SpinnerHelper;
/** /**

View file

@ -33,13 +33,14 @@ import info.nightscout.androidaps.db.ICallback;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 24.09.2017. * Created by mike on 24.09.2017.
*/ */
public class FoodService extends OrmLiteBaseService<DatabaseHelper> { public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
private static Logger log = LoggerFactory.getLogger(FoodService.class); private Logger log = LoggerFactory.getLogger(L.DATAFOOD);
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledFoodEventPost = null; private static ScheduledFuture<?> scheduledFoodEventPost = null;
@ -110,7 +111,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
try { try {
log.info("onCreate"); if (L.isEnabled(L.DATAFOOD))
log.info("onCreate");
TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Can't create database", e); log.error("Can't create database", e);
@ -122,7 +124,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
if (oldVersion == 7 && newVersion == 8) { if (oldVersion == 7 && newVersion == 8) {
log.debug("Upgrading database from v7 to v8"); log.debug("Upgrading database from v7 to v8");
} else { } else {
log.info("onUpgrade"); if (L.isEnabled(L.DATAFOOD))
log.info("onUpgrade");
// this.resetFood(); // this.resetFood();
} }
} }
@ -161,7 +164,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
class PostRunnable implements Runnable { class PostRunnable implements Runnable {
public void run() { public void run() {
log.debug("Firing EventFoodChange"); if (L.isEnabled(L.DATAFOOD))
log.debug("Firing EventFoodChange");
MainApp.bus().post(event); MainApp.bus().post(event);
callback.setPost(null); callback.setPost(null);
} }
@ -271,7 +275,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void deleteByNSId(String _id) throws SQLException { public void deleteByNSId(String _id) throws SQLException {
Food stored = this.findByNSId(_id); Food stored = this.findByNSId(_id);
if (stored != null) { 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); this.delete(stored);
} }
} }
@ -324,7 +329,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void createOrUpdate(Food food) { public void createOrUpdate(Food food) {
try { try {
this.getDao().createOrUpdate(food); 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) { } catch (SQLException e) {
log.error("Unable to createOrUpdate Food", e); log.error("Unable to createOrUpdate Food", e);
} }
@ -334,7 +340,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void create(Food food) { public void create(Food food) {
try { try {
this.getDao().create(food); 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) { } catch (SQLException e) {
log.error("Unable to create Food", e); log.error("Unable to create Food", e);
} }

View file

@ -12,6 +12,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -26,7 +27,7 @@ import info.nightscout.utils.SP;
*/ */
public class AutosensData implements DataPointWithLabelInterface { public class AutosensData implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
public void setChartTime(long chartTime) { public void setChartTime(long chartTime) {
this.chartTime = chartTime; this.chartTime = chartTime;
@ -48,7 +49,8 @@ public class AutosensData implements DataPointWithLabelInterface {
double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits());
double ic = profile.getIc(t.date); double ic = profile.getIc(t.date);
min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; 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 { } else {
min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact); min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact);
} }
@ -107,7 +109,8 @@ public class AutosensData implements DataPointWithLabelInterface {
activeCarbsList.remove(i--); activeCarbsList.remove(i--);
if (c.remaining > 0) if (c.remaining > 0)
cob -= c.remaining; 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());
} }
} }
} }

View file

@ -5,13 +5,13 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 06.01.2017. * Created by mike on 06.01.2017.
*/ */
public class AutosensResult { public class AutosensResult {
private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
//default values to show when autosens algorithm is not called //default values to show when autosens algorithm is not called
public double ratio = 1d; public double ratio = 1d;

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.IobCobCalculator; package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.os.SystemClock; import android.os.SystemClock;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray; import android.support.v4.util.LongSparseArray;
@ -16,7 +15,6 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -33,6 +31,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
@ -49,7 +48,7 @@ import static info.nightscout.utils.DateUtil.now;
*/ */
public class IobCobCalculatorPlugin extends PluginBase { public class IobCobCalculatorPlugin extends PluginBase {
private Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private static IobCobCalculatorPlugin plugin = null; private static IobCobCalculatorPlugin plugin = null;
@ -112,13 +111,15 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.debug("Locking getBucketedData"); //log.debug("Locking getBucketedData");
synchronized (dataLock) { synchronized (dataLock) {
if (bucketed_data == null) { if (bucketed_data == null) {
log.debug("No bucketed data available"); if (L.isEnabled(L.AUTOSENS))
log.debug("No bucketed data available");
return null; return null;
} }
int index = indexNewerThan(fromTime); int index = indexNewerThan(fromTime);
if (index > -1) { if (index > -1) {
List<BgReading> part = bucketed_data.subList(0, index); List<BgReading> 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; return part;
} }
} }
@ -144,7 +145,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
void loadBgData(long now) { void loadBgData(long now) {
long start = (long) (now - 60 * 60 * 1000L * (24 + dia)); long start = (long) (now - 60 * 60 * 1000L * (24 + dia));
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false); bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, now, false);
log.debug("BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(now)); 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() { private boolean isAbout5minData() {
@ -160,13 +162,15 @@ public class IobCobCalculatorPlugin extends PluginBase {
totalDiff += diff; totalDiff += diff;
if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30 if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false); 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 intervals = totalDiff / (5 * 60 * 1000d);
double variability = Math.abs(intervals - Math.round(intervals)); double variability = Math.abs(intervals - Math.round(intervals));
boolean is5mindata = variability < 0.02; 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; return is5mindata;
} }
} }
@ -293,7 +297,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.error("***** Average"); //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 calculateDetectionStart(long from, boolean limitDataToOldestAvailable) { public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) {
@ -306,7 +311,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
if (limitDataToOldestAvailable) { if (limitDataToOldestAvailable) {
getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia))); getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia)));
if (getBGDataFrom == oldestDataAvailable) if (getBGDataFrom == oldestDataAvailable)
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString()); if (L.isEnabled(L.AUTOSENS))
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString());
} else } else
getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia)); getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia));
return getBGDataFrom; return getBGDataFrom;
@ -413,12 +419,14 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable @Nullable
public AutosensData getLastAutosensDataSynchronized(String reason) { public AutosensData getLastAutosensDataSynchronized(String reason) {
if (thread != null && thread.isAlive()) { if (thread != null && thread.isAlive()) {
log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason); if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason);
try { try {
thread.join(5000); thread.join(5000);
} catch (InterruptedException ignored) { } 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) { synchronized (dataLock) {
return getLastAutosensData(reason); return getLastAutosensData(reason);
@ -456,7 +464,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable @Nullable
public AutosensData getLastAutosensData(String reason) { public AutosensData getLastAutosensData(String reason) {
if (autosensDataTable.size() < 1) { 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; return null;
} }
AutosensData data; AutosensData data;
@ -470,10 +479,12 @@ public class IobCobCalculatorPlugin extends PluginBase {
return null; return null;
} }
if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) { 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; return null;
} else { } else {
log.debug("AUTOSENSDATA (" + reason + ") " + data.toString()); if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA (" + reason + ") " + data.toString());
return data; return data;
} }
} }
@ -535,7 +546,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void onEventAppInitialized(EventAppInitialized ev) { public void onEventAppInitialized(EventAppInitialized ev) {
if (this != getPlugin()) { 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; return;
} }
runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev); runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev);
@ -545,7 +557,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@SuppressWarnings("unused") @SuppressWarnings("unused")
public void onEventNewBG(EventNewBG ev) { public void onEventNewBG(EventNewBG ev) {
if (this != getPlugin()) { 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; return;
} }
stopCalculation("onEventNewBG"); stopCalculation("onEventNewBG");
@ -555,16 +568,19 @@ public class IobCobCalculatorPlugin extends PluginBase {
public void stopCalculation(String from) { public void stopCalculation(String from) {
if (thread != null && thread.getState() != Thread.State.TERMINATED) { if (thread != null && thread.getState() != Thread.State.TERMINATED) {
stopCalculationTrigger = true; 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) { while (thread.getState() != Thread.State.TERMINATED) {
SystemClock.sleep(100); 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 end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) {
log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end)); if (L.isEnabled(L.AUTOSENS))
log.debug("Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end));
if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (thread == null || thread.getState() == Thread.State.TERMINATED) {
if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) if (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY))
thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause); thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause);
@ -577,7 +593,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe @Subscribe
public void onNewProfile(EventNewBasalProfile ev) { public void onNewProfile(EventNewBasalProfile ev) {
if (this != getPlugin()) { 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; return;
} }
if (MainApp.getConfigBuilder() == null) if (MainApp.getConfigBuilder() == null)
@ -591,7 +608,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
stopCalculation("onNewProfile"); stopCalculation("onNewProfile");
synchronized (dataLock) { 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<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
@ -601,7 +619,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe @Subscribe
public void onEventPreferenceChange(EventPreferenceChange ev) { public void onEventPreferenceChange(EventPreferenceChange ev) {
if (this != getPlugin()) { 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; return;
} }
if (ev.isChanged(R.string.key_openapsama_autosens_period) || if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
@ -614,7 +633,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
) { ) {
stopCalculation("onEventPreferenceChange"); stopCalculation("onEventPreferenceChange");
synchronized (dataLock) { 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<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
@ -625,12 +645,14 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe @Subscribe
public void onEventConfigBuilderChange(EventConfigBuilderChange ev) { public void onEventConfigBuilderChange(EventConfigBuilderChange ev) {
if (this != getPlugin()) { 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; return;
} }
stopCalculation("onEventConfigBuilderChange"); stopCalculation("onEventConfigBuilderChange");
synchronized (dataLock) { 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<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }
@ -641,7 +663,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe @Subscribe
public void onEventNewHistoryData(EventNewHistoryData ev) { public void onEventNewHistoryData(EventNewHistoryData ev) {
if (this != getPlugin()) { 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; return;
} }
//log.debug("Locking onNewHistoryData"); //log.debug("Locking onNewHistoryData");
@ -649,10 +672,11 @@ public class IobCobCalculatorPlugin extends PluginBase {
synchronized (dataLock) { synchronized (dataLock) {
// clear up 5 min back for proper COB calculation // clear up 5 min back for proper COB calculation
long time = ev.time - 5 * 60 * 1000L; 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--) { for (int index = iobTable.size() - 1; index >= 0; index--) {
if (iobTable.keyAt(index) > time) { if (iobTable.keyAt(index) > time) {
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString()); log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
iobTable.removeAt(index); iobTable.removeAt(index);
} else { } else {
@ -661,7 +685,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
for (int index = autosensDataTable.size() - 1; index >= 0; index--) { for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
if (autosensDataTable.keyAt(index) > time) { if (autosensDataTable.keyAt(index) > time) {
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString()); log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString());
autosensDataTable.removeAt(index); autosensDataTable.removeAt(index);
} else { } else {
@ -670,7 +694,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
for (int index = basalDataTable.size() - 1; index >= 0; index--) { for (int index = basalDataTable.size() - 1; index >= 0; index--) {
if (basalDataTable.keyAt(index) > time) { if (basalDataTable.keyAt(index) > time) {
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString()); log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString());
basalDataTable.removeAt(index); basalDataTable.removeAt(index);
} else { } else {
@ -684,7 +708,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
public void clearCache() { public void clearCache() {
synchronized (dataLock) { synchronized (dataLock) {
log.debug("Clearing cached data."); if (L.isEnabled(L.AUTOSENS))
log.debug("Clearing cached data.");
iobTable = new LongSparseArray<>(); iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>(); autosensDataTable = new LongSparseArray<>();
} }

View file

@ -17,7 +17,6 @@ import java.util.GregorianCalendar;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -26,6 +25,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
@ -43,7 +43,7 @@ import static java.util.Calendar.MINUTE;
*/ */
public class IobCobOref1Thread extends Thread { public class IobCobOref1Thread extends Thread {
private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private final Event cause; private final Event cause;
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
@ -72,13 +72,16 @@ public class IobCobOref1Thread extends Thread {
public final void run() { public final void run() {
mWakeLock.acquire(); mWakeLock.acquire();
try { try {
log.debug("AUTOSENSDATA thread started: " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread started: " + from);
if (MainApp.getConfigBuilder() == null) { 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 return; // app still initializing
} }
if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) { if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) {
log.debug("Aborting calculation thread (No profile): " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (No profile): " + from);
return; // app still initializing return; // app still initializing
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
@ -94,12 +97,14 @@ public class IobCobOref1Thread extends Thread {
LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { 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; return;
} }
long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); 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); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) { for (int i = bucketed_data.size() - 4; i >= 0; i--) {
@ -108,7 +113,8 @@ public class IobCobOref1Thread extends Thread {
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false; iobCobCalculatorPlugin.stopCalculationTrigger = false;
log.debug("Aborting calculation thread (trigger): " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (trigger): " + from);
return; return;
} }
// check if data already exists // check if data already exists
@ -125,11 +131,12 @@ public class IobCobOref1Thread extends Thread {
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime); Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
if (profile == null) { 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 return; // profile not set yet
} }
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")");
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
@ -171,7 +178,7 @@ public class IobCobOref1Thread extends Thread {
AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); 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()); log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString());
int past = 1; int past = 1;
try { try {
@ -187,7 +194,7 @@ public class IobCobOref1Thread extends Thread {
minDeviation = ad.avgDeviation; 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); // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation);
} }
} catch (Exception e) { } catch (Exception e) {
@ -340,13 +347,13 @@ public class IobCobOref1Thread extends Thread {
previous = autosensData; previous = autosensData;
if (bgTime < now()) if (bgTime < now())
autosensDataTable.put(bgTime, autosensData); autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime());
AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Sensitivity result: " + sensitivity.toString()); log.debug("Sensitivity result: " + sensitivity.toString());
autosensData.autosensResult = sensitivity; autosensData.autosensResult = sensitivity;
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug(autosensData.toString()); log.debug(autosensData.toString());
} }
} }
@ -357,7 +364,8 @@ public class IobCobOref1Thread extends Thread {
} finally { } finally {
mWakeLock.release(); mWakeLock.release();
MainApp.bus().post(new EventIobCalculationProgress("")); MainApp.bus().post(new EventIobCalculationProgress(""));
log.debug("AUTOSENSDATA thread ended: " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread ended: " + from);
} }
} }

View file

@ -15,7 +15,6 @@ import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -24,6 +23,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
@ -42,7 +42,7 @@ import static info.nightscout.utils.DateUtil.now;
*/ */
public class IobCobThread extends Thread { public class IobCobThread extends Thread {
private static Logger log = LoggerFactory.getLogger(Constants.AUTOSENS); private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private final Event cause; private final Event cause;
private IobCobCalculatorPlugin iobCobCalculatorPlugin; private IobCobCalculatorPlugin iobCobCalculatorPlugin;
@ -71,13 +71,16 @@ public class IobCobThread extends Thread {
public final void run() { public final void run() {
mWakeLock.acquire(); mWakeLock.acquire();
try { try {
log.debug("AUTOSENSDATA thread started: " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread started: " + from);
if (MainApp.getConfigBuilder() == null) { 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 return; // app still initializing
} }
if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) { if (!MainApp.getConfigBuilder().isProfileValid("IobCobThread")) {
log.debug("Aborting calculation thread (No profile): " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (No profile): " + from);
return; // app still initializing return; // app still initializing
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
@ -93,12 +96,14 @@ public class IobCobThread extends Thread {
LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { 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; return;
} }
long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); 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); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) { for (int i = bucketed_data.size() - 4; i >= 0; i--) {
@ -107,7 +112,8 @@ public class IobCobThread extends Thread {
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false; iobCobCalculatorPlugin.stopCalculationTrigger = false;
log.debug("Aborting calculation thread (trigger): " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("Aborting calculation thread (trigger): " + from);
return; return;
} }
// check if data already exists // check if data already exists
@ -124,11 +130,12 @@ public class IobCobThread extends Thread {
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime); Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
if (profile == null) { 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 return; // profile not set yet
} }
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")"); log.debug("Processing calculation thread: " + from + " (" + i + "/" + bucketed_data.size() + ")");
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
@ -170,7 +177,7 @@ public class IobCobThread extends Thread {
AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); 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()); log.debug(">>>>> bucketed_data.size()=" + bucketed_data.size() + " i=" + i + "hourAgoData=" + hourAgoData.toString());
int past = 1; int past = 1;
try { try {
@ -186,7 +193,7 @@ public class IobCobThread extends Thread {
minDeviation = ad.avgDeviation; 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); // log.debug("Deviations: " + new Date(bgTime) + new Date(ad.time) + " avgDeviation=" + avgDeviation + " deviationSlope=" + deviationSlope + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation=" + slopeFromMinDeviation);
} }
} catch (Exception e) { } catch (Exception e) {
@ -267,13 +274,13 @@ public class IobCobThread extends Thread {
previous = autosensData; previous = autosensData;
if (bgTime < now()) if (bgTime < now())
autosensDataTable.put(bgTime, autosensData); autosensDataTable.put(bgTime, autosensData);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); log.debug("Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime());
AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime);
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug("Sensitivity result: " + sensitivity.toString()); log.debug("Sensitivity result: " + sensitivity.toString());
autosensData.autosensResult = sensitivity; autosensData.autosensResult = sensitivity;
if (Config.logAutosensData) if (L.isEnabled(L.AUTOSENS))
log.debug(autosensData.toString()); log.debug(autosensData.toString());
} }
} }
@ -284,7 +291,8 @@ public class IobCobThread extends Thread {
} finally { } finally {
mWakeLock.release(); mWakeLock.release();
MainApp.bus().post(new EventIobCalculationProgress("")); MainApp.bus().post(new EventIobCalculationProgress(""));
log.debug("AUTOSENSDATA thread ended: " + from); if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA thread ended: " + from);
} }
} }

View file

@ -18,6 +18,7 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -25,7 +26,7 @@ import info.nightscout.utils.DecimalFormatter;
* Created by mike on 09.06.2016. * Created by mike on 09.06.2016.
*/ */
public class APSResult { public class APSResult {
private static Logger log = LoggerFactory.getLogger(APSResult.class); private static Logger log = LoggerFactory.getLogger(L.APS);
public long date = 0; public long date = 0;
public String reason; public String reason;

View file

@ -1,17 +1,11 @@
package info.nightscout.androidaps.plugins.Loop; 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.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
/* /*
{ {
@ -371,7 +365,7 @@ import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
*/ */
public class DeviceStatus { public class DeviceStatus {
private static Logger log = LoggerFactory.getLogger(DeviceStatus.class); private static Logger log = LoggerFactory.getLogger(L.APS);
public String device = null; public String device = null;
public JSONObject pump = null; public JSONObject pump = null;
@ -381,12 +375,12 @@ public class DeviceStatus {
public int uploaderBattery = 0; public int uploaderBattery = 0;
public String created_at = null; public String created_at = null;
public JSONObject mongoRecord () { public JSONObject mongoRecord() {
JSONObject record = new JSONObject(); JSONObject record = new JSONObject();
try { try {
if (device != null) record.put("device" , device); if (device != null) record.put("device", device);
if (pump != null) record.put("pump" , pump); if (pump != null) record.put("pump", pump);
if (suggested != null) { if (suggested != null) {
JSONObject openaps = new JSONObject(); JSONObject openaps = new JSONObject();
if (enacted != null) openaps.put("enacted", enacted); if (enacted != null) openaps.put("enacted", enacted);
@ -395,7 +389,7 @@ public class DeviceStatus {
record.put("openaps", openaps); record.put("openaps", openaps);
} }
if (uploaderBattery != 0) record.put("uploaderBattery", uploaderBattery); 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) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }

View file

@ -28,8 +28,6 @@ import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
public class LoopFragment extends SubscriberFragment { public class LoopFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(LoopFragment.class);
@BindView(R.id.loop_run) @BindView(R.id.loop_run)
Button runNowButton; Button runNowButton;
@BindView(R.id.loop_lastrun) @BindView(R.id.loop_lastrun)

View file

@ -21,7 +21,6 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -32,36 +31,36 @@ import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; 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.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class LoopPlugin extends PluginBase { 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 @NonNull
public static LoopPlugin getPlugin() { public static LoopPlugin getPlugin() {
@ -132,15 +131,15 @@ public class LoopPlugin extends PluginBase {
PumpInterface pump = ConfigBuilderPlugin.getActivePump(); PumpInterface pump = ConfigBuilderPlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable; return pump == null || pump.getPumpDescription().isTempBasalCapable;
} }
/** /**
* This method is triggered once autosens calculation has completed, so the LoopPlugin * 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 * 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 * 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. * the event causing the calculation is not EventNewBg.
* * <p>
* Callers of {@link info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin#runCalculation(String, long, boolean, Event)} * 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. * are sources triggering a calculation which triggers this method upon completion.
*/ */
@Subscribe @Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) { public void onStatusEvent(final EventAutosensCalculationFinished ev) {
@ -249,19 +248,20 @@ public class LoopPlugin extends PluginBase {
return isDisconnected; return isDisconnected;
} }
public synchronized void invoke(String initiator, boolean allowNotification){ public synchronized void invoke(String initiator, boolean allowNotification) {
invoke(initiator, allowNotification, false); invoke(initiator, allowNotification, false);
} }
public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) { public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) {
try { try {
if (Config.logFunctionCalls) if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator); log.debug("invoke from " + initiator);
Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed(); Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
if (!loopEnabled.value()) { if (!loopEnabled.value()) {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); 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)); MainApp.bus().post(new EventLoopSetLastRunGui(message));
return; return;
} }
@ -274,7 +274,8 @@ public class LoopPlugin extends PluginBase {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = MainApp.getConfigBuilder().getProfile();
if (!MainApp.getConfigBuilder().isProfileValid("Loop")) { if (!MainApp.getConfigBuilder().isProfileValid("Loop")) {
log.debug(MainApp.gs(R.string.noprofileselected)); if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return; return;
} }
@ -304,7 +305,8 @@ public class LoopPlugin extends PluginBase {
// safety check for multiple SMBs // safety check for multiple SMBs
long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime(); long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) { 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; resultAfterConstraints.smb = 0;
} }
@ -319,13 +321,15 @@ public class LoopPlugin extends PluginBase {
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
if (isSuspended()) { 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))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return; return;
} }
if (pump.isSuspended()) { 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))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return; return;
} }
@ -412,7 +416,7 @@ public class LoopPlugin extends PluginBase {
MainApp.bus().post(new EventLoopUpdateGui()); MainApp.bus().post(new EventLoopUpdateGui());
} finally { } finally {
if (Config.logFunctionCalls) if (L.isEnabled(L.APS))
log.debug("invoke end"); log.debug("invoke end");
} }
} }

View file

@ -34,8 +34,6 @@ import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private static Logger log = LoggerFactory.getLogger(NSClientFragment.class);
private TextView logTextView; private TextView logTextView;
private TextView queueTextView; private TextView queueTextView;
private TextView urlTextView; private TextView urlTextView;

View file

@ -29,6 +29,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; 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.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI;
@ -37,7 +38,7 @@ import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
public class NSClientPlugin extends PluginBase { public class NSClientPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(NSClientPlugin.class); private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
static NSClientPlugin nsClientPlugin; static NSClientPlugin nsClientPlugin;
@ -53,8 +54,8 @@ public class NSClientPlugin extends PluginBase {
private final List<EventNSClientNewLog> listLog = new ArrayList<>(); private final List<EventNSClientNewLog> listLog = new ArrayList<>();
Spanned textLog = Html.fromHtml(""); Spanned textLog = Html.fromHtml("");
public boolean paused = false; public boolean paused;
boolean autoscroll = true; boolean autoscroll;
public String status = ""; public String status = "";
@ -132,12 +133,14 @@ public class NSClientPlugin extends PluginBase {
private ServiceConnection mConnection = new ServiceConnection() { private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
log.debug("Service is disconnected"); if (L.isEnabled(L.NSCLIENT))
log.debug("Service is disconnected");
nsClientService = null; nsClientService = null;
} }
public void onServiceConnected(ComponentName name, IBinder service) { 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; NSClientService.LocalBinder mLocalBinder = (NSClientService.LocalBinder) service;
if (mLocalBinder != null) // is null when running in roboelectric if (mLocalBinder != null) // is null when running in roboelectric
nsClientService = mLocalBinder.getServiceInstance(); nsClientService = mLocalBinder.getServiceInstance();
@ -155,7 +158,8 @@ public class NSClientPlugin extends PluginBase {
@Subscribe @Subscribe
public void onStatusEvent(final EventNSClientNewLog ev) { public void onStatusEvent(final EventNSClientNewLog ev) {
addToLog(ev); addToLog(ev);
log.debug(ev.action + " " + ev.logText); if (L.isEnabled(L.NSCLIENT))
log.debug(ev.action + " " + ev.logText);
} }
@Subscribe @Subscribe
@ -165,30 +169,24 @@ public class NSClientPlugin extends PluginBase {
} }
synchronized void clearLog() { synchronized void clearLog() {
handler.post(new Runnable() { handler.post(() -> {
@Override synchronized (listLog) {
public void run() { listLog.clear();
synchronized (listLog) {
listLog.clear();
}
MainApp.bus().post(new EventNSClientUpdateGUI());
} }
MainApp.bus().post(new EventNSClientUpdateGUI());
}); });
} }
private synchronized void addToLog(final EventNSClientNewLog ev) { private synchronized void addToLog(final EventNSClientNewLog ev) {
handler.post(new Runnable() { handler.post(() -> {
@Override synchronized (listLog) {
public void run() { listLog.add(ev);
synchronized (listLog) { // remove the first line if log is too large
listLog.add(ev); if (listLog.size() >= Constants.MAX_LOG_LINES) {
// remove the first line if log is too large listLog.remove(0);
if (listLog.size() >= Constants.MAX_LOG_LINES) {
listLog.remove(0);
}
} }
MainApp.bus().post(new EventNSClientUpdateGUI());
} }
MainApp.bus().post(new EventNSClientUpdateGUI());
}); });
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.utils; package info.nightscout.androidaps.plugins.NSClientInternal;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@ -23,7 +23,8 @@ import java.util.Locale;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
@ -37,13 +38,16 @@ import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus; import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger; 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. * Created by mike on 26.05.2017.
*/ */
public class NSUpload { 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) { public static void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) {
try { try {
@ -232,7 +236,8 @@ public class NSUpload {
deviceStatus.enacted.put("requested", requested); deviceStatus.enacted.put("requested", requested);
} }
} else { } 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; deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL;
JSONObject pumpstatus = ConfigBuilderPlugin.getActivePump().getJSONStatus(profile, profileName); JSONObject pumpstatus = ConfigBuilderPlugin.getActivePump().getJSONStatus(profile, profileName);
@ -490,7 +495,7 @@ public class NSUpload {
try { try {
data.put("eventType", "Note"); data.put("eventType", "Note");
data.put("created_at", DateUtil.toISOString(new Date())); 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) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
@ -500,7 +505,7 @@ public class NSUpload {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent); context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString()); DbLogger.dbAdd(intent, data.toString());
} }
} }
public static void uploadEvent(String careportalEvent, long time, @Nullable String notes) { public static void uploadEvent(String careportalEvent, long time, @Nullable String notes) {

View file

@ -16,13 +16,14 @@ import java.sql.SQLException;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
/** /**
* Created by mike on 21.02.2016. * Created by mike on 21.02.2016.
*/ */
public class UploadQueue { public class UploadQueue {
private static Logger log = LoggerFactory.getLogger(UploadQueue.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static String status() { public static String status() {
return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS);
@ -43,15 +44,13 @@ public class UploadQueue {
public static void add(final DbRequest dbr) { public static void add(final DbRequest dbr) {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override if (L.isEnabled(L.NSCLIENT))
public void run() { log.debug("Adding to queue: " + dbr.data);
log.debug("QUEUE adding: " + dbr.data); MainApp.getDbHelper().create(dbr);
MainApp.getDbHelper().create(dbr); NSClientPlugin plugin = NSClientPlugin.getPlugin();
NSClientPlugin plugin = NSClientPlugin.getPlugin(); if (plugin != null) {
if (plugin != null) { plugin.resend("newdata");
plugin.resend("newdata");
}
} }
}); });
} }
@ -60,13 +59,12 @@ public class UploadQueue {
public static void clearQueue() { public static void clearQueue() {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override if (L.isEnabled(L.NSCLIENT))
public void run() { log.debug("ClearQueue");
log.debug("QUEUE ClearQueue"); MainApp.getDbHelper().deleteAllDbRequests();
MainApp.getDbHelper().deleteAllDbRequests(); if (L.isEnabled(L.NSCLIENT))
log.debug(status()); log.debug(status());
}
}); });
} }
} }
@ -74,22 +72,20 @@ public class UploadQueue {
public static void removeID(final JSONObject record) { public static void removeID(final JSONObject record) {
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override try {
public void run() { String id;
try { if (record.has("NSCLIENT_ID")) {
String id; id = record.getString("NSCLIENT_ID");
if (record.has("NSCLIENT_ID")) { } else {
id = record.getString("NSCLIENT_ID"); return;
} else {
return;
}
if (MainApp.getDbHelper().deleteDbRequest(id) == 1) {
log.debug("Removed item from UploadQueue. " + UploadQueue.status());
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
} }
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; return;
startService(); startService();
if (NSClientService.handler != null) { if (NSClientService.handler != null) {
NSClientService.handler.post(new Runnable() { NSClientService.handler.post(() -> {
@Override MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id);
public void run() { if (L.isEnabled(L.NSCLIENT))
MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status());
}
}); });
} }
} }
public String textList() { public String textList() {
String result = ""; String result = "";
CloseableIterator<DbRequest> iterator = null; CloseableIterator<DbRequest> iterator;
try { try {
iterator = MainApp.getDbHelper().getDbRequestInterator(); iterator = MainApp.getDbHelper().getDbRequestInterator();
try { try {

View file

@ -1,13 +1,13 @@
package info.nightscout.androidaps.plugins.NSClientInternal.acks; package info.nightscout.androidaps.plugins.NSClientInternal.acks;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
import io.socket.client.Ack; import io.socket.client.Ack;
@ -15,17 +15,18 @@ import io.socket.client.Ack;
* Created by mike on 29.12.2015. * Created by mike on 29.12.2015.
*/ */
public class NSAddAck extends Event implements Ack { 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 _id = null;
public String nsClientID = null; public String nsClientID = null;
public JSONObject json = null; public JSONObject json = null;
public void call(Object...args) {
public void call(Object... args) {
// Regular response // Regular response
try { try {
JSONArray responsearray = (JSONArray) (args[0]); JSONArray responsearray = (JSONArray) (args[0]);
JSONObject response = null; JSONObject response = null;
if (responsearray.length()>0) { if (responsearray.length() > 0) {
response = responsearray.getJSONObject(0); response = responsearray.getJSONObject(0);
_id = response.getString("_id"); _id = response.getString("_id");
json = response; json = response;
if (response.has("NSCLIENT_ID")) { if (response.has("NSCLIENT_ID")) {
@ -35,6 +36,7 @@ public class NSAddAck extends Event implements Ack {
MainApp.bus().post(this); MainApp.bus().post(this);
return; return;
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e);
} }
// Check for not authorized // Check for not authorized
try { try {
@ -45,7 +47,8 @@ public class NSAddAck extends Event implements Ack {
MainApp.bus().post(new EventNSClientRestart()); MainApp.bus().post(new EventNSClientRestart());
return; return;
} }
log.debug("DBACCESS " + response.getString("result")); if (L.isEnabled(L.NSCLIENT))
log.debug("DBACCESS " + response.getString("result"));
} }
return; return;
} catch (Exception e) { } catch (Exception e) {

View file

@ -7,15 +7,16 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import io.socket.client.Ack; import io.socket.client.Ack;
/** /**
* Created by mike on 21.02.2016. * Created by mike on 21.02.2016.
*/ */
public class NSUpdateAck extends Event implements Ack { 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 boolean result = false;
public String _id = null; public String _id;
public String action; public String action;
public void call(Object...args) { public void call(Object...args) {
JSONObject response = (JSONObject)args[0]; JSONObject response = (JSONObject)args[0];
@ -29,6 +30,7 @@ public class NSUpdateAck extends Event implements Ack {
} }
MainApp.bus().post(this); MainApp.bus().post(this);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e);
} }
} }

View file

@ -2,18 +2,12 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; 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.MainApp;
import info.nightscout.androidaps.R; 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.androidaps.plugins.NSClientInternal.data.NSAlarm;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -22,7 +16,6 @@ import info.nightscout.utils.SP;
*/ */
public class BroadcastAckAlarm { public class BroadcastAckAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastAckAlarm.class);
public static void handleClearAlarm(NSAlarm originalAlarm, Context context, long silenceTimeInMsec) { public static void handleClearAlarm(NSAlarm originalAlarm, Context context, long silenceTimeInMsec) {

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastAlarm { public class BroadcastAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastAlarm.class);
public static void handleAlarm(JSONObject alarm, Context context) { public static void handleAlarm(JSONObject alarm, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", alarm.toString()); bundle.putString("data", alarm.toString());

View file

@ -2,28 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastAnnouncement { public class BroadcastAnnouncement {
private static Logger log = LoggerFactory.getLogger(BroadcastAnnouncement.class);
public static void handleAnnouncement(JSONObject announcement, Context context) { public static void handleAnnouncement(JSONObject announcement, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", announcement.toString()); bundle.putString("data", announcement.toString());

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastCals { public class BroadcastCals {
private static Logger log = LoggerFactory.getLogger(BroadcastCals.class);
public static void handleNewCal(JSONArray cals, Context context, boolean isDelta) { public static void handleNewCal(JSONArray cals, Context context, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastClearAlarm { public class BroadcastClearAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastClearAlarm.class);
public static void handleClearAlarm(JSONObject clearalarm, Context context) { public static void handleClearAlarm(JSONObject clearalarm, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", clearalarm.toString()); bundle.putString("data", clearalarm.toString());

View file

@ -2,45 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class BroadcastDeviceStatus { 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) { public static void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(statuses); List<JSONArray> splitted = BroadcastTreatment.splitArray(statuses);
@ -67,31 +42,4 @@ public class BroadcastDeviceStatus {
} }
} }
} }
public static void handleNewFoods(JSONArray foods, Context context, boolean isDelta) {
List<JSONArray> 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);
}
}
}
} }

View file

@ -6,26 +6,18 @@ import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; 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 java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 20.02.2016. * Created by mike on 20.02.2016.
*/ */
public class BroadcastFood { public class BroadcastFood {
private static Logger log = LoggerFactory.getLogger(BroadcastFood.class);
public static void handleNewFood(JSONArray foods, Context context, boolean isDelta) { public static void handleNewFood(JSONArray foods, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(foods); List<JSONArray> splitted = BroadcastTreatment.splitArray(foods);

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastMbgs { public class BroadcastMbgs {
private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class);
public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) { public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();

View file

@ -2,18 +2,12 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; 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.MainApp;
import info.nightscout.androidaps.R; 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.androidaps.data.ProfileStore;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -22,8 +16,6 @@ import info.nightscout.utils.SP;
* Created by mike on 20.02.2016. * Created by mike on 20.02.2016.
*/ */
public class BroadcastProfile { public class BroadcastProfile {
private static Logger log = LoggerFactory.getLogger(BroadcastProfile.class);
public static void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) { public static void handleNewTreatment(ProfileStore profile, Context context, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();

View file

@ -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();
}
}
}

View file

@ -2,49 +2,22 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 22.02.2016. * Created by mike on 22.02.2016.
*/ */
public class BroadcastSgvs { 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) { public static void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) {
List<JSONArray> splitted = BroadcastTreatment.splitArray(sgvs); List<JSONArray> splitted = BroadcastTreatment.splitArray(sgvs);

View file

@ -3,18 +3,16 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -23,7 +21,7 @@ import info.nightscout.utils.SP;
* Created by mike on 24.02.2016. * Created by mike on 24.02.2016.
*/ */
public class BroadcastStatus { 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) { public static void handleNewStatus(NSSettingsStatus status, Context context, boolean isDelta) {
LocalBroadcastManager.getInstance(MainApp.instance()) LocalBroadcastManager.getInstance(MainApp.instance())

View file

@ -15,14 +15,15 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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; import info.nightscout.utils.SP;
/** /**
* Created by mike on 20.02.2016. * Created by mike on 20.02.2016.
*/ */
public class BroadcastTreatment { 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) { 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) { public static void handleChangedTreatment(JSONArray treatments, boolean isDelta) {
List<JSONArray> splitted = splitArray(treatments); List<JSONArray> 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) { public static void handleRemovedTreatment(JSONArray treatments, boolean isDelta) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();

View file

@ -2,27 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager; import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONObject; 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.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 26.06.2016. * Created by mike on 26.06.2016.
*/ */
public class BroadcastUrgentAlarm { public class BroadcastUrgentAlarm {
private static Logger log = LoggerFactory.getLogger(BroadcastUrgentAlarm.class);
public static void handleUrgentAlarm(JSONObject urgentalarm, Context context) { public static void handleUrgentAlarm(JSONObject urgentalarm, Context context) {
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString("data", urgentalarm.toString()); bundle.putString("data", urgentalarm.toString());

View file

@ -8,32 +8,36 @@ import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
/** /**
* Created by mike on 02.07.2016. * Created by mike on 02.07.2016.
*/ */
public class DbLogger { 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) { public static void dbAdd(Intent intent, String data) {
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0);
if (q.size() < 1) { 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"); log.error("DBADD No receivers");
} else if (Config.logNSUpload) } else if (L.isEnabled(L.NSCLIENT)) {
log.debug("DBADD dbAdd " + q.size() + " receivers " + data); 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<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0);
if (q.size() < 1) { 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"); log.error("DBREMOVE No receivers");
} else if (Config.logNSUpload) } else if (L.isEnabled(L.NSCLIENT)) {
log.debug("DBREMOVE dbRemove " + q.size() + " receivers " + data); if (L.isEnabled(L.NSCLIENT))
log.debug("DBREMOVE dbRemove " + q.size() + " receivers " + data);
}
} }
} }

View file

@ -5,12 +5,14 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
/** /**
* Created by mike on 11.06.2017. * Created by mike on 11.06.2017.
*/ */
public class NSAlarm { public class NSAlarm {
private static Logger log = LoggerFactory.getLogger(NSAlarm.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
JSONObject data; JSONObject data;

View file

@ -5,8 +5,10 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
public class NSCal { public class NSCal {
private static Logger log = LoggerFactory.getLogger(NSCal.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public long date; public long date;
public double slope; public double slope;
public double intercept; public double intercept;
@ -20,7 +22,7 @@ public class NSCal {
scale = json.getDouble("scale"); scale = json.getDouble("scale");
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
log.debug("Data: " + json.toString()); log.error("Data: " + json.toString());
} }
} }
} }

View file

@ -1,8 +1,11 @@
package info.nightscout.androidaps.plugins.NSClientInternal.data; package info.nightscout.androidaps.plugins.NSClientInternal.data;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html; import android.text.Html;
import android.text.Spanned; import android.text.Spanned;
import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -13,7 +16,10 @@ import java.util.Iterator;
import java.util.Map; import java.util.Map;
import info.nightscout.androidaps.R; 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.plugins.Loop.APSResult;
import info.nightscout.androidaps.logging.BundleLogger;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -73,7 +79,7 @@ import info.nightscout.utils.SP;
} }
*/ */
public class NSDeviceStatus { public class NSDeviceStatus {
private static Logger log = LoggerFactory.getLogger(NSDeviceStatus.class); private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
private static NSDeviceStatus instance = null; private static NSDeviceStatus instance = null;
@ -88,6 +94,41 @@ public class NSDeviceStatus {
public 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) { public NSDeviceStatus setData(JSONObject obj) {
this.data = obj; this.data = obj;
updatePumpData(obj); updatePumpData(obj);

View file

@ -5,8 +5,10 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
public class NSMbg { public class NSMbg {
private static Logger log = LoggerFactory.getLogger(NSMbg.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public long date; public long date;
public double mbg; public double mbg;
public String json; public String json;
@ -18,7 +20,7 @@ public class NSMbg {
this.json = json.toString(); this.json = json.toString();
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
log.debug("Data: " + json.toString()); log.error("Data: " + json.toString());
} }
} }
} }

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.plugins.NSClientInternal.data; 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 android.support.annotation.Nullable;
import org.json.JSONException; import org.json.JSONException;
@ -10,6 +13,16 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import java.util.Objects; 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", "status": "ok",
@ -101,7 +114,7 @@ import java.util.Objects;
} }
*/ */
public class NSSettingsStatus { public class NSSettingsStatus {
private static Logger log = LoggerFactory.getLogger(NSSettingsStatus.class); private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
private static NSSettingsStatus instance = null; private static NSSettingsStatus instance = null;
@ -111,6 +124,8 @@ public class NSSettingsStatus {
return instance; return instance;
} }
public String nightscoutVersionName = "";
private JSONObject data = null; private JSONObject data = null;
public NSSettingsStatus() { public NSSettingsStatus() {
@ -121,6 +136,59 @@ public class NSSettingsStatus {
return this; 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() { public String getName() {
return getStringOrNull("name"); return getStringOrNull("name");
} }
@ -134,7 +202,7 @@ public class NSSettingsStatus {
} }
public Date getServerTime() { public Date getServerTime() {
return getDateOrNull("versionNum"); return getDateOrNull("serverTime");
} }
public boolean getApiEnabled() { public boolean getApiEnabled() {
@ -202,13 +270,11 @@ public class NSSettingsStatus {
if (settingsO.has("thresholds")) { if (settingsO.has("thresholds")) {
JSONObject tObject = settingsO.getJSONObject("thresholds"); JSONObject tObject = settingsO.getJSONObject("thresholds");
if (tObject.has(what)) { if (tObject.has(what)) {
Double result = tObject.getDouble(what); return tObject.getDouble(what);
return result;
} }
} }
if (settingsO.has("alarmTimeagoWarnMins") && Objects.equals(what, "alarmTimeagoWarnMins")) { if (settingsO.has("alarmTimeagoWarnMins") && Objects.equals(what, "alarmTimeagoWarnMins")) {
Double result = settingsO.getDouble(what); return settingsO.getDouble(what);
return result;
} }
} }
} catch (JSONException e) { } catch (JSONException e) {

View file

@ -5,12 +5,14 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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} * {"mgdl":105,"mills":1455136282375,"device":"xDrip-BluetoothWixel","direction":"Flat","filtered":98272,"unfiltered":98272,"noise":1,"rssi":100}
*/ */
public class NSSgv { public class NSSgv {
private static Logger log = LoggerFactory.getLogger(NSSgv.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
private JSONObject data; private JSONObject data;

View file

@ -7,8 +7,10 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.logging.L;
public class NSTreatment { public class NSTreatment {
private static Logger log = LoggerFactory.getLogger(NSTreatment.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
private JSONObject data; private JSONObject data;
private String action = null; // "update", "remove" or null (add) private String action = null; // "update", "remove" or null (add)

View file

@ -11,15 +11,15 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; 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.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck; import info.nightscout.androidaps.plugins.NSClientInternal.data.AlarmAck;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService; import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class AckAlarmReceiver extends BroadcastReceiver { public class AckAlarmReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(AckAlarmReceiver.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
@Override @Override
@ -32,7 +32,8 @@ public class AckAlarmReceiver extends BroadcastReceiver {
return; return;
} }
if (SP.getBoolean(R.string.key_ns_noupload, false)) { 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; return;
} }
wakeLock.acquire(); wakeLock.acquire();

View file

@ -15,6 +15,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.interfaces.PluginType; 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.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastTreatment;
@ -22,7 +23,7 @@ import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class DBAccessReceiver extends BroadcastReceiver { public class DBAccessReceiver extends BroadcastReceiver {
private static Logger log = LoggerFactory.getLogger(DBAccessReceiver.class); private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
@Override @Override
@ -43,18 +44,21 @@ public class DBAccessReceiver extends BroadcastReceiver {
try { try {
collection = bundles.getString("collection"); collection = bundles.getString("collection");
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e);
} }
try { try {
_id = bundles.getString("_id"); _id = bundles.getString("_id");
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e);
} }
try { try {
data = new JSONObject(bundles.getString("data")); data = new JSONObject(bundles.getString("data"));
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e);
} }
if (data == null && !action.equals("dbRemove") || _id == null && action.equals("dbRemove")) { 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; return;
} }
@ -70,7 +74,7 @@ public class DBAccessReceiver extends BroadcastReceiver {
} }
if (!isAllowedCollection(collection)) { if (!isAllowedCollection(collection)) {
log.debug("DBACCESS wrong collection specified"); log.error("DBACCESS wrong collection specified");
return; return;
} }

View file

@ -9,7 +9,6 @@ import android.os.HandlerThread;
import android.os.IBinder; import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.hash.Hashing; import com.google.common.hash.Hashing;
import com.j256.ormlite.dao.CloseableIterator; import com.j256.ormlite.dao.CloseableIterator;
@ -23,7 +22,6 @@ import org.slf4j.LoggerFactory;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Date;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; 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.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginType; 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.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck; import info.nightscout.androidaps.plugins.NSClientInternal.acks.NSAddAck;
@ -70,7 +69,7 @@ import io.socket.client.Socket;
import io.socket.emitter.Emitter; import io.socket.emitter.Emitter;
public class NSClientService extends Service { 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; static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder(); private IBinder mBinder = new NSClientService.LocalBinder();
@ -156,13 +155,13 @@ public class NSClientService extends Service {
@Subscribe @Subscribe
public void onStatusEvent(EventAppExit event) { public void onStatusEvent(EventAppExit event) {
if (Config.logFunctionCalls) if (L.isEnabled(L.NSCLIENT))
log.debug("EventAppExit received"); log.debug("EventAppExit received");
destroy(); destroy();
stopSelf(); stopSelf();
if (Config.logFunctionCalls) if (L.isEnabled(L.NSCLIENT))
log.debug("EventAppExit finished"); log.debug("EventAppExit finished");
} }
@ -250,7 +249,8 @@ public class NSClientService extends Service {
private Emitter.Listener onDisconnect = new Emitter.Listener() { private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override @Override
public void call(Object... args) { 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")); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
} }
}; };
@ -326,8 +326,7 @@ public class NSClientService extends Service {
private Emitter.Listener onPing = new Emitter.Listener() { private Emitter.Listener onPing = new Emitter.Listener() {
@Override @Override
public void call(final Object... args) { 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 // send data if there is something waiting
resend("Ping received"); resend("Ping received");
} }
@ -352,16 +351,18 @@ public class NSClientService extends Service {
data = (JSONObject) args[0]; data = (JSONObject) args[0];
} catch (Exception e) { } catch (Exception e) {
FabricPrivacy.log("Wrong Announcement from NS: " + args[0]); FabricPrivacy.log("Wrong Announcement from NS: " + args[0]);
log.error("Unhandled exception", e);
return; return;
} }
if (Config.detailedLog) try {
try { MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received")));
MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); } catch (Exception e) {
} catch (Exception e) { FabricPrivacy.logException(e);
FabricPrivacy.logException(e); log.error("Unhandled exception", e);
} }
BroadcastAnnouncement.handleAnnouncement(data, getApplicationContext()); 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 @Override
public void call(final Object... args) { 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; JSONObject data;
try { try {
data = (JSONObject) args[0]; data = (JSONObject) args[0];
} catch (Exception e) { } catch (Exception e) {
FabricPrivacy.log("Wrong alarm from NS: " + args[0]); FabricPrivacy.log("Wrong alarm from NS: " + args[0]);
log.error("Unhandled exception", e);
return; return;
} }
BroadcastAlarm.handleAlarm(data, getApplicationContext()); 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]; data = (JSONObject) args[0];
} catch (Exception e) { } catch (Exception e) {
FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]);
log.error("Unhandled exception", e);
return; return;
} }
if (Config.detailedLog) MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received"));
MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received"));
BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext()); 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]; data = (JSONObject) args[0];
} catch (Exception e) { } catch (Exception e) {
FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]); FabricPrivacy.log("Wrong Urgent alarm from NS: " + args[0]);
log.error("Unhandled exception", e);
return; return;
} }
if (Config.detailedLog) MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received"));
MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received"));
BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext()); 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) { public void resend(final String reason) {
if (UploadQueue.size() == 0) if (UploadQueue.size() == 0)
return; return;
@ -766,7 +759,8 @@ public class NSClientService extends Service {
if (mSocket == null || !mSocket.connected()) return; if (mSocket == null || !mSocket.connected()) return;
if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) {
log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); if (L.isEnabled(L.NSCLIENT))
log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec");
return; return;
} }
lastResendTime = System.currentTimeMillis(); lastResendTime = System.currentTimeMillis();

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.OpenAPSAMA;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context; import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function; import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJSON; import org.mozilla.javascript.NativeJSON;
@ -18,7 +17,6 @@ import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback;
@ -35,7 +34,7 @@ import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class DetermineBasalAdapterAMAJS { public class DetermineBasalAdapterAMAJS {
private static Logger log = LoggerFactory.getLogger(DetermineBasalAdapterAMAJS.class); private static Logger log = LoggerFactory.getLogger(L.APS);
private ScriptReader mScriptReader = null; private ScriptReader mScriptReader = null;
@ -56,23 +55,24 @@ public class DetermineBasalAdapterAMAJS {
private String scriptDebug = ""; private String scriptDebug = "";
public DetermineBasalAdapterAMAJS(ScriptReader scriptReader) throws IOException { public DetermineBasalAdapterAMAJS(ScriptReader scriptReader) {
mScriptReader = scriptReader; mScriptReader = scriptReader;
} }
public DetermineBasalResultAMA invoke() { public DetermineBasalResultAMA invoke() {
if (L.isEnabled(L.APS)) {
log.debug(">>> Invoking detemine_basal <<<"); log.debug(">>> Invoking detemine_basal <<<");
log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString())); log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString()));
log.debug("IOB data: " + (storedIobData = mIobData.toString())); log.debug("IOB data: " + (storedIobData = mIobData.toString()));
log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString())); log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString()));
log.debug("Profile: " + (storedProfile = mProfile.toString())); log.debug("Profile: " + (storedProfile = mProfile.toString()));
log.debug("Meal data: " + (storedMeal_data = mMealData.toString())); log.debug("Meal data: " + (storedMeal_data = mMealData.toString()));
if (mAutosensData != null) if (mAutosensData != null)
log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString())); log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString()));
else else
log.debug("Autosens data: " + (storedAutosens_data = "undefined")); log.debug("Autosens data: " + (storedAutosens_data = "undefined"));
}
DetermineBasalResultAMA determineBasalResultAMA = null; DetermineBasalResultAMA determineBasalResultAMA = null;
@ -119,7 +119,7 @@ public class DetermineBasalAdapterAMAJS {
// Parse the jsResult object to a JSON-String // Parse the jsResult object to a JSON-String
String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString();
if (Config.logAPSResult) if (L.isEnabled(L.APS))
log.debug("Result: " + result); log.debug("Result: " + result);
try { try {
determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result)); determineBasalResultAMA = new DetermineBasalResultAMA(jsResult, new JSONObject(result));
@ -127,17 +127,13 @@ public class DetermineBasalAdapterAMAJS {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
} else { } else {
log.debug("Problem loading JS Functions"); log.error("Problem loading JS Functions");
} }
} catch (IOException e) { } catch (IOException e) {
log.debug("IOException"); log.error("IOException");
} catch (RhinoException e) { } catch (RhinoException e) {
log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
} catch (IllegalAccessException e) { } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
log.error(e.toString());
} catch (InstantiationException e) {
log.error(e.toString());
} catch (InvocationTargetException e) {
log.error(e.toString()); log.error(e.toString());
} finally { } finally {
Context.exit(); Context.exit();
@ -214,7 +210,7 @@ public class DetermineBasalAdapterAMAJS {
mProfile.put("temptargetSet", tempTargetSet); mProfile.put("temptargetSet", tempTargetSet);
mProfile.put("autosens_adjust_targets", SP.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true)); mProfile.put("autosens_adjust_targets", SP.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true));
//align with max-absorption model in AMA sensitivity //align with max-absorption model in AMA sensitivity
if(mealData.usedMinCarbsImpact > 0){ if (mealData.usedMinCarbsImpact > 0) {
mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact);
} else { } else {
mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); 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; if (jsonObject == null) return Undefined.instance;
Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), new Callable() { Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]);
@Override
public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) {
return objects[1];
}
});
return param; 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, "{myarray: " + jsonArray.toString() + " }", new Callable() {
Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), new Callable() { Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), (context, scriptable, scriptable1, objects) -> objects[1]);
@Override
public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) {
return objects[1];
}
});
return param; return param;
} }
public String readFile(String filename) throws IOException { private String readFile(String filename) throws IOException {
byte[] bytes = mScriptReader.readFile(filename); byte[] bytes = mScriptReader.readFile(filename);
String string = new String(bytes, "UTF-8"); String string = new String(bytes, "UTF-8");
if (string.startsWith("#!/usr/bin/env node")) { if (string.startsWith("#!/usr/bin/env node")) {

View file

@ -6,11 +6,12 @@ import org.mozilla.javascript.NativeObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
public class DetermineBasalResultAMA extends APSResult { 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 eventualBG;
private double snoozeBG; private double snoozeBG;
@ -47,7 +48,7 @@ public class DetermineBasalResultAMA extends APSResult {
bolusRequested = false; bolusRequested = false;
} }
public DetermineBasalResultAMA() { private DetermineBasalResultAMA() {
hasPredictions = true; hasPredictions = true;
} }

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.OpenAPSAMA;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -19,6 +18,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
@ -26,7 +26,7 @@ import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.utils.JSONFormatter;
public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnClickListener { 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; Button run;
TextView lastRunView; TextView lastRunView;
@ -43,29 +43,23 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { 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 = (Button) view.findViewById(R.id.openapsma_run);
run.setOnClickListener(this); run.setOnClickListener(this);
lastRunView = (TextView) view.findViewById(R.id.openapsma_lastrun); lastRunView = (TextView) view.findViewById(R.id.openapsma_lastrun);
glucoseStatusView = (TextView) view.findViewById(R.id.openapsma_glucosestatus); glucoseStatusView = (TextView) view.findViewById(R.id.openapsma_glucosestatus);
currentTempView = (TextView) view.findViewById(R.id.openapsma_currenttemp); currentTempView = (TextView) view.findViewById(R.id.openapsma_currenttemp);
iobDataView = (TextView) view.findViewById(R.id.openapsma_iobdata); iobDataView = (TextView) view.findViewById(R.id.openapsma_iobdata);
profileView = (TextView) view.findViewById(R.id.openapsma_profile); profileView = (TextView) view.findViewById(R.id.openapsma_profile);
mealDataView = (TextView) view.findViewById(R.id.openapsma_mealdata); mealDataView = (TextView) view.findViewById(R.id.openapsma_mealdata);
autosensDataView = (TextView) view.findViewById(R.id.openapsma_autosensdata); autosensDataView = (TextView) view.findViewById(R.id.openapsma_autosensdata);
scriptdebugView = (TextView) view.findViewById(R.id.openapsma_scriptdebugdata); scriptdebugView = (TextView) view.findViewById(R.id.openapsma_scriptdebugdata);
resultView = (TextView) view.findViewById(R.id.openapsma_result); resultView = (TextView) view.findViewById(R.id.openapsma_result);
requestView = (TextView) view.findViewById(R.id.openapsma_request); requestView = (TextView) view.findViewById(R.id.openapsma_request);
updateGUI(); updateGUI();
return view; return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
}
return null;
} }
@Override @Override
@ -93,35 +87,32 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli
protected void updateGUI() { protected void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override DetermineBasalResultAMA lastAPSResult = OpenAPSAMAPlugin.getPlugin().lastAPSResult;
public void run() { if (lastAPSResult != null) {
DetermineBasalResultAMA lastAPSResult = OpenAPSAMAPlugin.getPlugin().lastAPSResult; resultView.setText(JSONFormatter.format(lastAPSResult.json));
if (lastAPSResult != null) { requestView.setText(lastAPSResult.toSpanned());
resultView.setText(JSONFormatter.format(lastAPSResult.json)); }
requestView.setText(lastAPSResult.toSpanned()); DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS = OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS;
} if (determineBasalAdapterAMAJS != null) {
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS = OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS; glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getGlucoseStatusParam()));
if (determineBasalAdapterAMAJS != null) { currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam()));
glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getGlucoseStatusParam())); try {
currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam())); JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam());
try { iobDataView.setText(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0)));
JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam()); } catch (JSONException e) {
iobDataView.setText(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))); log.error("Unhandled exception", e);
} catch (JSONException e) { iobDataView.setText("JSONException");
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()));
} }
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) { void updateResultGUI(final String text) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override resultView.setText(text);
public void run() { glucoseStatusView.setText("");
resultView.setText(text); currentTempView.setText("");
glucoseStatusView.setText(""); iobDataView.setText("");
currentTempView.setText(""); profileView.setText("");
iobDataView.setText(""); mealDataView.setText("");
profileView.setText(""); autosensDataView.setText("");
mealDataView.setText(""); scriptdebugView.setText("");
autosensDataView.setText(""); requestView.setText("");
scriptdebugView.setText(""); lastRunView.setText("");
requestView.setText("");
lastRunView.setText("");
}
}); });
} }
} }

View file

@ -1,14 +1,11 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA; package info.nightscout.androidaps.plugins.OpenAPSAMA;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
@ -22,7 +19,9 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
@ -39,7 +38,7 @@ import info.nightscout.utils.Round;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class OpenAPSAMAPlugin extends PluginBase implements APSInterface { 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; private static OpenAPSAMAPlugin openAPSAMAPlugin;
@ -91,15 +90,11 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
@Override @Override
public void invoke(String initiator, boolean tempBasalFallback) { 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; lastAPSResult = null;
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS;
try { determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
determineBasalAdapterAMAJS = new DetermineBasalAdapterAMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
} catch (IOException e) {
log.error(e.getMessage(), e);
return;
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = MainApp.getConfigBuilder().getProfile();
@ -107,21 +102,21 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (profile == null) { if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); 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)); log.debug(MainApp.gs(R.string.noprofileselected));
return; return;
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); 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)); log.debug(MainApp.gs(R.string.openapsma_disabled));
return; return;
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); 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)); log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return; return;
} }
@ -139,11 +134,13 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
Date start = new Date(); Date start = new Date();
Date startPart = new Date(); Date startPart = new Date();
IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayInDia(profile);
Profiler.log(log, "calculateIobArrayInDia()", startPart); if (L.isEnabled(L.APS))
Profiler.log(log, "calculateIobArrayInDia()", startPart);
startPart = new Date(); startPart = new Date();
MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); 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(); double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value();
@ -163,7 +160,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (!HardLimits.checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) if (!HardLimits.checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
return; 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; return;
if (!HardLimits.checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF)) if (!HardLimits.checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return; return;
@ -184,8 +181,10 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
lastAutosensResult = new AutosensResult(); lastAutosensResult = new AutosensResult();
lastAutosensResult.sensResult = "autosens disabled"; lastAutosensResult.sensResult = "autosens disabled";
} }
Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); if (L.isEnabled(L.APS))
Profiler.log(log, "AMA data gathering", start); Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
if (L.isEnabled(L.APS))
Profiler.log(log, "AMA data gathering", start);
start = new Date(); start = new Date();
@ -200,7 +199,8 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
DetermineBasalResultAMA determineBasalResultAMA = determineBasalAdapterAMAJS.invoke(); 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 // Fix bug determine basal
if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress()) if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
determineBasalResultAMA.tempBasalRequested = false; determineBasalResultAMA.tempBasalRequested = false;

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.OpenAPSMA;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context; import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function; import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJSON; import org.mozilla.javascript.NativeJSON;
@ -16,7 +15,6 @@ import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; 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.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class DetermineBasalAdapterMAJS { 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 mProfile;
private JSONObject mGlucoseStatus; private JSONObject mGlucoseStatus;
private JSONObject mIobData; private JSONObject mIobData;
@ -39,12 +38,12 @@ public class DetermineBasalAdapterMAJS {
private JSONObject mCurrentTemp; private JSONObject mCurrentTemp;
private String storedCurrentTemp = null; private String storedCurrentTemp = null;
public String storedIobData = null; private String storedIobData = null;
private String storedGlucoseStatus = null; private String storedGlucoseStatus = null;
private String storedProfile = null; private String storedProfile = null;
private String storedMeal_data = null; private String storedMeal_data = null;
public DetermineBasalAdapterMAJS(ScriptReader scriptReader) throws IOException { DetermineBasalAdapterMAJS(ScriptReader scriptReader) {
mScriptReader = scriptReader; mScriptReader = scriptReader;
} }
@ -97,7 +96,7 @@ public class DetermineBasalAdapterMAJS {
// Parse the jsResult object to a JSON-String // Parse the jsResult object to a JSON-String
String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString();
if (Config.logAPSResult) if (L.isEnabled(L.APS))
log.debug("Result: " + result); log.debug("Result: " + result);
try { try {
determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result)); determineBasalResultMA = new DetermineBasalResultMA(jsResult, new JSONObject(result));
@ -108,14 +107,10 @@ public class DetermineBasalAdapterMAJS {
log.debug("Problem loading JS Functions"); log.debug("Problem loading JS Functions");
} }
} catch (IOException e) { } catch (IOException e) {
log.debug("IOException"); log.error("IOException");
} catch (RhinoException e) { } catch (RhinoException e) {
log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
} catch (IllegalAccessException e) { } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
log.error(e.toString());
} catch (InstantiationException e) {
log.error(e.toString());
} catch (InvocationTargetException e) {
log.error(e.toString()); log.error(e.toString());
} finally { } finally {
Context.exit(); Context.exit();
@ -210,7 +205,7 @@ public class DetermineBasalAdapterMAJS {
mMealData.put("boluses", mealData.boluses); mMealData.put("boluses", mealData.boluses);
} }
public String readFile(String filename) throws IOException { private String readFile(String filename) throws IOException {
byte[] bytes = mScriptReader.readFile(filename); byte[] bytes = mScriptReader.readFile(filename);
String string = new String(bytes, "UTF-8"); String string = new String(bytes, "UTF-8");
if (string.startsWith("#!/usr/bin/env node")) { if (string.startsWith("#!/usr/bin/env node")) {
@ -219,13 +214,8 @@ public class DetermineBasalAdapterMAJS {
return string; return string;
} }
public Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) { private Object makeParam(JSONObject jsonObject, Context rhino, Scriptable scope) {
Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), new Callable() { Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]);
@Override
public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) {
return objects[1];
}
});
return param; return param;
} }

View file

@ -6,17 +6,18 @@ import org.mozilla.javascript.NativeObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
public class DetermineBasalResultMA extends 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 JSONObject json = new JSONObject();
public double eventualBG; private double eventualBG;
public double snoozeBG; private double snoozeBG;
public String mealAssist; private String mealAssist;
public DetermineBasalResultMA(NativeObject result, JSONObject j) { DetermineBasalResultMA(NativeObject result, JSONObject j) {
json = j; json = j;
if (result.containsKey("error")) { if (result.containsKey("error")) {
reason = (String) result.get("error"); reason = (String) result.get("error");
@ -49,7 +50,7 @@ public class DetermineBasalResultMA extends APSResult {
} }
} }
public DetermineBasalResultMA() { private DetermineBasalResultMA() {
} }
@Override @Override

View file

@ -4,8 +4,7 @@ import org.mozilla.javascript.ScriptableObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.ToastUtils;
/** /**
* Created by adrian on 15/10/17. * Created by adrian on 15/10/17.
@ -14,10 +13,10 @@ import info.nightscout.utils.ToastUtils;
public class LoggerCallback extends ScriptableObject { 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(); private static StringBuffer errorBuffer = new StringBuffer();
static StringBuffer logBuffer = new StringBuffer(); private static StringBuffer logBuffer = new StringBuffer();
public LoggerCallback() { public LoggerCallback() {
@ -36,26 +35,27 @@ public class LoggerCallback extends ScriptableObject {
} }
public void jsFunction_log(Object obj1) { 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(obj1.toString());
logBuffer.append(' '); logBuffer.append(' ');
} }
public void jsFunction_error(Object obj1) { 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(obj1.toString());
errorBuffer.append(' '); errorBuffer.append(' ');
} }
public static String getScriptDebug() {
public static String getScriptDebug(){
String ret = ""; String ret = "";
if(errorBuffer.length() > 0){ if (errorBuffer.length() > 0) {
ret += "e:\n" + errorBuffer.toString(); ret += "e:\n" + errorBuffer.toString();
} }
if(ret.length() > 0 && logBuffer.length() > 0) ret += '\n'; if (ret.length() > 0 && logBuffer.length() > 0) ret += '\n';
if(logBuffer.length() > 0){ if (logBuffer.length() > 0) {
ret += "d:\n" + logBuffer.toString(); ret += "d:\n" + logBuffer.toString();
} }
return ret; return ret;

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.OpenAPSMA;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
@ -12,10 +11,6 @@ import android.widget.TextView;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; 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.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
@ -24,8 +19,6 @@ import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.utils.JSONFormatter;
public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener { public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(OpenAPSMAFragment.class);
Button run; Button run;
TextView lastRunView; TextView lastRunView;
TextView glucoseStatusView; TextView glucoseStatusView;
@ -87,25 +80,22 @@ public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClic
protected void updateGUI() { protected void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override DetermineBasalResultMA lastAPSResult = OpenAPSMAPlugin.getPlugin().lastAPSResult;
public void run() { if (lastAPSResult != null) {
DetermineBasalResultMA lastAPSResult = OpenAPSMAPlugin.getPlugin().lastAPSResult; resultView.setText(JSONFormatter.format(lastAPSResult.json));
if (lastAPSResult != null) { requestView.setText(lastAPSResult.toSpanned());
resultView.setText(JSONFormatter.format(lastAPSResult.json)); }
requestView.setText(lastAPSResult.toSpanned()); DetermineBasalAdapterMAJS determineBasalAdapterMAJS = OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS;
} if (determineBasalAdapterMAJS != null) {
DetermineBasalAdapterMAJS determineBasalAdapterMAJS = OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS; glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getGlucoseStatusParam()));
if (determineBasalAdapterMAJS != null) { currentTempView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getCurrentTempParam()));
glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getGlucoseStatusParam())); iobDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getIobDataParam()));
currentTempView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getCurrentTempParam())); profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam()));
iobDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getIobDataParam())); mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam()));
profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam())); }
mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam())); if (OpenAPSMAPlugin.getPlugin().lastAPSRun != null) {
} lastRunView.setText(OpenAPSMAPlugin.getPlugin().lastAPSRun.toLocaleString());
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) { private void updateResultGUI(final String text) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override resultView.setText(text);
public void run() { glucoseStatusView.setText("");
resultView.setText(text); currentTempView.setText("");
glucoseStatusView.setText(""); iobDataView.setText("");
currentTempView.setText(""); profileView.setText("");
iobDataView.setText(""); mealDataView.setText("");
profileView.setText(""); requestView.setText("");
mealDataView.setText(""); lastRunView.setText("");
requestView.setText("");
lastRunView.setText("");
}
}); });
} }
} }

View file

@ -4,10 +4,8 @@ import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
@ -21,6 +19,7 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
@ -39,7 +38,7 @@ import static info.nightscout.utils.HardLimits.verifyHardLimits;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class OpenAPSMAPlugin extends PluginBase implements APSInterface { 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; private static OpenAPSMAPlugin openAPSMAPlugin;
@ -90,15 +89,11 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
@Override @Override
public void invoke(String initiator, boolean tempBasalFallback) { 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; lastAPSResult = null;
DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null; DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null;
try { determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
} catch (IOException e) {
log.error(e.getMessage(), e);
return;
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = MainApp.getConfigBuilder().getProfile();
@ -106,21 +101,21 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
if (profile == null) { if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); 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)); log.debug(MainApp.gs(R.string.noprofileselected));
return; return;
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); 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)); log.debug(MainApp.gs(R.string.openapsma_disabled));
return; return;
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); 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)); log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return; return;
} }
@ -147,7 +142,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); 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]); 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]); maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
@ -177,7 +173,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", 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(); long now = System.currentTimeMillis();

View file

@ -6,7 +6,7 @@ import info.nightscout.androidaps.events.EventUpdateGui;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class EventOpenAPSUpdateResultGui extends EventUpdateGui { public class EventOpenAPSUpdateResultGui extends EventUpdateGui {
public String text = null; public String text;
public EventOpenAPSUpdateResultGui(String text) { public EventOpenAPSUpdateResultGui(String text) {
this.text = text; this.text = text;

View file

@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.OpenAPSSMB;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context; import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function; import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJSON; import org.mozilla.javascript.NativeJSON;
@ -18,7 +17,6 @@ import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback;
@ -35,10 +34,10 @@ import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class DetermineBasalAdapterSMBJS { 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 mProfile;
private JSONObject mGlucoseStatus; private JSONObject mGlucoseStatus;
private JSONArray mIobData; private JSONArray mIobData;
@ -64,7 +63,7 @@ public class DetermineBasalAdapterSMBJS {
* Main code * Main code
*/ */
public DetermineBasalAdapterSMBJS(ScriptReader scriptReader) throws IOException { DetermineBasalAdapterSMBJS(ScriptReader scriptReader) {
mScriptReader = scriptReader; mScriptReader = scriptReader;
} }
@ -72,19 +71,21 @@ public class DetermineBasalAdapterSMBJS {
public DetermineBasalResultSMB invoke() { public DetermineBasalResultSMB invoke() {
log.debug(">>> Invoking detemine_basal <<<"); if (L.isEnabled(L.APS)) {
log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString())); log.debug(">>> Invoking detemine_basal <<<");
log.debug("IOB data: " + (storedIobData = mIobData.toString())); log.debug("Glucose status: " + (storedGlucoseStatus = mGlucoseStatus.toString()));
log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString())); log.debug("IOB data: " + (storedIobData = mIobData.toString()));
log.debug("Profile: " + (storedProfile = mProfile.toString())); log.debug("Current temp: " + (storedCurrentTemp = mCurrentTemp.toString()));
log.debug("Meal data: " + (storedMeal_data = mMealData.toString())); log.debug("Profile: " + (storedProfile = mProfile.toString()));
if (mAutosensData != null) log.debug("Meal data: " + (storedMeal_data = mMealData.toString()));
log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString())); if (mAutosensData != null)
else log.debug("Autosens data: " + (storedAutosens_data = mAutosensData.toString()));
log.debug("Autosens data: " + (storedAutosens_data = "undefined")); else
log.debug("Reservoir data: " + "undefined"); log.debug("Autosens data: " + (storedAutosens_data = "undefined"));
log.debug("MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed)); log.debug("Reservoir data: " + "undefined");
log.debug("SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed)); log.debug("MicroBolusAllowed: " + (storedMicroBolusAllowed = "" + mMicrobolusAllowed));
log.debug("SMBAlwaysAllowed: " + (storedSMBAlwaysAllowed = "" + mSMBAlwaysAllowed));
}
DetermineBasalResultSMB determineBasalResultSMB = null; DetermineBasalResultSMB determineBasalResultSMB = null;
@ -135,7 +136,7 @@ public class DetermineBasalAdapterSMBJS {
// Parse the jsResult object to a JSON-String // Parse the jsResult object to a JSON-String
String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString(); String result = NativeJSON.stringify(rhino, scope, jsResult, null, null).toString();
if (Config.logAPSResult) if (L.isEnabled(L.APS))
log.debug("Result: " + result); log.debug("Result: " + result);
try { try {
determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result)); determineBasalResultSMB = new DetermineBasalResultSMB(new JSONObject(result));
@ -143,17 +144,13 @@ public class DetermineBasalAdapterSMBJS {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
} else { } else {
log.debug("Problem loading JS Functions"); log.error("Problem loading JS Functions");
} }
} catch (IOException e) { } catch (IOException e) {
log.debug("IOException"); log.error("IOException");
} catch (RhinoException e) { } catch (RhinoException e) {
log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString()); log.error("RhinoException: (" + e.lineNumber() + "," + e.columnNumber() + ") " + e.toString());
} catch (IllegalAccessException e) { } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
log.error(e.toString());
} catch (InstantiationException e) {
log.error(e.toString());
} catch (InvocationTargetException e) {
log.error(e.toString()); log.error(e.toString());
} finally { } finally {
Context.exit(); Context.exit();
@ -244,7 +241,7 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("maxCOB", SMBDefaults.maxCOB); mProfile.put("maxCOB", SMBDefaults.maxCOB);
mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps); mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps);
//align with max-absorption model in AMA sensitivity //align with max-absorption model in AMA sensitivity
if(mealData.usedMinCarbsImpact > 0){ if (mealData.usedMinCarbsImpact > 0) {
mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact);
} else { } else {
mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); 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; if (jsonObject == null) return Undefined.instance;
Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), new Callable() { Object param = NativeJSON.parse(rhino, scope, jsonObject.toString(), (context, scriptable, scriptable1, objects) -> objects[1]);
@Override
public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) {
return objects[1];
}
});
return param; 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, "{myarray: " + jsonArray.toString() + " }", new Callable() {
Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), new Callable() { Object param = NativeJSON.parse(rhino, scope, jsonArray.toString(), (context, scriptable, scriptable1, objects) -> objects[1]);
@Override
public Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object[] objects) {
return objects[1];
}
});
return param; return param;
} }
public String readFile(String filename) throws IOException { private String readFile(String filename) throws IOException {
byte[] bytes = mScriptReader.readFile(filename); byte[] bytes = mScriptReader.readFile(filename);
String string = new String(bytes, "UTF-8"); String string = new String(bytes, "UTF-8");
if (string.startsWith("#!/usr/bin/env node")) { if (string.startsWith("#!/usr/bin/env node")) {

View file

@ -5,11 +5,12 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
public class DetermineBasalResultSMB extends APSResult { 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 eventualBG;
private double snoozeBG; private double snoozeBG;

View file

@ -21,6 +21,7 @@ import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
@ -28,7 +29,7 @@ import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.utils.JSONFormatter;
public class OpenAPSSMBFragment extends SubscriberFragment { 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) @BindView(R.id.openapsma_run)
Button run; Button run;
@ -84,40 +85,37 @@ public class OpenAPSSMBFragment extends SubscriberFragment {
protected void updateGUI() { protected void updateGUI() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override synchronized (OpenAPSSMBFragment.this) {
public void run() { if (!isBound()) return;
synchronized (OpenAPSSMBFragment.this) { OpenAPSSMBPlugin plugin = OpenAPSSMBPlugin.getPlugin();
if (!isBound()) return; DetermineBasalResultSMB lastAPSResult = plugin.lastAPSResult;
OpenAPSSMBPlugin plugin = OpenAPSSMBPlugin.getPlugin(); if (lastAPSResult != null) {
DetermineBasalResultSMB lastAPSResult = plugin.lastAPSResult; resultView.setText(JSONFormatter.format(lastAPSResult.json));
if (lastAPSResult != null) { requestView.setText(lastAPSResult.toSpanned());
resultView.setText(JSONFormatter.format(lastAPSResult.json)); }
requestView.setText(lastAPSResult.toSpanned()); DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = plugin.lastDetermineBasalAdapterSMBJS;
} if (determineBasalAdapterSMBJS != null) {
DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = plugin.lastDetermineBasalAdapterSMBJS; glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getGlucoseStatusParam()).toString().trim());
if (determineBasalAdapterSMBJS != null) { currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim());
glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getGlucoseStatusParam()).toString().trim()); try {
currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim()); JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam());
try { iobDataView.setText((String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim());
JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam()); } catch (JSONException e) {
iobDataView.setText((String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim()); log.error("Unhandled exception", e);
} catch (JSONException e) { iobDataView.setText("JSONException see log for details");
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());
} }
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) { void updateResultGUI(final String text) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override synchronized (OpenAPSSMBFragment.this) {
public void run() { if (isBound()) {
synchronized (OpenAPSSMBFragment.this) { resultView.setText(text);
if (isBound()) { glucoseStatusView.setText("");
resultView.setText(text); currentTempView.setText("");
glucoseStatusView.setText(""); iobDataView.setText("");
currentTempView.setText(""); profileView.setText("");
iobDataView.setText(""); mealDataView.setText("");
profileView.setText(""); autosensDataView.setText("");
mealDataView.setText(""); scriptdebugView.setText("");
autosensDataView.setText(""); requestView.setText("");
scriptdebugView.setText(""); lastRunView.setText("");
requestView.setText("");
lastRunView.setText("");
}
} }
} }
}); });

View file

@ -1,14 +1,11 @@
package info.nightscout.androidaps.plugins.OpenAPSSMB; package info.nightscout.androidaps.plugins.OpenAPSSMB;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
@ -23,17 +20,19 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; 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.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.HardLimits; import info.nightscout.utils.HardLimits;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.Profiler; import info.nightscout.utils.Profiler;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.ToastUtils; import info.nightscout.utils.ToastUtils;
@ -42,7 +41,7 @@ import info.nightscout.utils.ToastUtils;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { 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; private static OpenAPSSMBPlugin openAPSSMBPlugin;
@ -94,15 +93,11 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
@Override @Override
public void invoke(String initiator, boolean tempBasalFallback) { 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; lastAPSResult = null;
DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = null; DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS;
try { determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext()));
determineBasalAdapterSMBJS = new DetermineBasalAdapterSMBJS(new ScriptReader(MainApp.instance().getBaseContext()));
} catch (IOException e) {
log.error(e.getMessage(), e);
return;
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData(); GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = MainApp.getConfigBuilder().getProfile();
@ -110,21 +105,21 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (profile == null) { if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected))); 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)); log.debug(MainApp.gs(R.string.noprofileselected));
return; return;
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled))); 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)); log.debug(MainApp.gs(R.string.openapsma_disabled));
return; return;
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata))); 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)); log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return; return;
} }
@ -146,11 +141,13 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
Date start = new Date(); Date start = new Date();
Date startPart = new Date(); Date startPart = new Date();
IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(profile); IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(profile);
Profiler.log(log, "calculateIobArrayInDia()", startPart); if (L.isEnabled(L.APS))
Profiler.log(log, "calculateIobArrayInDia()", startPart);
startPart = new Date(); startPart = new Date();
MealData mealData = TreatmentsPlugin.getPlugin().getMealData(); 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(); double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value();
@ -170,7 +167,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA)) if (!checkOnlyHardLimits(profile.getDia(), "dia", HardLimits.MINDIA, HardLimits.MAXDIA))
return; return;
if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC)) if (!checkOnlyHardLimits(profile.getIcTimeFromMidnight(Profile.secondsFromMidnight()), "carbratio", HardLimits.MINIC, HardLimits.MAXIC))
return; return;
if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF)) if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return; return;
@ -200,8 +197,10 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering);
inputConstraints.copyReasons(advancedFiltering); inputConstraints.copyReasons(advancedFiltering);
Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); if (L.isEnabled(L.APS))
Profiler.log(log, "SMB data gathering", start); Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
if (L.isEnabled(L.APS))
Profiler.log(log, "SMB data gathering", start);
start = new Date(); start = new Date();
try { try {
@ -219,7 +218,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke(); 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? // TODO still needed with oref1?
// Fix bug determine basal // Fix bug determine basal
if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress()) if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())

View file

@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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 { public class ErrorDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(ErrorDialog.class); private static Logger log = LoggerFactory.getLogger(ErrorDialog.class);

View file

@ -4,7 +4,7 @@ import android.os.Bundle;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class ErrorHelperActivity extends AppCompatActivity { public class ErrorHelperActivity extends AppCompatActivity {

View file

@ -21,7 +21,7 @@ import android.widget.RadioButton;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import info.nightscout.utils.NSUpload; import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;

View file

@ -80,13 +80,13 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
@ -115,7 +115,7 @@ import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.DefaultValueHelper; import info.nightscout.utils.DefaultValueHelper;
import info.nightscout.utils.FabricPrivacy; 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.OKDialog;
import info.nightscout.utils.Profiler; import info.nightscout.utils.Profiler;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -126,7 +126,7 @@ import info.nightscout.utils.ToastUtils;
import static info.nightscout.utils.DateUtil.now; import static info.nightscout.utils.DateUtil.now;
public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener { public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private static Logger log = LoggerFactory.getLogger(Constants.OVERVIEW); private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
TextView timeView; TextView timeView;
TextView bgView; TextView bgView;
@ -826,7 +826,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> { builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
synchronized (builder) { synchronized (builder) {
if (accepted) { if (accepted) {
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
log.debug("guarding: already accepted"); log.debug("guarding: already accepted");
return; return;
} }
@ -1032,7 +1032,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
public void updateGUI(final String from) { public void updateGUI(final String from) {
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
log.debug("updateGUI entered from: " + from); log.debug("updateGUI entered from: " + from);
final Date updateGUIStart = new Date(); final Date updateGUIStart = new Date();
@ -1428,7 +1428,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final long now = System.currentTimeMillis(); final long now = System.currentTimeMillis();
// ------------------ 1st graph // ------------------ 1st graph
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
Profiler.log(log, from + " - 1st graph - START", updateGUIStart); Profiler.log(log, from + " - 1st graph - START", updateGUIStart);
final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin()); final GraphData graphData = new GraphData(bgGraph, IobCobCalculatorPlugin.getPlugin());
@ -1461,7 +1461,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
graphData.addNowLine(now); graphData.addNowLine(now);
// ------------------ 2nd graph // ------------------ 2nd graph
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
Profiler.log(log, from + " - 2nd graph - START", updateGUIStart); Profiler.log(log, from + " - 2nd graph - START", updateGUIStart);
final GraphData secondGraphData = new GraphData(iobGraph, IobCobCalculatorPlugin.getPlugin()); final GraphData secondGraphData = new GraphData(iobGraph, IobCobCalculatorPlugin.getPlugin());
@ -1516,13 +1516,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// finally enforce drawing of graphs // finally enforce drawing of graphs
graphData.performUpdate(); graphData.performUpdate();
secondGraphData.performUpdate(); secondGraphData.performUpdate();
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
Profiler.log(log, from + " - onDataChanged", updateGUIStart); Profiler.log(log, from + " - onDataChanged", updateGUIStart);
}); });
} }
}).start(); }).start();
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
Profiler.log(log, from, updateGUIStart); Profiler.log(log, from, updateGUIStart);
} }

View file

@ -7,7 +7,6 @@ import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
@ -16,6 +15,7 @@ import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore; import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore;
@ -25,7 +25,7 @@ import info.nightscout.utils.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class OverviewPlugin extends PluginBase { public class OverviewPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(Constants.OVERVIEW); private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
private static OverviewPlugin overviewPlugin = new OverviewPlugin(); private static OverviewPlugin overviewPlugin = new OverviewPlugin();

View file

@ -18,7 +18,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
@ -28,6 +27,7 @@ import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.BasalData; import info.nightscout.androidaps.plugins.IobCobCalculator.BasalData;
@ -51,7 +51,7 @@ import info.nightscout.utils.Round;
*/ */
public class GraphData { public class GraphData {
private static Logger log = LoggerFactory.getLogger(Constants.OVERVIEW); private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
private GraphView graph; private GraphView graph;
public double maxY = Double.MIN_VALUE; public double maxY = Double.MIN_VALUE;
@ -75,7 +75,7 @@ public class GraphData {
List<DataPointWithLabelInterface> bgListArray = new ArrayList<>(); List<DataPointWithLabelInterface> bgListArray = new ArrayList<>();
if (bgReadingsArray == null || bgReadingsArray.size() == 0) { if (bgReadingsArray == null || bgReadingsArray.size() == 0) {
if (Config.logOverview) if (L.isEnabled(L.OVERVIEW))
log.debug("No BG data."); log.debug("No BG data.");
return; return;
} }

View file

@ -15,10 +15,9 @@ import org.slf4j.LoggerFactory;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm; import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
@ -26,7 +25,7 @@ import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<NotificationRecyclerViewAdapter.NotificationsViewHolder> { public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<NotificationRecyclerViewAdapter.NotificationsViewHolder> {
private static Logger log = LoggerFactory.getLogger(Constants.NOTIFICATION); private static Logger log = LoggerFactory.getLogger(L.NOTIFICATION);
private List<Notification> notificationsList; private List<Notification> notificationsList;
@ -98,12 +97,12 @@ public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<Notifi
BroadcastAckAlarm.handleClearAlarm(notification.nsAlarm, MainApp.instance().getApplicationContext(), 60 * 60 * 1000L); BroadcastAckAlarm.handleClearAlarm(notification.nsAlarm, MainApp.instance().getApplicationContext(), 60 * 60 * 1000L);
} }
// Adding current time to snooze if we got staleData // Adding current time to snooze if we got staleData
if (Config.logNotification) if (L.isEnabled(L.NOTIFICATION))
log.debug("Notification text is: " + notification.text); log.debug("Notification text is: " + notification.text);
if (notification.text.equals(MainApp.gs(R.string.nsalarm_staledata))) { if (notification.text.equals(MainApp.gs(R.string.nsalarm_staledata))) {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore; NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L; long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L;
if (Config.logNotification) if (L.isEnabled(L.NOTIFICATION))
log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis()); log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis());
nstore.snoozeTo(System.currentTimeMillis() + (SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L)); nstore.snoozeTo(System.currentTimeMillis() + (SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L));
} }

View file

@ -22,10 +22,10 @@ import java.util.Comparator;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.AlarmSoundService; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.services.AlarmSoundService;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
@ -36,7 +36,7 @@ public class NotificationStore {
private static final String CHANNEL_ID = "AndroidAPS-Overview"; private static final String CHANNEL_ID = "AndroidAPS-Overview";
private static Logger log = LoggerFactory.getLogger(Constants.NOTIFICATION); private static Logger log = LoggerFactory.getLogger(L.NOTIFICATION);
public List<Notification> store = new ArrayList<>(); public List<Notification> store = new ArrayList<>();
private boolean usesChannels; private boolean usesChannels;
@ -52,7 +52,7 @@ public class NotificationStore {
} }
public synchronized boolean add(Notification n) { public synchronized boolean add(Notification n) {
if (Config.logNotification) if (L.isEnabled(L.NOTIFICATION))
log.debug("Notification received: " + n.text); log.debug("Notification received: " + n.text);
for (Notification storeNotification : store) { for (Notification storeNotification : store) {
if (storeNotification.id == n.id) { if (storeNotification.id == n.id) {
@ -108,7 +108,7 @@ public class NotificationStore {
} }
public void snoozeTo(long timeToSnooze) { public void snoozeTo(long timeToSnooze) {
if (Config.logNotification) if (L.isEnabled(L.NOTIFICATION))
log.debug("Snoozing alarm until: " + timeToSnooze); log.debug("Snoozing alarm until: " + timeToSnooze);
SP.putLong("snoozedTo", timeToSnooze); SP.putLong("snoozedTo", timeToSnooze);
} }
@ -118,7 +118,7 @@ public class NotificationStore {
Notification notification = new Notification(Notification.NSALARM, MainApp.gs(R.string.nsalarm_staledata), Notification.URGENT); Notification notification = new Notification(Notification.NSALARM, MainApp.gs(R.string.nsalarm_staledata), Notification.URGENT);
SP.putLong("snoozedTo", System.currentTimeMillis()); SP.putLong("snoozedTo", System.currentTimeMillis());
add(notification); add(notification);
if (Config.logNotification) if (L.isEnabled(L.NOTIFICATION))
log.debug("Snoozed to current time and added back notification!"); log.debug("Snoozed to current time and added back notification!");
} }
} }

View file

@ -25,20 +25,18 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.interfaces.PumpDescription; 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.CareportalFragment;
import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NumberPicker; import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
import info.nightscout.utils.TimeListEdit; import info.nightscout.utils.TimeListEdit;
public class LocalProfileFragment extends SubscriberFragment { public class LocalProfileFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(LocalProfileFragment.class);
NumberPicker diaView; NumberPicker diaView;
RadioButton mgdlView; RadioButton mgdlView;
RadioButton mmolView; RadioButton mmolView;
@ -81,80 +79,72 @@ public class LocalProfileFragment extends SubscriberFragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { 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); invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile);
diaView = (NumberPicker) layout.findViewById(R.id.localprofile_dia);
diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch); if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) {
mgdlView = (RadioButton) layout.findViewById(R.id.localprofile_mgdl); layout.findViewById(R.id.localprofile_basal).setVisibility(View.GONE);
mmolView = (RadioButton) layout.findViewById(R.id.localprofile_mmol); }
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); 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); 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); 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); 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); updateGUI();
resetButton = (Button) layout.findViewById(R.id.localprofile_reset); });
saveButton = (Button) layout.findViewById(R.id.localprofile_save);
saveButton.setOnClickListener(view -> {
invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile); if (!LocalProfilePlugin.getPlugin().isValidEditState()) {
return; //Should not happen as saveButton should not be visible if not valid
if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) {
layout.findViewById(R.id.localprofile_basal).setVisibility(View.GONE);
} }
LocalProfilePlugin.getPlugin().storeSettings();
updateGUI();
});
mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); return layout;
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;
} }
public void doEdit() { public void doEdit() {
@ -203,7 +193,7 @@ public class LocalProfileFragment extends SubscriberFragment {
} }
//Show reset button iff data was edited //Show reset button iff data was edited
if(isEdited) { if (isEdited) {
resetButton.setVisibility(View.VISIBLE); resetButton.setVisibility(View.VISIBLE);
} else { } else {
resetButton.setVisibility(View.GONE); resetButton.setVisibility(View.GONE);

View file

@ -8,7 +8,6 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -26,7 +26,7 @@ import info.nightscout.utils.SP;
*/ */
public class LocalProfilePlugin extends PluginBase implements ProfileInterface { public class LocalProfilePlugin extends PluginBase implements ProfileInterface {
public static final String LOCAL_PROFILE = "LocalProfile"; 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; private static LocalProfilePlugin localProfilePlugin;
@ -81,13 +81,13 @@ public class LocalProfilePlugin extends PluginBase implements ProfileInterface {
createAndStoreConvertedProfile(); createAndStoreConvertedProfile();
edited = false; edited = false;
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Storing settings: " + getRawProfile().getData().toString()); log.debug("Storing settings: " + getRawProfile().getData().toString());
MainApp.bus().post(new EventProfileStoreChanged()); MainApp.bus().post(new EventProfileStoreChanged());
} }
public synchronized void loadSettings() { public synchronized void loadSettings() {
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Loading stored settings"); log.debug("Loading stored settings");
mgdl = SP.getBoolean(LOCAL_PROFILE + "mgdl", false); mgdl = SP.getBoolean(LOCAL_PROFILE + "mgdl", false);

View file

@ -27,7 +27,6 @@ import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI; import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph; import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.OKDialog; import info.nightscout.utils.OKDialog;
import static butterknife.OnItemSelected.Callback.NOTHING_SELECTED; import static butterknife.OnItemSelected.Callback.NOTHING_SELECTED;
@ -62,24 +61,22 @@ public class NSProfileFragment extends SubscriberFragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { 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); unbinder = ButterKnife.bind(this, view);
updateGUI(); updateGUI();
return view; return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
}
return null;
} }
@Subscribe @Subscribe
public void onStatusEvent(final EventNSProfileUpdateGUI ev) { public void onStatusEvent(final EventNSProfileUpdateGUI ev) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(() -> { synchronized (NSProfileFragment.this) { updateGUI(); } }); activity.runOnUiThread(() -> {
synchronized (NSProfileFragment.this) {
updateGUI();
}
});
} }
@Override @Override

View file

@ -13,7 +13,8 @@ import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.data.ProfileStore;
import info.nightscout.androidaps.events.EventProfileStoreChanged; import info.nightscout.androidaps.events.EventProfileStoreChanged;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -27,7 +28,7 @@ import info.nightscout.utils.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class NSProfilePlugin extends PluginBase implements ProfileInterface { 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; private static NSProfilePlugin nsProfilePlugin;
@ -77,7 +78,7 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface {
MainApp.bus().post(new EventProfileStoreChanged()); MainApp.bus().post(new EventProfileStoreChanged());
MainApp.bus().post(new EventNSProfileUpdateGUI()); MainApp.bus().post(new EventNSProfileUpdateGUI());
} }
if (Config.logIncommingData) if (L.isEnabled(L.PROFILE))
log.debug("Received profileStore: " + activeProfile + " " + profile); log.debug("Received profileStore: " + activeProfile + " " + profile);
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -86,31 +87,29 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface {
private void storeNSProfile() { private void storeNSProfile() {
SP.putString("profile", profile.getData().toString()); SP.putString("profile", profile.getData().toString());
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Storing profile"); log.debug("Storing profile");
} }
private void loadNSProfile() { private void loadNSProfile() {
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Loading stored profile"); log.debug("Loading stored profile");
String profileString = SP.getString("profile", null); String profileString = SP.getString("profile", null);
if (profileString != null) { if (profileString != null) {
if (Config.logPrefsChange) { if (L.isEnabled(L.PROFILE))
log.debug("Loaded profile: " + profileString); log.debug("Loaded profile: " + profileString);
try { try {
profile = new ProfileStore(new JSONObject(profileString)); profile = new ProfileStore(new JSONObject(profileString));
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
profile = null; profile = null;
}
} }
} else { } else {
if (Config.logPrefsChange) { if (L.isEnabled(L.PROFILE))
log.debug("Stored profile not found"); log.debug("Stored profile not found");
// force restart of nsclient to fetch profile // force restart of nsclient to fetch profile
Intent restartNSClient = new Intent(Intents.ACTION_RESTART); Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient); MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
}
} }
} }

View file

@ -26,12 +26,9 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
public class SimpleProfileFragment extends SubscriberFragment { public class SimpleProfileFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(SimpleProfileFragment.class);
EditText diaView; EditText diaView;
RadioButton mgdlView; RadioButton mgdlView;
RadioButton mmolView; RadioButton mmolView;
@ -46,92 +43,86 @@ public class SimpleProfileFragment extends SubscriberFragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
try { View layout = inflater.inflate(R.layout.simpleprofile_fragment, container, false);
View layout = inflater.inflate(R.layout.simpleprofile_fragment, container, false); diaView = (EditText) layout.findViewById(R.id.simpleprofile_dia);
diaView = (EditText) layout.findViewById(R.id.simpleprofile_dia); mgdlView = (RadioButton) layout.findViewById(R.id.simpleprofile_mgdl);
mgdlView = (RadioButton) layout.findViewById(R.id.simpleprofile_mgdl); mmolView = (RadioButton) layout.findViewById(R.id.simpleprofile_mmol);
mmolView = (RadioButton) layout.findViewById(R.id.simpleprofile_mmol); icView = (EditText) layout.findViewById(R.id.simpleprofile_ic);
icView = (EditText) layout.findViewById(R.id.simpleprofile_ic); isfView = (EditText) layout.findViewById(R.id.simpleprofile_isf);
isfView = (EditText) layout.findViewById(R.id.simpleprofile_isf); basalView = (EditText) layout.findViewById(R.id.simpleprofile_basalrate);
basalView = (EditText) layout.findViewById(R.id.simpleprofile_basalrate); targetlowView = (EditText) layout.findViewById(R.id.simpleprofile_targetlow);
targetlowView = (EditText) layout.findViewById(R.id.simpleprofile_targetlow); targethighView = (EditText) layout.findViewById(R.id.simpleprofile_targethigh);
targethighView = (EditText) layout.findViewById(R.id.simpleprofile_targethigh); profileswitchButton = (Button) layout.findViewById(R.id.simpleprofile_profileswitch);
profileswitchButton = (Button) layout.findViewById(R.id.simpleprofile_profileswitch); invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile);
invalidProfile = (TextView) layout.findViewById(R.id.invalidprofile);
if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) { if (!ConfigBuilderPlugin.getActivePump().getPumpDescription().isTempBasalCapable) {
layout.findViewById(R.id.simpleprofile_basalrate).setVisibility(View.GONE); layout.findViewById(R.id.simpleprofile_basalrate).setVisibility(View.GONE);
layout.findViewById(R.id.simpleprofile_basalrate_label).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);
} }
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 @Subscribe

View file

@ -9,7 +9,6 @@ import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class SimpleProfilePlugin extends PluginBase implements ProfileInterface { 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; private static SimpleProfilePlugin simpleProfilePlugin;
@ -58,7 +58,7 @@ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface
} }
public void storeSettings() { public void storeSettings() {
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Storing settings"); log.debug("Storing settings");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext());
SharedPreferences.Editor editor = settings.edit(); SharedPreferences.Editor editor = settings.edit();
@ -73,13 +73,13 @@ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface
editor.apply(); editor.apply();
createConvertedProfile(); createConvertedProfile();
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Storing settings: " + getRawProfile().getData().toString()); log.debug("Storing settings: " + getRawProfile().getData().toString());
MainApp.bus().post(new EventProfileStoreChanged()); MainApp.bus().post(new EventProfileStoreChanged());
} }
private void loadSettings() { private void loadSettings() {
if (Config.logPrefsChange) if (L.isEnabled(L.PROFILE))
log.debug("Loading stored settings"); log.debug("Loading stored settings");
mgdl = SP.getBoolean("SimpleProfile" + "mgdl", true); mgdl = SP.getBoolean("SimpleProfile" + "mgdl", true);

View file

@ -31,8 +31,6 @@ import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TemporaryBasal; 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.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
@ -42,6 +40,8 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
@ -60,6 +60,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.PumpHistory;
import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.PumpHistoryRequest; import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.PumpHistoryRequest;
import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.Tdd; 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.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
@ -69,7 +70,7 @@ import info.nightscout.utils.SP;
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class ComboPlugin extends PluginBase implements PumpInterface, ConstraintsInterface { 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_TBRS_SET = "combo_tbrs_set";
static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered"; static final String COMBO_BOLUSES_DELIVERED = "combo_boluses_delivered";
@ -198,7 +199,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
@Override @Override
public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) {
boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);
if (allowHardwarePump || context == null){ if (allowHardwarePump || context == null) {
pluginSwitcher.invoke(); pluginSwitcher.invoke();
} else { } else {
AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog.Builder builder = new AlertDialog.Builder(context);
@ -207,13 +208,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
pluginSwitcher.invoke(); pluginSwitcher.invoke();
SP.putBoolean("allow_hardware_pump", true); 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() { .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
pluginSwitcher.cancel(); 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(); builder.create().show();
@ -260,7 +263,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
@Override @Override
public void disconnect(String reason) { 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(); ruffyScripter.disconnect();
} }
@ -359,7 +363,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
*/ */
@Override @Override
public synchronized void getPumpStatus() { public synchronized void getPumpStatus() {
log.debug("getPumpStatus called"); if (L.isEnabled(L.PUMP))
log.debug("getPumpStatus called");
if (!pump.initialized) { if (!pump.initialized) {
initializePump(); initializePump();
} else { } else {
@ -371,10 +376,12 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
private synchronized void initializePump() { private synchronized void initializePump() {
long maxWait = System.currentTimeMillis() + 15 * 1000; long maxWait = System.currentTimeMillis() + 15 * 1000;
while (!ruffyScripter.isPumpAvailable()) { 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); SystemClock.sleep(100);
if (System.currentTimeMillis() > maxWait) { if (System.currentTimeMillis() > maxWait) {
log.debug("ruffy service unavailable, wtf"); if (L.isEnabled(L.PUMP))
log.debug("ruffy service unavailable, wtf");
return; return;
} }
} }
@ -393,7 +400,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// note that since the history is checked upon every connect, the above already updated // note that since the history is checked upon every connect, the above already updated
// the DB with any changed history records // the DB with any changed history records
if (pumpHistoryChanged) { 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; pumpHistoryChanged = false;
} }
@ -542,7 +550,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// within the last 1-2 minutes // within the last 1-2 minutes
if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01 if (Math.abs(previousBolus.amount - detailedBolusInfo.insulin) < 0.01
&& previousBolus.timestamp + 60 * 1000 > System.currentTimeMillis()) { && 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) return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.gs(R.string.bolus_frequency_exceeded)); .comment(MainApp.gs(R.string.bolus_frequency_exceeded));
} }
@ -562,7 +571,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
return new PumpEnactResult().success(false).enacted(false) return new PumpEnactResult().success(false).enacted(false)
.comment(MainApp.gs(R.string.combo_error_no_connection_no_bolus_delivered)); .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); SystemClock.sleep(2000);
timeCheckResult = runCommand(null, 0, ruffyScripter::readPumpState); timeCheckResult = runCommand(null, 0, ruffyScripter::readPumpState);
waitLoops++; waitLoops++;
@ -573,7 +583,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) .putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("waitTimeSecs", String.valueOf(waitDuration))); .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) { if (cancelBolus) {
@ -735,11 +746,13 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
*/ */
@Override @Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean force) { 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 unroundedPercentage = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10); int roundedPercentage = (int) (Math.round(absoluteRate / getBaseBasalRate() * 10) * 10);
if (unroundedPercentage != roundedPercentage) { 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); return setTempBasalPercent(roundedPercentage, durationInMinutes);
@ -757,7 +770,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
} }
private PumpEnactResult setTempBasalPercent(Integer percent, final Integer durationInMinutes) { 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) { if (pumpHistoryChanged && percent > 110) {
return new PumpEnactResult().success(false).enacted(false) return new PumpEnactResult().success(false).enacted(false)
@ -767,13 +781,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
int adjustedPercent = percent; int adjustedPercent = percent;
if (adjustedPercent > pumpDescription.maxTempPercent) { 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; adjustedPercent = pumpDescription.maxTempPercent;
} }
if (adjustedPercent % 10 != 0) { if (adjustedPercent % 10 != 0) {
Long rounded = Math.round(adjustedPercent / 10d) * 10; 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(); adjustedPercent = rounded.intValue();
} }
@ -822,7 +838,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
*/ */
@Override @Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) { 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()); final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
if (enforceNew) { if (enforceNew) {
CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState); CommandResult stateResult = runCommand(MainApp.gs(R.string.combo_pump_action_refreshing), 2, ruffyScripter::readPumpState);
@ -832,7 +849,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (!stateResult.state.tbrActive) { if (!stateResult.state.tbrActive) {
return new PumpEnactResult().success(true).enacted(false); 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); CommandResult cancelResult = runCommand(MainApp.gs(R.string.combo_pump_action_cancelling_tbr), 2, ruffyScripter::cancelTbr);
if (!cancelResult.success) { if (!cancelResult.success) {
return new PumpEnactResult().success(false).enacted(false); return new PumpEnactResult().success(false).enacted(false);
@ -853,7 +871,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// Let fake neutral temp keep run (see below) // Let fake neutral temp keep run (see below)
// Note that since this runs on the queue a connection is opened regardless, but this // 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). // 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) return new PumpEnactResult().success(true).enacted(true)
.comment("cancelTempBasal skipping changing tbr since it already is at " .comment("cancelTempBasal skipping changing tbr since it already is at "
+ activeTemp.percentRate + "% and running for another " + activeTemp.percentRate + "% and running for another "
@ -862,7 +881,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 // 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%. // on whether the TBR we're cancelling is above or below 100%.
final int percentage = (activeTemp.percentRate > 100) ? 110 : 90; 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); return setTempBasalPercent(percentage, 15);
} }
} }
@ -901,7 +921,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (!commandResult.success && retries > 0) { if (!commandResult.success && retries > 0) {
for (int retryAttempts = 1; !commandResult.success && retryAttempts <= retries; retryAttempts++) { 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(); commandResult = commandExecution.execute();
} }
} }
@ -982,7 +1003,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
if (aapsTbr == null || aapsTbr.percentRate != 0) { 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() TemporaryBasal newTempBasal = new TemporaryBasal()
.date(now) .date(now)
.percent(0) .percent(0)
@ -1042,11 +1064,13 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (state.pumpTime == 0) { if (state.pumpTime == 0) {
// time couldn't be read (e.g. a warning is displayed on the menu , hiding the time field) // 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) { } 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); 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)); MainApp.bus().post(new EventNewNotification(notification));
} else if (Math.abs(state.pumpTime - System.currentTimeMillis()) >= 3 * 60 * 1000) { } 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); 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)); MainApp.bus().post(new EventNewNotification(notification));
} }
@ -1108,7 +1132,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now); TemporaryBasal aapsTbr = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
if (aapsTbr == null && state.tbrActive && state.tbrRemainingDuration > 2) { 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") FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboTbrMismatch")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) .putCustomAttribute("version", BuildConfig.VERSION)
@ -1120,7 +1145,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
.source(Source.USER); .source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(newTempBasal);
} else if (aapsTbr != null && aapsTbr.getPlannedRemainingMinutes() > 2 && !state.tbrActive) { } 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") FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboTbrMismatch")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) .putCustomAttribute("version", BuildConfig.VERSION)
@ -1133,7 +1159,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
} else if (aapsTbr != null && state.tbrActive } else if (aapsTbr != null && state.tbrActive
&& (aapsTbr.percentRate != state.tbrPercent || && (aapsTbr.percentRate != state.tbrPercent ||
Math.abs(aapsTbr.getPlannedRemainingMinutes() - state.tbrRemainingDuration) > 2)) { 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") FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboTbrMismatch")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) .putCustomAttribute("version", BuildConfig.VERSION)
@ -1218,7 +1245,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// no history, nothing to check or complain about // no history, nothing to check or complain about
if (quickInfoResult.history == null || quickInfoResult.history.bolusHistory.isEmpty()) { 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; pumpHistoryChanged = false;
return null; return null;
} }
@ -1227,13 +1255,15 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
List<Bolus> initialPumpBolusHistory = quickInfoResult.history.bolusHistory; List<Bolus> initialPumpBolusHistory = quickInfoResult.history.bolusHistory;
if (recentBoluses.size() == 1 && initialPumpBolusHistory.size() >= 1 if (recentBoluses.size() == 1 && initialPumpBolusHistory.size() >= 1
&& recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))) { && 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; pumpHistoryChanged = false;
return null; return null;
} else if (recentBoluses.size() == 2 && initialPumpBolusHistory.size() >= 2 } else if (recentBoluses.size() == 2 && initialPumpBolusHistory.size() >= 2
&& recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0)) && recentBoluses.get(0).equals(quickInfoResult.history.bolusHistory.get(0))
&& recentBoluses.get(1).equals(quickInfoResult.history.bolusHistory.get(1))) { && 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; pumpHistoryChanged = false;
return null; return null;
} }
@ -1253,7 +1283,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// for. // for.
HashSet<Bolus> bolusSet = new HashSet<>(historyResult.history.bolusHistory); HashSet<Bolus> bolusSet = new HashSet<>(historyResult.history.bolusHistory);
if (bolusSet.size() != historyResult.history.bolusHistory.size()) { 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") FabricPrivacy.getInstance().logCustom(new CustomEvent("ComboBolusToDbError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION) .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION) .putCustomAttribute("version", BuildConfig.VERSION)
@ -1266,7 +1297,8 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history); pumpHistoryChanged = updateDbFromPumpHistory(historyResult.history);
if (pumpHistoryChanged) { if (pumpHistoryChanged) {
log.debug("Setting 'pumpHistoryChanged' true"); if (L.isEnabled(L.PUMP))
log.debug("Setting 'pumpHistoryChanged' true");
} }
List<Bolus> updatedPumpBolusHistory = historyResult.history.bolusHistory; List<Bolus> updatedPumpBolusHistory = historyResult.history.bolusHistory;

View file

@ -5,11 +5,11 @@ import android.support.annotation.Nullable;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; 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.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; 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.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification; 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 { public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface {
protected Logger log; protected Logger log = LoggerFactory.getLogger(L.PUMP);
protected AbstractDanaRExecutionService sExecutionService; protected AbstractDanaRExecutionService sExecutionService;
@ -133,7 +134,8 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement); Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement);
if (profileValue == null) return true; if (profileValue == null) return true;
if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { 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; return false;
} }
} }
@ -183,7 +185,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
result.isPercent = true; result.isPercent = true;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalPercent: Correct value already set"); log.debug("setTempBasalPercent: Correct value already set");
return result; return result;
} }
@ -197,7 +199,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
result.isPercent = true; result.isPercent = true;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalPercent: OK"); log.debug("setTempBasalPercent: OK");
return result; return result;
} }
@ -225,7 +227,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
result.absolute = pump.extendedBolusAbsoluteRate; result.absolute = pump.extendedBolusAbsoluteRate;
result.isPercent = false; result.isPercent = false;
result.isTempCancel = 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); log.debug("setExtendedBolus: Correct extended bolus already set. Current: " + pump.extendedBolusAmount + " Asked: " + insulin);
return result; return result;
} }
@ -240,7 +242,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
if (!SP.getBoolean("danar_useextended", false)) if (!SP.getBoolean("danar_useextended", false))
result.bolusDelivered = pump.extendedBolusAmount; result.bolusDelivered = pump.extendedBolusAmount;
result.isPercent = false; result.isPercent = false;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setExtendedBolus: OK"); log.debug("setExtendedBolus: OK");
return result; return result;
} }
@ -263,7 +265,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
if (!pump.isExtendedInProgress) { if (!pump.isExtendedInProgress) {
result.success = true; result.success = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("cancelExtendedBolus: OK"); log.debug("cancelExtendedBolus: OK");
return result; return result;
} else { } else {

View file

@ -25,12 +25,13 @@ import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; 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.ExtendedBolus;
import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.Dialogs.ProfileViewDialog; 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.androidaps.queue.events.EventQueueChanged;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SetWarnColor; import info.nightscout.utils.SetWarnColor;
public class DanaRFragment extends SubscriberFragment { 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 Handler loopHandler = new Handler();
private Runnable refreshLoop = new Runnable() { private Runnable refreshLoop = new Runnable() {
@ -113,18 +113,12 @@ public class DanaRFragment extends SubscriberFragment {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
try { View view = inflater.inflate(R.layout.danar_fragment, container, false);
View view = inflater.inflate(R.layout.danar_fragment, container, false); unbinder = ButterKnife.bind(this, view);
unbinder = ButterKnife.bind(this, view);
pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder)); pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder));
return view; return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
}
return null;
} }
@OnClick(R.id.danar_history) @OnClick(R.id.danar_history)
@ -145,11 +139,14 @@ public class DanaRFragment extends SubscriberFragment {
} }
@OnClick(R.id.danar_user_options) @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) @OnClick(R.id.danar_btconnection)
void onBtConnectionClick() { void onBtConnectionClick() {
log.debug("Clicked connect to pump"); if (L.isEnabled(L.PUMP))
log.debug("Clicked connect to pump");
DanaRPump.getInstance().lastConnection = 0; DanaRPump.getInstance().lastConnection = 0;
ConfigBuilderPlugin.getCommandQueue().readStatus("Clicked connect to pump", null); ConfigBuilderPlugin.getCommandQueue().readStatus("Clicked connect to pump", null);
} }
@ -162,10 +159,11 @@ public class DanaRFragment extends SubscriberFragment {
activity.runOnUiThread( activity.runOnUiThread(
new Runnable() { new Runnable() {
@Override @Override
public void run() { public void run() {
synchronized(DanaRFragment.this){ synchronized (DanaRFragment.this) {
if(btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null ) return; if (btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null)
return;
if (c.sStatus == EventPumpStatusChanged.CONNECTING) if (c.sStatus == EventPumpStatusChanged.CONNECTING)
btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"); btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s");
@ -216,7 +214,7 @@ public class DanaRFragment extends SubscriberFragment {
@SuppressLint("SetTextI18n") @SuppressLint("SetTextI18n")
@Override @Override
public void run() { public void run() {
synchronized(DanaRFragment.this) { synchronized (DanaRFragment.this) {
if (!isBound()) return; if (!isBound()) return;
DanaRPump pump = DanaRPump.getInstance(); DanaRPump pump = DanaRPump.getInstance();

View file

@ -11,9 +11,6 @@ import android.support.v7.app.AlertDialog;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo; 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.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStartWithSpeed;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
@ -49,7 +47,6 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
public DanaRPlugin() { public DanaRPlugin() {
super(); super();
log = LoggerFactory.getLogger(DanaRPlugin.class);
useExtendedBoluses = SP.getBoolean("danar_useextended", false); useExtendedBoluses = SP.getBoolean("danar_useextended", false);
pumpDescription.isBolusCapable = true; pumpDescription.isBolusCapable = true;
@ -85,7 +82,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
@Override @Override
public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) { public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) {
boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false); boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);
if (allowHardwarePump || context == null){ if (allowHardwarePump || context == null) {
pluginSwitcher.invoke(); pluginSwitcher.invoke();
} else { } else {
AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog.Builder builder = new AlertDialog.Builder(context);
@ -94,13 +91,15 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
pluginSwitcher.invoke(); pluginSwitcher.invoke();
SP.putBoolean("allow_hardware_pump", true); 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() { .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
pluginSwitcher.cancel(); 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(); builder.create().show();
@ -127,12 +126,14 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
private ServiceConnection mConnection = new ServiceConnection() { private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
log.debug("Service is disconnected"); if (L.isEnabled(L.PUMP))
log.debug("Service is disconnected");
sExecutionService = null; sExecutionService = null;
} }
public void onServiceConnected(ComponentName name, IBinder service) { 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; DanaRExecutionService.LocalBinder mLocalBinder = (DanaRExecutionService.LocalBinder) service;
sExecutionService = mLocalBinder.getServiceInstance(); 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); result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStartWithSpeed.errorCode);
else else
result.comment = MainApp.gs(R.string.virtualpump_resultok); 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); log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.insulin = t.insulin; detailedBolusInfo.insulin = t.insulin;
detailedBolusInfo.date = System.currentTimeMillis(); detailedBolusInfo.date = System.currentTimeMillis();
@ -237,13 +238,13 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
if (doTempOff) { if (doTempOff) {
// If extended in progress // If extended in progress
if (activeExtended != null && useExtendedBoluses) { if (activeExtended != null && useExtendedBoluses) {
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Stopping extended bolus (doTempOff)"); log.debug("setTempBasalAbsolute: Stopping extended bolus (doTempOff)");
return cancelExtendedBolus(); return cancelExtendedBolus();
} }
// If temp in progress // If temp in progress
if (activeTemp != null) { if (activeTemp != null) {
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)"); log.debug("setTempBasalAbsolute: Stopping temp basal (doTempOff)");
return cancelRealTempBasal(); return cancelRealTempBasal();
} }
@ -252,7 +253,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
result.percent = 100; result.percent = 100;
result.isPercent = true; result.isPercent = true;
result.isTempCancel = true; result.isTempCancel = true;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: doTempOff OK"); log.debug("setTempBasalAbsolute: doTempOff OK");
return result; return result;
} }
@ -264,12 +265,12 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
if (percentRate > getPumpDescription().maxTempPercent) { if (percentRate > getPumpDescription().maxTempPercent) {
percentRate = getPumpDescription().maxTempPercent; percentRate = getPumpDescription().maxTempPercent;
} }
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Calculated percent rate: " + percentRate); log.debug("setTempBasalAbsolute: Calculated percent rate: " + percentRate);
// If extended in progress // If extended in progress
if (activeExtended != null && useExtendedBoluses) { if (activeExtended != null && useExtendedBoluses) {
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)"); log.debug("setTempBasalAbsolute: Stopping extended bolus (doLowTemp || doHighTemp)");
result = cancelExtendedBolus(); result = cancelExtendedBolus();
if (!result.success) { if (!result.success) {
@ -280,7 +281,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
// Check if some temp is already in progress // Check if some temp is already in progress
if (activeTemp != null) { if (activeTemp != null) {
// Correct basal already set ? // Correct basal already set ?
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: currently running: " + activeTemp.toString()); log.debug("setTempBasalAbsolute: currently running: " + activeTemp.toString());
if (activeTemp.percentRate == percentRate) { if (activeTemp.percentRate == percentRate) {
if (enforceNew) { if (enforceNew) {
@ -292,21 +293,21 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
result.duration = activeTemp.getPlannedRemainingMinutes(); result.duration = activeTemp.getPlannedRemainingMinutes();
result.isPercent = true; result.isPercent = true;
result.isTempCancel = false; result.isTempCancel = false;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); log.debug("setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)");
return result; return result;
} }
} }
} }
// Convert duration from minutes to hours // 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)"); log.debug("setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)");
return setTempBasalPercent(percentRate, durationInMinutes, profile, false); return setTempBasalPercent(percentRate, durationInMinutes, profile, false);
} }
if (doExtendedTemp) { if (doExtendedTemp) {
// Check if some temp is already in progress // Check if some temp is already in progress
if (activeTemp != null) { if (activeTemp != null) {
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Stopping temp basal (doExtendedTemp)"); log.debug("setTempBasalAbsolute: Stopping temp basal (doExtendedTemp)");
result = cancelRealTempBasal(); result = cancelRealTempBasal();
// Check for proper result // Check for proper result
@ -325,7 +326,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours extendedRateToSet = Round.roundTo(extendedRateToSet, pumpDescription.extendedBolusStep * 2); // *2 because of halfhours
// What is current rate of extended bolusing in u/h? // 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: 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"); log.debug("setTempBasalAbsolute: Rate to set: " + extendedRateToSet + "U/h");
} }
@ -339,21 +340,21 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
result.duration = pump.extendedBolusRemainingMinutes; result.duration = pump.extendedBolusRemainingMinutes;
result.isPercent = false; result.isPercent = false;
result.isTempCancel = false; result.isTempCancel = false;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Correct extended already set"); log.debug("setTempBasalAbsolute: Correct extended already set");
return result; return result;
} }
// Now set new extended, no need to to stop previous (if running) because it's replaced // Now set new extended, no need to to stop previous (if running) because it's replaced
Double extendedAmount = extendedRateToSet / 2 * durationInHalfHours; Double extendedAmount = extendedRateToSet / 2 * durationInHalfHours;
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Setting extended: " + extendedAmount + "U halfhours: " + durationInHalfHours); log.debug("setTempBasalAbsolute: Setting extended: " + extendedAmount + "U halfhours: " + durationInHalfHours);
result = setExtendedBolus(extendedAmount, durationInMinutes); result = setExtendedBolus(extendedAmount, durationInMinutes);
if (!result.success) { if (!result.success) {
log.error("setTempBasalAbsolute: Failed to set extended bolus"); log.error("setTempBasalAbsolute: Failed to set extended bolus");
return result; return result;
} }
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("setTempBasalAbsolute: Extended bolus set ok"); log.debug("setTempBasalAbsolute: Extended bolus set ok");
result.absolute = result.absolute + getBaseBasalRate(); result.absolute = result.absolute + getBaseBasalRate();
return result; return result;
@ -392,7 +393,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
result.success = true; result.success = true;
result.isTempCancel = true; result.isTempCancel = true;
result.comment = MainApp.gs(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (L.isEnabled(L.PUMP))
log.debug("cancelRealTempBasal: OK"); log.debug("cancelRealTempBasal: OK");
return result; return result;
} else { } else {

View file

@ -9,18 +9,18 @@ import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 04.07.2016. * Created by mike on 04.07.2016.
*/ */
public class DanaRPump { public class DanaRPump {
private static Logger log = LoggerFactory.getLogger(DanaRPump.class); private Logger log = LoggerFactory.getLogger(L.PUMP);
private static DanaRPump instance = null; private static DanaRPump instance = null;
@ -236,13 +236,13 @@ public class DanaRPump {
return PROFILE_PREFIX + (activeProfile + 1); return PROFILE_PREFIX + (activeProfile + 1);
} }
public static double[] buildDanaRProfileRecord(Profile nsProfile) { public double[] buildDanaRProfileRecord(Profile nsProfile) {
double[] record = new double[24]; double[] record = new double[24];
for (Integer hour = 0; hour < 24; hour++) { for (Integer hour = 0; hour < 24; hour++) {
//Some values get truncated to the next lower one. //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) // -> 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; 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); log.debug("NS basal value for " + hour + ":00 is " + value);
record[hour] = value; record[hour] = value;
} }

View file

@ -33,8 +33,6 @@ import info.nightscout.utils.DecimalFormatter;
* Created by mike on 10.07.2016. * Created by mike on 10.07.2016.
*/ */
public class ProfileViewDialog extends DialogFragment { public class ProfileViewDialog extends DialogFragment {
private static Logger log = LoggerFactory.getLogger(ProfileViewDialog.class);
private TextView noProfile; private TextView noProfile;
private TextView units; private TextView units;
private TextView dia; private TextView dia;

View file

@ -10,7 +10,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; 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.MessageBase;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageHashTable; import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageHashTable;
import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread; import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread;
@ -20,7 +20,7 @@ import info.nightscout.utils.CRC;
* Created by mike on 17.07.2016. * Created by mike on 17.07.2016.
*/ */
public class SerialIOThread extends AbstractSerialIOThread { 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 InputStream mInputStream = null;
private OutputStream mOutputStream = null; private OutputStream mOutputStream = null;
@ -71,7 +71,7 @@ public class SerialIOThread extends AbstractSerialIOThread {
message = MessageHashTable.findMessage(command); message = MessageHashTable.findMessage(command);
} }
if (Config.logDanaMessageDetail) if (L.isEnabled(L.PUMPBTCOMM))
log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff)); log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff));
// process the message content // process the message content
@ -83,7 +83,7 @@ public class SerialIOThread extends AbstractSerialIOThread {
} }
} }
} catch (Exception e) { } 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); log.error("Thread exception: ", e);
mKeepRunning = false; mKeepRunning = false;
} }
@ -147,7 +147,7 @@ public class SerialIOThread extends AbstractSerialIOThread {
processedMessage = message; processedMessage = message;
byte[] messageBytes = message.getRawMessageBytes(); byte[] messageBytes = message.getRawMessageBytes();
if (Config.logDanaSerialEngine) if (L.isEnabled(L.PUMPBTCOMM))
log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes)); log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes));
try { try {
@ -169,7 +169,8 @@ public class SerialIOThread extends AbstractSerialIOThread {
log.warn("Reply not received " + message.getMessageName()); log.warn("Reply not received " + message.getMessageName());
if (message.getCommand() == 0xF0F1) { if (message.getCommand() == 0xF0F1) {
DanaRPump.getInstance().isNewPump = false; 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 { try {
mInputStream.close(); mInputStream.close();
} catch (Exception e) { } catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage()); if (L.isEnabled(L.PUMPBTCOMM))
log.debug(e.getMessage());
} }
try { try {
mOutputStream.close(); mOutputStream.close();
} catch (Exception e) { } catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage()); if (L.isEnabled(L.PUMPBTCOMM))
log.debug(e.getMessage());
} }
try { try {
mRfCommSocket.close(); mRfCommSocket.close();
} catch (Exception e) { } catch (Exception e) {
if (Config.logDanaSerialEngine) log.debug(e.getMessage()); if (L.isEnabled(L.PUMPBTCOMM))
log.debug(e.getMessage());
} }
try { try {
System.runFinalization(); System.runFinalization();
} catch (Exception e) { } 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);
} }
} }

Some files were not shown because too many files have changed in this diff Show more