Merge branch 'dev' into tbr_wear_accept

This commit is contained in:
Milos Kozak 2018-08-01 08:18:29 +02:00 committed by GitHub
commit 7c9b81fbbf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
376 changed files with 14973 additions and 14083 deletions

4
.gitignore vendored
View file

@ -10,4 +10,6 @@ build/
app/src/main/jniLibs
full/
debug/
release/
release/
app/com.crashlytics.settings.json
app/session_analytics.tap

View file

@ -63,7 +63,7 @@ android {
targetSdkVersion 25
multiDexEnabled true
versionCode 1500
version "2.0b-dev"
version "2.0c-dev"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild()
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

View file

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

View file

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

View file

@ -23,22 +23,4 @@ public class Config {
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean detailedLog = true;
public static final boolean logFunctionCalls = true;
public static final boolean logIncommingData = true;
public static final boolean logAPSResult = true;
public static final boolean logPumpComm = true;
public static final boolean logPrefsChange = true;
public static final boolean logConfigBuilder = true;
public static final boolean logNSUpload = true;
public static final boolean logPumpActions = true;
public static final boolean logCongigBuilderActions = true;
public static final boolean logAutosensData = false;
public static final boolean logEvents = false;
public static final boolean logProfile = false;
// DanaR specific
public static final boolean logDanaBTComm = true;
public static boolean logDanaMessageDetail = true;
public static final boolean logDanaSerialEngine = true;
}

View file

@ -67,4 +67,5 @@ public class Constants {
//SMS Communicator
public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs();
}

View file

@ -38,14 +38,21 @@ import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
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.events.EventAppExit;
import info.nightscout.androidaps.events.EventFeatureRunning;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.LogSettingActivity;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
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.setupwizard.SetupWizardActivity;
import info.nightscout.androidaps.tabs.TabPageAdapter;
@ -58,7 +65,7 @@ import info.nightscout.utils.PasswordProtection;
import info.nightscout.utils.SP;
public class MainActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(MainActivity.class);
private static Logger log = LoggerFactory.getLogger(L.CORE);
protected PowerManager.WakeLock mWakeLock;
@ -70,7 +77,7 @@ public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Config.logFunctionCalls)
if (L.isEnabled(L.CORE))
log.debug("onCreate");
Iconify.with(new FontAwesomeModule());
@ -130,6 +137,9 @@ public class MainActivity extends AppCompatActivity {
protected void onResume() {
super.onResume();
if (L.isEnabled(L.CORE))
log.debug("onResume");
if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) {
Intent intent = new Intent(this, SetupWizardActivity.class);
startActivity(intent);
@ -149,6 +159,8 @@ public class MainActivity extends AppCompatActivity {
@Override
public void onDestroy() {
if (L.isEnabled(L.CORE))
log.debug("onDestroy");
if (mWakeLock != null)
if (mWakeLock.isHeld())
mWakeLock.release();
@ -281,7 +293,7 @@ public class MainActivity extends AppCompatActivity {
private void checkUpgradeToProfileTarget() { // TODO: can be removed in the future
boolean oldKeyExists = SP.contains("openapsma_min_bg");
if (oldKeyExists) {
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
String oldRange = SP.getDouble("openapsma_min_bg", 0d) + " - " + SP.getDouble("openapsma_max_bg", 0d);
String newRange = "";
if (profile != null) {
@ -391,6 +403,9 @@ public class MainActivity extends AppCompatActivity {
case R.id.nav_show_logcat:
LogDialog.showLogcat(this);
return true;
case R.id.nav_logsettings:
startActivity(new Intent(this, LogSettingActivity.class));
return true;
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION);
@ -400,7 +415,7 @@ public class MainActivity extends AppCompatActivity {
builder.setIcon(R.mipmap.blueowl);
String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + ConfigBuilderPlugin.nightscoutVersionName;
message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName;
if (MainApp.engineeringMode)
message += "\n" + MainApp.gs(R.string.engineering_mode_enabled);
message += MainApp.gs(R.string.about_link_urls);

View file

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

View file

@ -1,616 +0,0 @@
package info.nightscout.androidaps.Services;
import android.app.IntentService;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Telephony;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventNewSMS;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.Source.SourcePoctechPlugin;
import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.utils.BundleLogger;
import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
public class DataService extends IntentService {
private static Logger log = LoggerFactory.getLogger(DataService.class);
boolean xDripEnabled = false;
boolean nsClientEnabled = true;
boolean mm640gEnabled = false;
boolean glimpEnabled = false;
boolean dexcomG5Enabled = false;
boolean poctechEnabled = false;
public DataService() {
super("DataService");
registerBus();
}
@Override
protected void onHandleIntent(final Intent intent) {
if (Config.logFunctionCalls)
log.debug("onHandleIntent " + BundleLogger.log(intent.getExtras()));
if (ConfigBuilderPlugin.getPlugin().getActiveBgSource() == null) {
xDripEnabled = true;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceXdripPlugin.class)) {
xDripEnabled = true;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceNSClientPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = true;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceMM640gPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = true;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceGlimpPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = true;
dexcomG5Enabled = false;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourceDexcomG5Plugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = true;
poctechEnabled = false;
} else if (ConfigBuilderPlugin.getPlugin().getActiveBgSource().getClass().equals(SourcePoctechPlugin.class)) {
xDripEnabled = false;
nsClientEnabled = false;
mm640gEnabled = false;
glimpEnabled = false;
dexcomG5Enabled = false;
poctechEnabled = true;
}
boolean isNSProfile = MainApp.getConfigBuilder().getActiveProfileInterface() != null && MainApp.getConfigBuilder().getActiveProfileInterface().getClass().equals(NSProfilePlugin.class);
boolean acceptNSData = !SP.getBoolean(R.string.key_ns_upload_only, false);
Bundle bundles = intent.getExtras();
if (bundles != null && bundles.containsKey("islocal")) {
acceptNSData = acceptNSData || bundles.getBoolean("islocal");
}
if (intent != null) {
final String action = intent.getAction();
if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) {
if (xDripEnabled) {
handleNewDataFromXDrip(intent);
}
} else if (Intents.NS_EMULATOR.equals(action)) {
if (mm640gEnabled) {
handleNewDataFromMM640g(intent);
}
} else if (Intents.GLIMP_BG.equals(action)) {
if (glimpEnabled) {
handleNewDataFromGlimp(intent);
}
} else if (Intents.DEXCOMG5_BG.equals(action)) {
if (dexcomG5Enabled) {
handleNewDataFromDexcomG5(intent);
}
} else if (Intents.POCTECH_BG.equals(action)) {
if (poctechEnabled) {
handleNewDataFromPoctech(intent);
}
} else if (Intents.ACTION_NEW_SGV.equals(action)) {
if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true))
handleNewDataFromNSClient(intent);
// Objectives 0
ObjectivesPlugin.bgIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
} else if (isNSProfile && Intents.ACTION_NEW_PROFILE.equals(action) || Intents.ACTION_NEW_DEVICESTATUS.equals(action)) {
// always handle Profile if NSProfile is enabled without looking at nsUploadOnly
handleNewDataFromNSClient(intent);
} else if (acceptNSData &&
(Intents.ACTION_NEW_TREATMENT.equals(action) ||
Intents.ACTION_CHANGED_TREATMENT.equals(action) ||
Intents.ACTION_REMOVED_TREATMENT.equals(action) ||
Intents.ACTION_NEW_STATUS.equals(action) ||
Intents.ACTION_NEW_DEVICESTATUS.equals(action) ||
Intents.ACTION_NEW_FOOD.equals(action) ||
Intents.ACTION_CHANGED_FOOD.equals(action) ||
Intents.ACTION_REMOVED_FOOD.equals(action) ||
Intents.ACTION_NEW_CAL.equals(action) ||
Intents.ACTION_NEW_MBG.equals(action))
) {
handleNewDataFromNSClient(intent);
} else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) {
handleNewSMS(intent);
}
}
if (Config.logFunctionCalls)
log.debug("onHandleIntent exit " + intent);
DataReceiver.completeWakefulIntent(intent);
}
/*
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (Config.logFunctionCalls)
log.debug("onStartCommand");
return START_STICKY;
}
*/
@Override
public void onDestroy() {
super.onDestroy();
MainApp.bus().unregister(this);
}
private void registerBus() {
try {
MainApp.bus().unregister(this);
} catch (RuntimeException x) {
// Ignore
}
MainApp.bus().register(this);
}
private void handleNewDataFromXDrip(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
bgReading.value = bundle.getDouble(Intents.EXTRA_BG_ESTIMATE);
bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME);
bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP);
bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW);
String source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified");
SourceXdripPlugin.getPlugin().setSource(source);
MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP");
}
private void handleNewDataFromGlimp(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
bgReading.value = bundle.getDouble("mySGV");
bgReading.direction = bundle.getString("myTrend");
bgReading.date = bundle.getLong("myTimestamp");
bgReading.raw = 0;
MainApp.getDbHelper().createIfNotExists(bgReading, "GLIMP");
}
private void handleNewDataFromDexcomG5(Intent intent) {
// onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
String data = bundle.getString("data");
log.debug("Received Dexcom Data", data);
try {
JSONArray jsonArray = new JSONArray(data);
log.debug("Received Dexcom Data size:" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
bgReading.value = json.getInt("m_value");
bgReading.direction = json.getString("m_trend");
bgReading.date = json.getLong("m_time") * 1000L;
bgReading.raw = 0;
boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5");
if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading);
}
if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleNewDataFromPoctech(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
String data = bundle.getString("data");
log.debug("Received Poctech Data", data);
try {
JSONArray jsonArray = new JSONArray(data);
log.debug("Received Poctech Data size:" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
bgReading.value = json.getDouble("current");
bgReading.direction = json.getString("direction");
bgReading.date = json.getLong("date");
bgReading.raw = json.getDouble("raw");
if (JsonHelper.safeGetString(json, "units", Constants.MGDL).equals("mmol/L"))
bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL;
boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech");
if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading);
}
if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void handleNewDataFromMM640g(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
final String collection = bundle.getString("collection");
if (collection == null) return;
if (collection.equals("entries")) {
final String data = bundle.getString("data");
if ((data != null) && (data.length() > 0)) {
try {
final JSONArray json_array = new JSONArray(data);
for (int i = 0; i < json_array.length(); i++) {
final JSONObject json_object = json_array.getJSONObject(i);
final String type = json_object.getString("type");
switch (type) {
case "sgv":
BgReading bgReading = new BgReading();
bgReading.value = json_object.getDouble("sgv");
bgReading.direction = json_object.getString("direction");
bgReading.date = json_object.getLong("date");
bgReading.raw = json_object.getDouble("sgv");
MainApp.getDbHelper().createIfNotExists(bgReading, "MM640g");
break;
default:
log.debug("Unknown entries type: " + type);
}
}
} catch (JSONException e) {
log.error("Got JSON exception: " + e);
}
}
}
}
private void handleNewDataFromNSClient(Intent intent) {
Bundle bundles = intent.getExtras();
if (bundles == null) return;
if (Config.logIncommingData)
log.debug("Got intent: " + intent.getAction());
if (intent.getAction().equals(Intents.ACTION_NEW_STATUS)) {
if (bundles.containsKey("nsclientversioncode")) {
ConfigBuilderPlugin.nightscoutVersionCode = bundles.getInt("nightscoutversioncode"); // for ver 1.2.3 contains 10203
ConfigBuilderPlugin.nightscoutVersionName = bundles.getString("nightscoutversionname");
ConfigBuilderPlugin.nsClientVersionCode = bundles.getInt("nsclientversioncode"); // for ver 1.17 contains 117
ConfigBuilderPlugin.nsClientVersionName = bundles.getString("nsclientversionname");
log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName);
try {
if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
}
} catch (PackageManager.NameNotFoundException e) {
log.error("Unhandled exception", e);
}
if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS));
}
} else {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
}
if (bundles.containsKey("status")) {
try {
JSONObject statusJson = new JSONObject(bundles.getString("status"));
NSSettingsStatus.getInstance().setData(statusJson);
if (Config.logIncommingData)
log.debug("Received status: " + statusJson.toString());
Double targetHigh = NSSettingsStatus.getInstance().getThreshold("bgTargetTop");
Double targetlow = NSSettingsStatus.getInstance().getThreshold("bgTargetBottom");
if (targetHigh != null)
OverviewPlugin.bgTargetHigh = targetHigh;
if (targetlow != null)
OverviewPlugin.bgTargetLow = targetlow;
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_DEVICESTATUS)) {
try {
if (bundles.containsKey("devicestatus")) {
JSONObject devicestatusJson = new JSONObject(bundles.getString("devicestatus"));
NSDeviceStatus.getInstance().setData(devicestatusJson);
if (devicestatusJson.has("pump")) {
// Objectives 0
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
}
}
if (bundles.containsKey("devicestatuses")) {
String devicestatusesstring = bundles.getString("devicestatuses");
JSONArray jsonArray = new JSONArray(devicestatusesstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject devicestatusJson = jsonArray.getJSONObject(i);
NSDeviceStatus.getInstance().setData(devicestatusJson);
if (devicestatusJson.has("pump")) {
// Objectives 0
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
}
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
// Handle profile
if (intent.getAction().equals(Intents.ACTION_NEW_PROFILE)) {
try {
String activeProfile = bundles.getString("activeprofile");
String profile = bundles.getString("profile");
ProfileStore profileStore = new ProfileStore(new JSONObject(profile));
NSProfilePlugin.getPlugin().storeNewProfile(profileStore);
MainApp.bus().post(new EventNSProfileUpdateGUI());
if (Config.logIncommingData)
log.debug("Received profileStore: " + activeProfile + " " + profile);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_TREATMENT) || intent.getAction().equals(Intents.ACTION_CHANGED_TREATMENT)) {
try {
if (bundles.containsKey("treatment")) {
JSONObject json = new JSONObject(bundles.getString("treatment"));
handleTreatmentFromNS(json, intent);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
handleTreatmentFromNS(json, intent);
}
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_REMOVED_TREATMENT)) {
try {
if (bundles.containsKey("treatment")) {
String trstring = bundles.getString("treatment");
JSONObject json = new JSONObject(trstring);
handleTreatmentFromNS(json);
}
if (bundles.containsKey("treatments")) {
String trstring = bundles.getString("treatments");
JSONArray jsonArray = new JSONArray(trstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
handleTreatmentFromNS(json);
}
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_SGV)) {
try {
if (bundles.containsKey("sgv")) {
String sgvstring = bundles.getString("sgv");
JSONObject sgvJson = new JSONObject(sgvstring);
storeSgv(sgvJson);
}
if (bundles.containsKey("sgvs")) {
String sgvstring = bundles.getString("sgvs");
JSONArray jsonArray = new JSONArray(sgvstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject sgvJson = jsonArray.getJSONObject(i);
storeSgv(sgvJson);
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_MBG)) {
try {
if (bundles.containsKey("mbg")) {
String mbgstring = bundles.getString("mbg");
JSONObject mbgJson = new JSONObject(mbgstring);
storeMbg(mbgJson);
}
if (bundles.containsKey("mbgs")) {
String sgvstring = bundles.getString("mbgs");
JSONArray jsonArray = new JSONArray(sgvstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject mbgJson = jsonArray.getJSONObject(i);
storeMbg(mbgJson);
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
if (intent.getAction().equals(Intents.ACTION_NEW_FOOD)
|| intent.getAction().equals(Intents.ACTION_CHANGED_FOOD)) {
int mode = Intents.ACTION_NEW_FOOD.equals(intent.getAction()) ? EventNsFood.ADD : EventNsFood.UPDATE;
EventNsFood evt = new EventNsFood(mode, bundles);
MainApp.bus().post(evt);
}
if (intent.getAction().equals(Intents.ACTION_REMOVED_FOOD)) {
EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles);
MainApp.bus().post(evt);
}
}
private void handleTreatmentFromNS(JSONObject json) {
// new DB model
EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json);
MainApp.bus().post(evtTreatment);
// old DB model
String _id = JsonHelper.safeGetString(json, "_id");
MainApp.getDbHelper().deleteTempTargetById(_id);
MainApp.getDbHelper().deleteTempBasalById(_id);
MainApp.getDbHelper().deleteExtendedBolusById(_id);
MainApp.getDbHelper().deleteCareportalEventById(_id);
MainApp.getDbHelper().deleteProfileSwitchById(_id);
}
private void handleTreatmentFromNS(JSONObject json, Intent intent) throws JSONException {
// new DB model
int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE;
double insulin = JsonHelper.safeGetDouble(json, "insulin");
double carbs = JsonHelper.safeGetDouble(json, "carbs");
String eventType = JsonHelper.safeGetString(json, "eventType");
if (insulin > 0 || carbs > 0) {
EventNsTreatment evtTreatment = new EventNsTreatment(mode, json);
MainApp.bus().post(evtTreatment);
} else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) {
// old DB model
MainApp.getDbHelper().updateDanaRHistoryRecordId(json);
} else if (eventType.equals(CareportalEvent.TEMPORARYTARGET)) {
MainApp.getDbHelper().createTemptargetFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.TEMPBASAL)) {
MainApp.getDbHelper().createTempBasalFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.COMBOBOLUS)) {
MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.PROFILESWITCH)) {
MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(json);
} else if (eventType.equals(CareportalEvent.SITECHANGE) ||
eventType.equals(CareportalEvent.INSULINCHANGE) ||
eventType.equals(CareportalEvent.SENSORCHANGE) ||
eventType.equals(CareportalEvent.BGCHECK) ||
eventType.equals(CareportalEvent.NOTE) ||
eventType.equals(CareportalEvent.NONE) ||
eventType.equals(CareportalEvent.ANNOUNCEMENT) ||
eventType.equals(CareportalEvent.QUESTION) ||
eventType.equals(CareportalEvent.EXERCISE) ||
eventType.equals(CareportalEvent.OPENAPSOFFLINE) ||
eventType.equals(CareportalEvent.PUMPBATTERYCHANGE)) {
MainApp.getDbHelper().createCareportalEventFromJsonIfNotExists(json);
}
if (eventType.equals(CareportalEvent.ANNOUNCEMENT)) {
long date = JsonHelper.safeGetLong(json,"mills");
long now = System.currentTimeMillis();
String enteredBy = JsonHelper.safeGetString(json, "enteredBy", "");
String notes = JsonHelper.safeGetString(json, "notes", "");
if (date > now - 15 * 60 * 1000L && !notes.isEmpty()
&& !enteredBy.equals(SP.getString("careportal_enteredby", "AndroidAPS"))) {
Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60);
MainApp.bus().post(new EventNewNotification(announcement));
}
}
}
private void storeMbg(JSONObject mbgJson) {
NSMbg nsMbg = new NSMbg(mbgJson);
CareportalEvent careportalEvent = new CareportalEvent(nsMbg);
MainApp.getDbHelper().createOrUpdate(careportalEvent);
if (Config.logIncommingData)
log.debug("Adding/Updating new MBG: " + careportalEvent.log());
}
private void storeSgv(JSONObject sgvJson) {
NSSgv nsSgv = new NSSgv(sgvJson);
BgReading bgReading = new BgReading(nsSgv);
MainApp.getDbHelper().createIfNotExists(bgReading, "NS");
SourceNSClientPlugin.getPlugin().detectSource(JsonHelper.safeGetString(sgvJson, "device"), JsonHelper.safeGetLong(sgvJson, "mills"));
}
private void handleNewSMS(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
MainApp.bus().post(new EventNewSMS(bundle));
}
}

View file

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

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps;
package info.nightscout.androidaps.activities;
import android.os.Bundle;
import android.os.SystemClock;
@ -29,10 +29,13 @@ import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnLongClick;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
@ -227,7 +230,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
return;
final PumpInterface pump = ConfigBuilderPlugin.getActivePump();
final Profile profile = MainApp.getConfigBuilder().getProfile();
final Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) {
noProfile.setVisibility(View.VISIBLE);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps;
package info.nightscout.androidaps.activities;
import android.content.SharedPreferences;
import android.os.Bundle;
@ -11,6 +11,9 @@ import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase;
@ -86,7 +89,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
pref.setSummary("******");
} else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) {
pref.setSummary(SP.getString(R.string.key_danars_name, ""));
} else if (editTextPref.getText() != null && !editTextPref.getText().equals("")) {
} else if (editTextPref.getText() != null ) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText());
} else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) {

View file

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

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps;
package info.nightscout.androidaps.activities;
import android.app.Activity;
import android.graphics.Color;
@ -33,14 +33,15 @@ import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
@ -121,7 +122,7 @@ public class TDDStatsActivity extends Activity {
TBB = SP.getString("TBB", "10.00");
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile != null) {
double cppTBB = profile.baseBasalSum();
TBB = decimalFormat.format(cppTBB);

View file

@ -52,6 +52,14 @@ public class Profile {
protected Profile() {
}
@Override
public String toString() {
if (json != null)
return json.toString();
else
return "Profile has no JSON";
}
// Constructor from profileStore JSON
public Profile(JSONObject json, String units) {
init(json, 100, 0);
@ -295,8 +303,6 @@ public class Profile {
Integer getShitfTimeSecs(Integer originalTime) {
Integer shiftedTime = originalTime + timeshift * 60 * 60;
shiftedTime = (shiftedTime + 24 * 60 * 60) % (24 * 60 * 60);
if (timeshift != 0 && Config.logProfile)
log.debug("(Sec) Original time: " + originalTime + " ShiftedTime: " + shiftedTime);
return shiftedTime;
}

View file

@ -10,11 +10,12 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.Round;
public class PumpEnactResult {
private static Logger log = LoggerFactory.getLogger(PumpEnactResult.class);
private static Logger log = LoggerFactory.getLogger(L.APS);
public boolean success = false; // request was processed successfully (but possible no change was needed)
public boolean enacted = false; // request was processed successfully and change has been made

View file

@ -15,6 +15,8 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
@ -24,7 +26,7 @@ import info.nightscout.utils.SP;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)
public class BgReading implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(BgReading.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;
@ -142,7 +144,7 @@ public class BgReading implements DataPointWithLabelInterface {
return false;
if (raw != other.raw)
return false;
if (!direction.equals(other.direction))
if (!Objects.equals(direction, other.direction))
return false;
if (!Objects.equals(_id, other._id))
return false;
@ -168,7 +170,7 @@ public class BgReading implements DataPointWithLabelInterface {
@Override
public double getY() {
String units = MainApp.getConfigBuilder().getProfileUnits();
String units = ProfileFunctions.getInstance().getProfileUnits();
return valueToUnits(units);
}
@ -202,7 +204,7 @@ public class BgReading implements DataPointWithLabelInterface {
@Override
public int getColor() {
String units = MainApp.getConfigBuilder().getProfileUnits();
String units = ProfileFunctions.getInstance().getProfileUnits();
Double lowLine = SP.getDouble("low_mark", 0d);
Double highLine = SP.getDouble("high_mark", 0d);
if (lowLine < 1) {

View file

@ -25,6 +25,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
@ -35,7 +37,7 @@ import info.nightscout.utils.Translator;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
public class CareportalEvent implements DataPointWithLabelInterface, Interval {
private static Logger log = LoggerFactory.getLogger(CareportalEvent.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;
@ -153,7 +155,7 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@Override
public double getY() {
String units = MainApp.getConfigBuilder().getProfileUnits();
String units = ProfileFunctions.getInstance().getProfileUnits();
if (eventType.equals(MBG)) {
double mbg = 0d;
try {

View file

@ -27,8 +27,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
@ -43,12 +41,14 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.PercentageSplitter;
import info.nightscout.utils.ToastUtils;
@ -61,7 +61,7 @@ import info.nightscout.utils.ToastUtils;
* direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static Logger log = LoggerFactory.getLogger(DatabaseHelper.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
public static final String DATABASE_NAME = "AndroidAPSDb";
public static final String DATABASE_BGREADINGS = "BgReadings";
@ -108,7 +108,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
log.info("onCreate");
if (L.isEnabled(L.DATABASE))
log.info("onCreate");
TableUtils.createTableIfNotExists(connectionSource, TempTarget.class);
TableUtils.createTableIfNotExists(connectionSource, BgReading.class);
TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class);
@ -326,15 +327,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
BgReading old = getDaoBgReadings().queryForId(bgReading.date);
if (old == null) {
getDaoBgReadings().create(bgReading);
log.debug("BG: New record from: " + from + " " + bgReading.toString());
if (L.isEnabled(L.DATABASE))
log.debug("BG: New record from: " + from + " " + bgReading.toString());
scheduleBgChange(bgReading);
return true;
}
if (!old.isEqual(bgReading)) {
log.debug("BG: Similiar found: " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("BG: Similiar found: " + old.toString());
old.copyFrom(bgReading);
getDaoBgReadings().update(old);
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("BG: Updating record from: " + from + " New data: " + old.toString());
scheduleBgChange(bgReading);
return false;
}
@ -356,7 +360,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleBgChange(@Nullable final BgReading bgReading) {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventNewBg");
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
MainApp.bus().post(new EventNewBG(bgReading));
scheduledBgPost = null;
}
@ -388,7 +393,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) {
log.debug(e.getMessage(), e);
log.error("Unhandled exception", e);
}
if (bgList != null && bgList.size() > 0)
return bgList.get(0);
@ -596,7 +601,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
@ -615,20 +621,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTempTargets().delete(old); // need to delete/create because date may change too
old.copyFrom(tempTarget);
getDaoTempTargets().create(old);
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString());
scheduleTemporaryTargetChange();
return true;
}
}
}
getDaoTempTargets().create(tempTarget);
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
if (tempTarget.source == Source.USER) {
getDaoTempTargets().create(tempTarget);
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString());
scheduleTemporaryTargetChange();
return true;
}
@ -650,7 +659,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleTemporaryTargetChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempTargetChange");
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange");
MainApp.bus().post(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
@ -682,7 +692,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTemptargetFromJsonIfNotExists(JSONObject trJson) {
try {
String units = JsonHelper.safeGetString(trJson, "units", MainApp.getConfigBuilder().getProfileUnits());
String units = JsonHelper.safeGetString(trJson, "units", ProfileFunctions.getInstance().getProfileUnits());
TempTarget tempTarget = new TempTarget()
.date(trJson.getLong("mills"))
.duration(trJson.getInt("duration"))
@ -770,7 +780,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} else if (list.size() == 1) {
DanaRHistoryRecord record = list.get(0);
if (record._id == null || !record._id.equals(trJson.getString("_id"))) {
if (Config.logIncommingData)
if (L.isEnabled(L.DATABASE))
log.debug("Updating _id in DanaR history database: " + trJson.getString("_id"));
record._id = trJson.getString("_id");
getDaoDanaRHistory().update(record);
@ -800,11 +810,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
List<TemporaryBasal> trList = getDaoTemporaryBasal().query(preparedQuery);
if (trList.size() > 0) {
// do nothing, pump history record cannot be changed
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false;
}
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
@ -821,7 +833,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
@ -843,7 +856,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too
old.copyFrom(tempBasal);
getDaoTemporaryBasal().create(old);
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleTemporaryBasalChange();
@ -852,14 +866,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
}
if (tempBasal.source == Source.USER) {
getDaoTemporaryBasal().create(tempBasal);
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
updateEarliestDataChange(tempBasal.date);
scheduleTemporaryBasalChange();
return true;
@ -899,7 +915,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventTempBasalChange");
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempBasalChange");
MainApp.bus().post(new EventReloadTempBasalData());
MainApp.bus().post(new EventTempBasalChange());
if (earliestDataChange != null)
@ -991,7 +1008,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteTempBasalById(String _id) {
TemporaryBasal stored = findTempBasalById(_id);
if (stored != null) {
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleTemporaryBasalChange();
@ -1037,7 +1055,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return false;
}
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
@ -1050,7 +1069,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
@ -1072,7 +1092,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoExtendedBolus().delete(old); // need to delete/create because date may change too
old.copyFrom(extendedBolus);
getDaoExtendedBolus().create(old);
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.toString());
updateEarliestDataChange(oldDate);
updateEarliestDataChange(old.date);
scheduleExtendedBolusChange();
@ -1081,14 +1102,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
}
if (extendedBolus.source == Source.USER) {
getDaoExtendedBolus().create(extendedBolus);
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.toString());
updateEarliestDataChange(extendedBolus.date);
scheduleExtendedBolusChange();
return true;
@ -1128,7 +1151,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteExtendedBolusById(String _id) {
ExtendedBolus stored = findExtendedBolusById(_id);
if (stored != null) {
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
if (L.isEnabled(L.DATABASE))
log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString());
delete(stored);
updateEarliestDataChange(stored.date);
scheduleExtendedBolusChange();
@ -1181,7 +1205,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleExtendedBolusChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventExtendedBolusChange");
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange");
MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
@ -1321,11 +1346,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (list.size() == 1) {
CareportalEvent record = list.get(0);
if (Config.logIncommingData)
if (L.isEnabled(L.DATABASE))
log.debug("Removing CareportalEvent record from database: " + record.log());
delete(record);
} else {
if (Config.logIncommingData)
if (L.isEnabled(L.DATABASE))
log.debug("CareportalEvent not found database: " + _id);
}
} catch (SQLException e) {
@ -1345,12 +1370,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (list.size() == 0) {
careportalEvent = new CareportalEvent();
careportalEvent.source = Source.NIGHTSCOUT;
if (Config.logIncommingData)
if (L.isEnabled(L.DATABASE))
log.debug("Adding CareportalEvent record to database: " + trJson.toString());
// Record does not exists. add
} else if (list.size() == 1) {
careportalEvent = list.get(0);
if (Config.logIncommingData)
if (L.isEnabled(L.DATABASE))
log.debug("Updating CareportalEvent record in database: " + trJson.toString());
} else {
log.error("Something went wrong");
@ -1369,7 +1394,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleCareportalEventChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing scheduleCareportalEventChange");
if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange");
MainApp.bus().post(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
@ -1415,7 +1441,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
@ -1434,7 +1461,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
getDaoProfileSwitch().delete(old); // need to delete/create because date may change too
old.copyFrom(profileSwitch);
getDaoProfileSwitch().create(old);
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString());
scheduleProfileSwitchChange();
return true;
}
@ -1443,13 +1471,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// look for already added percentage from NS
profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName);
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
if (profileSwitch.source == Source.USER) {
getDaoProfileSwitch().create(profileSwitch);
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString());
scheduleProfileSwitchChange();
return true;
}
@ -1471,7 +1501,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static void scheduleProfileSwitchChange() {
class PostRunnable implements Runnable {
public void run() {
log.debug("Firing EventProfileSwitchChange");
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventProfileSwitchChange");
MainApp.bus().post(new EventReloadProfileSwitchData());
MainApp.bus().post(new EventProfileSwitchChange());
scheduledProfileSwitchEventPost = null;
@ -1521,15 +1552,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
Profile profile = store.getSpecificProfile(profileSwitch.profileName);
if (profile != null) {
profileSwitch.profileJson = profile.getData().toString();
log.debug("Profile switch prefilled with JSON from local store");
if (L.isEnabled(L.DATABASE))
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
} else {
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
if (L.isEnabled(L.DATABASE))
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
} else {
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
if (L.isEnabled(L.DATABASE))
log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString());
return;
}
}
@ -1544,7 +1578,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void deleteProfileSwitchById(String _id) {
ProfileSwitch stored = findProfileSwitchById(_id);
if (stored != null) {
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
if (L.isEnabled(L.DATABASE))
log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString());
delete(stored);
scheduleTemporaryTargetChange();
}

View file

@ -10,6 +10,8 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
/**
* Created by mike on 27.02.2016.
* <p>
@ -17,7 +19,7 @@ import org.slf4j.LoggerFactory;
*/
@DatabaseTable(tableName = DatabaseHelper.DATABASE_DBREQUESTS)
public class DbRequest {
private static Logger log = LoggerFactory.getLogger(DbRequest.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public String nsClientID = null;

View file

@ -21,6 +21,7 @@ import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -36,7 +37,7 @@ import info.nightscout.utils.Round;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_EXTENDEDBOLUSES)
public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(ExtendedBolus.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;

View file

@ -17,6 +17,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -27,7 +28,7 @@ import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(ProfileSwitch.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;

View file

@ -8,6 +8,8 @@ import org.slf4j.LoggerFactory;
import java.util.Objects;
import info.nightscout.androidaps.logging.L;
/**
* Created by mike on 20.09.2017.
*/
@ -15,7 +17,7 @@ import java.util.Objects;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TDDS)
public class TDD {
private static Logger log = LoggerFactory.getLogger(TDD.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;

View file

@ -11,12 +11,13 @@ import java.util.Objects;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS)
public class TempTarget implements Interval {
private static Logger log = LoggerFactory.getLogger(TempTarget.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;

View file

@ -15,7 +15,9 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter;
@ -27,7 +29,7 @@ import info.nightscout.utils.SP;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS)
public class TemporaryBasal implements Interval {
private static Logger log = LoggerFactory.getLogger(TemporaryBasal.class);
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
public long date;
@ -93,7 +95,7 @@ public class TemporaryBasal implements Interval {
}
public TemporaryBasal(ExtendedBolus extendedBolus) {
double basal = MainApp.getConfigBuilder().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
double basal = ProfileFunctions.getInstance().getProfile(extendedBolus.date).getBasal(extendedBolus.date);
this.date = extendedBolus.date;
this.isValid = extendedBolus.isValid;
this.source = extendedBolus.source;
@ -318,7 +320,7 @@ public class TemporaryBasal implements Interval {
public String toStringFull() {
if(isFakeExtended){
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal();
double rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
return getCalcuatedPercentageIfNeeded() + DecimalFormatter.to2Decimal(rate) + "U/h ("+DecimalFormatter.to2Decimal(netExtendedRate)+"E) @" +
@ -340,7 +342,7 @@ public class TemporaryBasal implements Interval {
double rate = 0d;
if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal();
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
} else if (isAbsolute){
@ -348,7 +350,7 @@ public class TemporaryBasal implements Interval {
}
if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if(profile != null) {
double basal = profile.getBasal();
if(basal != 0){
@ -367,7 +369,7 @@ public class TemporaryBasal implements Interval {
double rate = 0d;
if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal();
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
} else if (isAbsolute){
@ -375,7 +377,7 @@ public class TemporaryBasal implements Interval {
}
if(SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)){
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if(profile != null) {
double basal = profile.getBasal();
if(basal != 0){
@ -392,7 +394,7 @@ public class TemporaryBasal implements Interval {
double rate = 0d;
if (isFakeExtended) {
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasalRate = profile.getBasal();
rate = (currentBasalRate == null)?0d:(currentBasalRate+netExtendedRate);
} else if (isAbsolute){

View file

@ -1,8 +1,12 @@
package info.nightscout.androidaps.interfaces;
import android.content.Intent;
/**
* Created by mike on 20.06.2016.
*/
public interface BgSourceInterface {
boolean advancedFilteringSupported();
void handleNewData(Intent intent);
}

View file

@ -6,12 +6,14 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.logging.L;
/**
* Created by mike on 19.03.2018.
*/
public class Constraint<T extends Comparable> {
private static Logger log = LoggerFactory.getLogger(Constraint.class);
private static Logger log = LoggerFactory.getLogger(L.APS);
T value;
T originalValue;
@ -57,7 +59,7 @@ public class Constraint<T extends Comparable> {
return this;
}
public Constraint<T> setIfGreater(T value, String reason, Object from) {
public Constraint<T> setIfGreater(T value, String reason, Object from) {
if (value.compareTo(this.value) > 0) {
this.value = value;
mostLimiting.clear();
@ -74,7 +76,7 @@ public class Constraint<T extends Comparable> {
return this;
}
public Constraint addMostLimingReason(String reason, Object from) {
public Constraint addMostLimingReason(String reason, Object from) {
mostLimiting.add(from.getClass().getSimpleName().replace("Plugin", "") + ": " + reason);
return this;
}
@ -86,7 +88,8 @@ public class Constraint<T extends Comparable> {
if (count++ != 0) sb.append("\n");
sb.append(r);
}
log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString());
if (L.isEnabled(L.APS))
log.debug("Limiting origial value: " + originalValue + " to " + value + ". Reason: " + sb.toString());
return sb.toString();
}
@ -110,7 +113,7 @@ public class Constraint<T extends Comparable> {
}
public void copyReasons(Constraint<?> another) {
for (String s: another.getReasonList()) {
for (String s : another.getReasonList()) {
reasons.add(s);
}
}

View file

@ -7,6 +7,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
@ -14,7 +15,7 @@ import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
* Created by mike on 09.06.2016.
*/
public abstract class PluginBase {
private static Logger log = LoggerFactory.getLogger(PluginBase.class);
private static Logger log = LoggerFactory.getLogger(L.CORE);
public enum State {
NOT_INITIALIZED,
@ -113,7 +114,8 @@ public abstract class PluginBase {
if (state != State.ENABLED) {
onStateChange(type, state, State.ENABLED);
state = State.ENABLED;
log.debug("Starting: " + getName());
if (L.isEnabled(L.CORE))
log.debug("Starting: " + getName());
onStart();
}
} else { // disabling plugin
@ -121,7 +123,8 @@ public abstract class PluginBase {
onStateChange(type, state, State.ENABLED);
state = State.DISABLED;
onStop();
log.debug("Stopping: " + getName());
if (L.isEnabled(L.CORE))
log.debug("Stopping: " + getName());
}
}
} else if (type == PluginType.PROFILE) {

View file

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

View file

@ -0,0 +1,121 @@
package info.nightscout.androidaps.logging;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.utils.SP;
public class L {
public static class LogElement {
String name;
boolean defaultValue;
boolean enabled;
boolean requiresRestart = false;
LogElement(String name, boolean defaultValue) {
this.name = name;
this.defaultValue = defaultValue;
enabled = SP.getBoolean(getSPName(), defaultValue);
}
LogElement(String name, boolean defaultValue, boolean requiresRestart) {
this.name = name;
this.defaultValue = defaultValue;
this.requiresRestart = requiresRestart;
enabled = SP.getBoolean(getSPName(), defaultValue);
}
LogElement(boolean defaultValue) {
this.name = "NONEXISTING";
this.defaultValue = defaultValue;
enabled = defaultValue;
}
private String getSPName() {
return "log_" + name;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
SP.putBoolean(getSPName(), enabled);
}
void resetToDefault() {
setEnabled(defaultValue);
}
}
private static List<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 List<LogElement> getLogElements() {
return logElements;
}
public static void resetToDefaults() {
for (LogElement element : logElements) {
element.resetToDefault();
}
}
public static final String CORE = "CORE";
public static final String AUTOSENS = "AUTOSENS";
public static final String EVENTS = "EVENTS";
public static final String BGSOURCE = "BGSOURCE";
public static final String OVERVIEW = "OVERVIEW";
public static final String NOTIFICATION = "NOTIFICATION";
public static final String DATASERVICE = "DATASERVICE";
public static final String DATABASE = "DATABASE";
public static final String DATAFOOD = "DATAFOOD";
public static final String DATATREATMENTS = "DATATREATMENTS";
public static final String NSCLIENT = "NSCLIENT";
public static final String OBJECTIVES = "OBJECTIVES";
public static final String PUMP = "PUMP";
public static final String PUMPQUEUE = "PUMPQUEUE";
public static final String PUMPCOMM = "PUMPCOMM";
public static final String PUMPBTCOMM = "PUMPBTCOMM";
public static final String APS = "APS";
public static final String PROFILE = "PROFILE";
public static final String CONFIGBUILDER = "CONFIGBUILDER";
private static void initialize() {
logElements = new ArrayList<>();
logElements.add(new LogElement(APS, true));
logElements.add(new LogElement(AUTOSENS, false));
logElements.add(new LogElement(BGSOURCE, true));
logElements.add(new LogElement(CONFIGBUILDER, true));
logElements.add(new LogElement(CORE, true));
logElements.add(new LogElement(DATABASE, true));
logElements.add(new LogElement(DATAFOOD, true));
logElements.add(new LogElement(DATASERVICE, true));
logElements.add(new LogElement(DATATREATMENTS, true));
logElements.add(new LogElement(EVENTS, false, true));
logElements.add(new LogElement(NOTIFICATION, true));
logElements.add(new LogElement(NSCLIENT, true));
logElements.add(new LogElement(OBJECTIVES, false));
logElements.add(new LogElement(OVERVIEW, true));
logElements.add(new LogElement(PROFILE, true));
logElements.add(new LogElement(PUMP, true));
logElements.add(new LogElement(PUMPBTCOMM, false));
logElements.add(new LogElement(PUMPCOMM, true));
logElements.add(new LogElement(PUMPQUEUE, true));
}
}

View file

@ -0,0 +1,79 @@
package info.nightscout.androidaps.logging;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.nightscout.androidaps.R;
public class LogSettingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logsetting);
ButterKnife.bind(this);
createViewsForSettings(L.getLogElements());
}
private void createViewsForSettings(List<L.LogElement> elements) {
if (elements.size() == 0) return;
LinearLayout container = (LinearLayout) findViewById(R.id.logsettings_placeholder);
container.removeAllViews();
for (L.LogElement element : elements) {
PluginViewHolder pluginViewHolder = new PluginViewHolder(element);
container.addView(pluginViewHolder.getBaseView());
}
}
@OnClick(R.id.logsettings_reset)
public void onResetClick() {
L.resetToDefaults();
createViewsForSettings(L.getLogElements());
}
public class PluginViewHolder {
private Unbinder unbinder;
private L.LogElement element;
LinearLayout baseView;
@BindView(R.id.logsettings_description)
TextView description;
@BindView(R.id.logsettings_visibility)
CheckBox enabled;
public PluginViewHolder(L.LogElement element) {
this.element = element;
baseView = (LinearLayout) getLayoutInflater().inflate(R.layout.logsettings_item, null);
unbinder = ButterKnife.bind(this, baseView);
description.setText(element.name);
enabled.setChecked(element.enabled);
}
public View getBaseView() {
return baseView;
}
@OnClick(R.id.logsettings_visibility)
void onEnagledChanged() {
element.setEnabled(enabled.isChecked());
}
public void unbind() {
unbinder.unbind();
}
}
}

View file

@ -14,10 +14,10 @@ import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.HistoryBrowseActivity;
import info.nightscout.androidaps.activities.HistoryBrowseActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.TDDStatsActivity;
import info.nightscout.androidaps.activities.TDDStatsActivity;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
@ -33,6 +33,7 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SingleClickButton;
@ -131,7 +132,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
profileSwitch.setVisibility(View.GONE);
}
if (MainApp.getConfigBuilder().getProfile() == null) {
if (ProfileFunctions.getInstance().getProfile() == null) {
tempTarget.setVisibility(View.GONE);
extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.GONE);

View file

@ -39,7 +39,7 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;

View file

@ -25,6 +25,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.FabricPrivacy;
@ -70,7 +71,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
double tempPercentStep = pumpDescription.tempPercentStep;
basalPercent.setParams(100d, 0d, maxTempPercent, tempPercentStep, new DecimalFormat("0"), true);
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
Double currentBasal = profile != null ? profile.getBasal() : 0d;
basalAbsolute = (NumberPicker) view.findViewById(R.id.overview_newtempbasal_basalabsoluteinput);
basalAbsolute.setParams(currentBasal, 0d, pumpDescription.maxTempAbsolute, pumpDescription.tempAbsoluteStep, new DecimalFormat("0.00"), true);
@ -118,7 +119,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
final boolean setAsPercent = percentRadio.isChecked();
int durationInMinutes = SafeParse.stringToInt(duration.getText());
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null)
return;

View file

@ -49,13 +49,14 @@ import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.DefaultValueHelper;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.HardLimits;
import info.nightscout.utils.JsonHelper;
import info.nightscout.utils.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
@ -171,7 +172,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
view.findViewById(R.id.cancel).setOnClickListener(this);
// profile
profile = MainApp.getConfigBuilder().getProfile();
profile = ProfileFunctions.getInstance().getProfile();
profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profileStore == null) {
if (options.eventType == R.id.careportal_profileswitch) {
@ -186,7 +187,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
profileSpinner.setAdapter(adapter);
// set selected to actual profile
for (int p = 0; p < profileList.size(); p++) {
if (profileList.get(p).equals(MainApp.getConfigBuilder().getProfileName(false)))
if (profileList.get(p).equals(ProfileFunctions.getInstance().getProfileName(false)))
profileSpinner.setSelection(p);
}
}
@ -214,7 +215,7 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
}
boolean erase = false;
String units = MainApp.getConfigBuilder().getProfileUnits();
String units = ProfileFunctions.getInstance().getProfileUnits();
DefaultValueHelper helper = new DefaultValueHelper();
if (MainApp.gs(R.string.eatingsoon).equals(reasonList.get(position))) {
defaultDuration = helper.determineEatingSoonTTDuration();
@ -786,8 +787,8 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER;
profileSwitch.profileName = MainApp.getConfigBuilder().getProfileName(System.currentTimeMillis(), false);
profileSwitch.profileJson = MainApp.getConfigBuilder().getProfile().getData().toString();
profileSwitch.profileName = ProfileFunctions.getInstance().getProfileName(System.currentTimeMillis(), false);
profileSwitch.profileJson = ProfileFunctions.getInstance().getProfile().getData().toString();
profileSwitch.profilePlugin = MainApp.getConfigBuilder().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;

View file

@ -26,7 +26,7 @@ import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.PreferencesActivity;
import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventRefreshGui;

View file

@ -1,35 +1,17 @@
package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Intent;
import android.support.annotation.Nullable;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppInitialized;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
@ -38,24 +20,18 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
/**
* Created by mike on 05.08.2016.
*/
public class ConfigBuilderPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(ConfigBuilderPlugin.class);
private Logger log = LoggerFactory.getLogger(L.CONFIGBUILDER);
private static ConfigBuilderPlugin configBuilderPlugin;
@ -70,15 +46,9 @@ public class ConfigBuilderPlugin extends PluginBase {
private static ProfileInterface activeProfile;
private static TreatmentsInterface activeTreatments;
private static APSInterface activeAPS;
private static LoopPlugin activeLoop;
private static InsulinInterface activeInsulin;
private static SensitivityInterface activeSensitivity;
static public String nightscoutVersionName = "";
static public Integer nightscoutVersionCode = 0;
static public String nsClientVersionName = "";
static public Integer nsClientVersionCode = 0;
private static ArrayList<PluginBase> pluginList;
private static CommandQueue commandQueue = new CommandQueue();
@ -119,14 +89,15 @@ public class ConfigBuilderPlugin extends PluginBase {
private void setAlwaysEnabledPluginsEnabled() {
for (PluginBase plugin : pluginList) {
if (plugin.pluginDescription.alwaysEnabled) plugin.setPluginEnabled(plugin.getType(), true);
if (plugin.pluginDescription.alwaysEnabled)
plugin.setPluginEnabled(plugin.getType(), true);
}
storeSettings("setAlwaysEnabledPluginsEnabled");
}
public void storeSettings(String from) {
if (pluginList != null) {
if (Config.logPrefsChange)
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Storing settings from: " + from);
for (PluginBase p : pluginList) {
@ -149,16 +120,18 @@ public class ConfigBuilderPlugin extends PluginBase {
private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
SP.putBoolean(settingEnabled, p.isEnabled(type));
log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (storeVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
SP.putBoolean(settingVisible, p.isFragmentVisible());
log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible());
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Storing: " + settingVisible + ":" + p.isFragmentVisible());
}
}
private void loadSettings() {
if (Config.logPrefsChange)
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Loading stored settings");
for (PluginBase p : pluginList) {
PluginType type = p.getType();
@ -179,7 +152,8 @@ public class ConfigBuilderPlugin extends PluginBase {
else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
p.setPluginEnabled(type, true);
}
log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (loadVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
if (SP.contains(settingVisible))
@ -187,7 +161,8 @@ public class ConfigBuilderPlugin extends PluginBase {
else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
p.setFragmentVisible(type, true);
}
log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible());
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Loaded: " + settingVisible + ":" + p.isFragmentVisible());
}
}
@ -195,10 +170,11 @@ public class ConfigBuilderPlugin extends PluginBase {
private void upgradeSettings() {
if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return;
if (Config.logPrefsChange)
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Upgrading stored settings");
for (PluginBase p : pluginList) {
log.debug("Processing " + p.getName());
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Processing " + p.getName());
for (int type = 1; type < 11; type++) {
PluginType newType;
switch (type) {
@ -282,20 +258,21 @@ public class ConfigBuilderPlugin extends PluginBase {
}
void logPluginStatus() {
for (PluginBase p : pluginList) {
log.debug(p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
(p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
(p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
(p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
(p.isEnabled(PluginType.APS) ? " APS" : "") +
(p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
(p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
(p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
(p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
(p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
);
}
if (L.isEnabled(L.CONFIGBUILDER))
for (PluginBase p : pluginList) {
log.debug(p.getName() + ":" +
(p.isEnabled(PluginType.GENERAL) ? " GENERAL" : "") +
(p.isEnabled(PluginType.TREATMENT) ? " TREATMENT" : "") +
(p.isEnabled(PluginType.SENSITIVITY) ? " SENSITIVITY" : "") +
(p.isEnabled(PluginType.PROFILE) ? " PROFILE" : "") +
(p.isEnabled(PluginType.APS) ? " APS" : "") +
(p.isEnabled(PluginType.PUMP) ? " PUMP" : "") +
(p.isEnabled(PluginType.CONSTRAINTS) ? " CONSTRAINTS" : "") +
(p.isEnabled(PluginType.LOOP) ? " LOOP" : "") +
(p.isEnabled(PluginType.BGSOURCE) ? " BGSOURCE" : "") +
(p.isEnabled(PluginType.INSULIN) ? " INSULIN" : "")
);
}
}
private void verifySelectionInCategories() {
@ -337,9 +314,6 @@ public class ConfigBuilderPlugin extends PluginBase {
}
this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
// PluginType.LOOP
activeLoop = this.determineActivePlugin(PluginType.LOOP);
// PluginType.TREATMENT
activeTreatments = this.determineActivePlugin(PluginType.TREATMENT);
}
@ -395,7 +369,7 @@ public class ConfigBuilderPlugin extends PluginBase {
private void setFragmentVisiblities(String activePluginName, ArrayList<PluginBase> pluginsInCategory,
PluginType pluginType) {
if (Config.logConfigBuilder)
if (L.isEnabled(L.CONFIGBUILDER))
log.debug("Selected interface: " + activePluginName);
for (PluginBase p : pluginsInCategory) {
if (!p.getName().equals(activePluginName)) {
@ -421,247 +395,4 @@ public class ConfigBuilderPlugin extends PluginBase {
return found;
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return;
}
PumpInterface pump = getActivePump();
request.rateConstraint = new Constraint<>(request.rate);
request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value();
if (!pump.isInitialized()) {
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: cancelTempBasal()");
getCommandQueue().cancelTempBasal(false, callback);
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: setTempBasalAbsolute()");
getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
public void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
long lastBolusTime = activeTreatments.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
log.debug("SMB requested but still in 3 min interval");
if (callback != null) {
callback.result(new PumpEnactResult()
.comment(MainApp.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
PumpInterface pump = getActivePump();
if (!pump.isInitialized()) {
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (Config.logCongigBuilderActions)
log.debug("applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
if (Config.logCongigBuilderActions)
log.debug("applyAPSRequest: bolus()");
getCommandQueue().bolus(detailedBolusInfo, callback);
}
@Subscribe
public void onProfileSwitch(EventProfileSwitchChange ignored) {
getCommandQueue().setProfile(getProfile(), new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
MainApp.bus().post(new EventNewBasalProfile());
}
});
}
public String getProfileName() {
return getProfileName(System.currentTimeMillis());
}
public String getProfileName(boolean customized) {
return getProfileName(System.currentTimeMillis(), customized);
}
public String getProfileName(long time) {
return getProfileName(time, true);
}
public String getProfileName(long time, boolean customized) {
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profileSwitch.profileName;
}
}
}
return MainApp.gs(R.string.noprofileselected);
}
public boolean isProfileValid(String from) {
return getProfile() != null && getProfile().isValid(from);
}
@Nullable
public Profile getProfile() {
return getProfile(System.currentTimeMillis());
}
public String getProfileUnits() {
Profile profile = getProfile();
return profile != null ? profile.getUnits() : Constants.MGDL;
}
@Nullable
public Profile getProfile(long time) {
if (activeTreatments == null) {
log.debug("getProfile activeTreatments == null: returning null");
return null; //app not initialized
}
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return profileSwitch.getProfileObject();
} else if (activeProfile.getProfile() != null) {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profile;
}
}
if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("time", time)
.putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString())
);
}
log.debug("getProfile at the end: returning null");
return null;
}
public void disconnectPump(int durationInMinutes, Profile profile) {
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
if (getActivePump().getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
}
}
});
}
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
public void suspendLoop(int durationInMinutes) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
}

View file

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

View file

@ -0,0 +1,142 @@
package info.nightscout.androidaps.plugins.ConfigBuilder;
import android.content.Intent;
import android.support.annotation.Nullable;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.FabricPrivacy;
public class ProfileFunctions {
private static Logger log = LoggerFactory.getLogger(L.PROFILE);
private static ProfileFunctions profileFunctions = null;
public static ProfileFunctions getInstance() {
if (profileFunctions == null)
profileFunctions = new ProfileFunctions();
return profileFunctions;
}
static {
ProfileFunctions.getInstance(); // register to bus at start
}
ProfileFunctions() {
MainApp.bus().register(this);
}
@Subscribe
public void onProfileSwitch(EventProfileSwitchChange ignored) {
if (L.isEnabled(L.PROFILE))
log.debug("onProfileSwitch");
MainApp.getConfigBuilder().getCommandQueue().setProfile(getProfile(), new Callback() {
@Override
public void run() {
if (!result.success) {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment);
i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
MainApp.bus().post(new EventNewBasalProfile());
}
});
}
public String getProfileName() {
return getProfileName(System.currentTimeMillis());
}
public String getProfileName(boolean customized) {
return getProfileName(System.currentTimeMillis(), customized);
}
public String getProfileName(long time) {
return getProfileName(time, true);
}
public String getProfileName(long time, boolean customized) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface();
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profileSwitch.profileName;
}
}
}
return MainApp.gs(R.string.noprofileselected);
}
public boolean isProfileValid(String from) {
return getProfile() != null && getProfile().isValid(from);
}
@Nullable
public Profile getProfile() {
return getProfile(System.currentTimeMillis());
}
public String getProfileUnits() {
Profile profile = getProfile();
return profile != null ? profile.getUnits() : Constants.MGDL;
}
@Nullable
public Profile getProfile(long time) {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = MainApp.getConfigBuilder().getActiveProfileInterface();
//log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
return profileSwitch.getProfileObject();
} else if (activeProfile.getProfile() != null) {
Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
if (profile != null)
return profile;
}
}
if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
.putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
.putCustomAttribute("version", BuildConfig.VERSION)
.putCustomAttribute("time", time)
.putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString())
);
}
log.error("getProfile at the end: returning null");
return null;
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -5,6 +5,7 @@ import com.squareup.otto.Bus;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
@ -61,7 +62,7 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli
}
public double getUserDefinedDia() {
return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : MIN_DIA;
return ProfileFunctions.getInstance().getProfile() != null ? ProfileFunctions.getInstance().getProfile().getDia() : MIN_DIA;
}
public Iob iobCalcForTreatment(Treatment treatment, long time) {

View file

@ -12,6 +12,8 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
@ -26,7 +28,7 @@ import info.nightscout.utils.SP;
*/
public class AutosensData implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger("AUTOSENS");
private static Logger log = LoggerFactory.getLogger(L.AUTOSENS);
public void setChartTime(long chartTime) {
this.chartTime = chartTime;
@ -44,11 +46,12 @@ public class AutosensData implements DataPointWithLabelInterface {
remaining = t.carbs;
if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) {
double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME);
Profile profile = MainApp.getConfigBuilder().getProfile(t.date);
Profile profile = ProfileFunctions.getInstance().getProfile(t.date);
double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits());
double ic = profile.getIc(t.date);
min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic;
log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic);
if (L.isEnabled(L.AUTOSENS))
log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic);
} else {
min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact);
}
@ -107,7 +110,8 @@ public class AutosensData implements DataPointWithLabelInterface {
activeCarbsList.remove(i--);
if (c.remaining > 0)
cob -= c.remaining;
log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString());
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString());
}
}
}

View file

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

View file

@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.os.SystemClock;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
@ -16,7 +15,6 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -33,7 +31,9 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin;
@ -49,7 +49,7 @@ import static info.nightscout.utils.DateUtil.now;
*/
public class IobCobCalculatorPlugin extends PluginBase {
private Logger log = LoggerFactory.getLogger("AUTOSENS");
private Logger log = LoggerFactory.getLogger(L.AUTOSENS);
private static IobCobCalculatorPlugin plugin = null;
@ -112,13 +112,15 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.debug("Locking getBucketedData");
synchronized (dataLock) {
if (bucketed_data == null) {
log.debug("No bucketed data available");
if (L.isEnabled(L.AUTOSENS))
log.debug("No bucketed data available");
return null;
}
int index = indexNewerThan(fromTime);
if (index > -1) {
List<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;
}
}
@ -144,7 +146,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
void loadBgData(long now) {
long start = (long) (now - 60 * 60 * 1000L * (24 + dia));
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() {
@ -160,13 +163,15 @@ public class IobCobCalculatorPlugin extends PluginBase {
totalDiff += diff;
if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false);
return false;
if (L.isEnabled(L.AUTOSENS))
return false;
}
}
double intervals = totalDiff / (5 * 60 * 1000d);
double variability = Math.abs(intervals - Math.round(intervals));
boolean is5mindata = variability < 0.02;
log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata);
if (L.isEnabled(L.AUTOSENS))
log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata);
return is5mindata;
}
}
@ -293,11 +298,12 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.error("***** Average");
}
}
log.debug("Bucketed data created. Size: " + bucketed_data.size());
if (L.isEnabled(L.AUTOSENS))
log.debug("Bucketed data created. Size: " + bucketed_data.size());
}
public long calculateDetectionStart(long from, boolean limitDataToOldestAvailable) {
Profile profile = MainApp.getConfigBuilder().getProfile(from);
Profile profile = ProfileFunctions.getInstance().getProfile(from);
double dia = Constants.defaultDIA;
if (profile != null) dia = profile.getDia();
@ -306,7 +312,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
if (limitDataToOldestAvailable) {
getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia)));
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
getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia));
return getBGDataFrom;
@ -413,12 +420,14 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable
public AutosensData getLastAutosensDataSynchronized(String reason) {
if (thread != null && thread.isAlive()) {
log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason);
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA is waiting for calculation thread: " + reason);
try {
thread.join(5000);
} catch (InterruptedException ignored) {
}
log.debug("AUTOSENSDATA finished waiting for calculation thread: " + reason);
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA finished waiting for calculation thread: " + reason);
}
synchronized (dataLock) {
return getLastAutosensData(reason);
@ -456,7 +465,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Nullable
public AutosensData getLastAutosensData(String reason) {
if (autosensDataTable.size() < 1) {
log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")");
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA null: autosensDataTable empty (" + reason + ")");
return null;
}
AutosensData data;
@ -470,10 +480,12 @@ public class IobCobCalculatorPlugin extends PluginBase {
return null;
}
if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) {
log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time));
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time));
return null;
} else {
log.debug("AUTOSENSDATA (" + reason + ") " + data.toString());
if (L.isEnabled(L.AUTOSENS))
log.debug("AUTOSENSDATA (" + reason + ") " + data.toString());
return data;
}
}
@ -535,7 +547,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@SuppressWarnings("unused")
public void onEventAppInitialized(EventAppInitialized ev) {
if (this != getPlugin()) {
log.debug("Ignoring event for non default instance");
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
return;
}
runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev);
@ -545,7 +558,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@SuppressWarnings("unused")
public void onEventNewBG(EventNewBG ev) {
if (this != getPlugin()) {
log.debug("Ignoring event for non default instance");
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
return;
}
stopCalculation("onEventNewBG");
@ -555,16 +569,19 @@ public class IobCobCalculatorPlugin extends PluginBase {
public void stopCalculation(String from) {
if (thread != null && thread.getState() != Thread.State.TERMINATED) {
stopCalculationTrigger = true;
log.debug("Stopping calculation thread: " + from);
if (L.isEnabled(L.AUTOSENS))
log.debug("Stopping calculation thread: " + from);
while (thread.getState() != Thread.State.TERMINATED) {
SystemClock.sleep(100);
}
log.debug("Calculation thread stopped: " + from);
if (L.isEnabled(L.AUTOSENS))
log.debug("Calculation thread stopped: " + from);
}
}
public void runCalculation(String from, long 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 (SensitivityOref1Plugin.getPlugin().isEnabled(PluginType.SENSITIVITY))
thread = new IobCobOref1Thread(this, from, end, bgDataReload, limitDataToOldestAvailable, cause);
@ -577,12 +594,13 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe
public void onNewProfile(EventNewBasalProfile ev) {
if (this != getPlugin()) {
log.debug("Ignoring event for non default instance");
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
return;
}
if (MainApp.getConfigBuilder() == null)
return; // app still initializing
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null)
return; // app still initializing
dia = profile.getDia();
@ -591,7 +609,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
stopCalculation("onNewProfile");
synchronized (dataLock) {
log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
@ -601,7 +620,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe
public void onEventPreferenceChange(EventPreferenceChange ev) {
if (this != getPlugin()) {
log.debug("Ignoring event for non default instance");
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
return;
}
if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
@ -614,7 +634,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
) {
stopCalculation("onEventPreferenceChange");
synchronized (dataLock) {
log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
@ -625,12 +646,14 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe
public void onEventConfigBuilderChange(EventConfigBuilderChange ev) {
if (this != getPlugin()) {
log.debug("Ignoring event for non default instance");
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
return;
}
stopCalculation("onEventConfigBuilderChange");
synchronized (dataLock) {
log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
@ -641,7 +664,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Subscribe
public void onEventNewHistoryData(EventNewHistoryData ev) {
if (this != getPlugin()) {
log.debug("Ignoring event for non default instance");
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
return;
}
//log.debug("Locking onNewHistoryData");
@ -649,10 +673,11 @@ public class IobCobCalculatorPlugin extends PluginBase {
synchronized (dataLock) {
// clear up 5 min back for proper COB calculation
long time = ev.time - 5 * 60 * 1000L;
log.debug("Invalidating cached data to: " + new Date(time).toLocaleString());
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data to: " + new Date(time).toLocaleString());
for (int index = iobTable.size() - 1; index >= 0; index--) {
if (iobTable.keyAt(index) > time) {
if (Config.logAutosensData)
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
iobTable.removeAt(index);
} else {
@ -661,7 +686,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
for (int index = autosensDataTable.size() - 1; index >= 0; index--) {
if (autosensDataTable.keyAt(index) > time) {
if (Config.logAutosensData)
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString());
autosensDataTable.removeAt(index);
} else {
@ -670,7 +695,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
for (int index = basalDataTable.size() - 1; index >= 0; index--) {
if (basalDataTable.keyAt(index) > time) {
if (Config.logAutosensData)
if (L.isEnabled(L.AUTOSENS))
log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString());
basalDataTable.removeAt(index);
} else {
@ -684,7 +709,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
public void clearCache() {
synchronized (dataLock) {
log.debug("Clearing cached data.");
if (L.isEnabled(L.AUTOSENS))
log.debug("Clearing cached data.");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -21,50 +21,56 @@ import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.ToastUtils;
/**
* Created by mike on 05.08.2016.
*/
public class LoopPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(LoopPlugin.class);
private static Logger log = LoggerFactory.getLogger(L.APS);
public static final String CHANNEL_ID = "AndroidAPS-Openloop";
private static final String CHANNEL_ID = "AndroidAPS-Openloop";
long lastBgTriggeredRun = 0;
private long lastBgTriggeredRun = 0;
protected static LoopPlugin loopPlugin;
private static LoopPlugin loopPlugin;
@NonNull
public static LoopPlugin getPlugin() {
@ -135,15 +141,15 @@ public class LoopPlugin extends PluginBase {
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
return pump == null || pump.getPumpDescription().isTempBasalCapable;
}
/**
* This method is triggered once autosens calculation has completed, so the LoopPlugin
* has current data to work with. However, autosens calculation can be triggered by multiple
* sources and currently only a new BG should trigger a loop run. Hence we return early if
* the event causing the calculation is not EventNewBg.
*
* Callers of {@link info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin#runCalculation(String, long, boolean, Event)}
* are sources triggering a calculation which triggers this method upon completion.
* <p>
* Callers of {@link info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin#runCalculation(String, long, boolean, Event)}
* are sources triggering a calculation which triggers this method upon completion.
*/
@Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) {
@ -252,19 +258,20 @@ public class LoopPlugin extends PluginBase {
return isDisconnected;
}
public synchronized void invoke(String initiator, boolean allowNotification){
public synchronized void invoke(String initiator, boolean allowNotification) {
invoke(initiator, allowNotification, false);
}
public synchronized void invoke(String initiator, boolean allowNotification, boolean tempBasalFallback) {
try {
if (Config.logFunctionCalls)
if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator);
Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
if (!loopEnabled.value()) {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
log.debug(message);
if (L.isEnabled(L.APS))
log.debug(message);
MainApp.bus().post(new EventLoopSetLastRunGui(message));
return;
}
@ -274,10 +281,11 @@ public class LoopPlugin extends PluginBase {
if (!isEnabled(PluginType.LOOP))
return;
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (!MainApp.getConfigBuilder().isProfileValid("Loop")) {
log.debug(MainApp.gs(R.string.noprofileselected));
if (!ProfileFunctions.getInstance().isProfileValid("Loop")) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return;
}
@ -307,7 +315,8 @@ public class LoopPlugin extends PluginBase {
// safety check for multiple SMBs
long lastBolusTime = TreatmentsPlugin.getPlugin().getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
log.debug("SMB requsted but still in 3 min interval");
if (L.isEnabled(L.APS))
log.debug("SMB requsted but still in 3 min interval");
resultAfterConstraints.smb = 0;
}
@ -322,13 +331,15 @@ public class LoopPlugin extends PluginBase {
NSUpload.uploadDeviceStatus();
if (isSuspended()) {
log.debug(MainApp.gs(R.string.loopsuspended));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.loopsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return;
}
if (pump.isSuspended()) {
log.debug(MainApp.gs(R.string.pumpsuspended));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.pumpsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return;
}
@ -347,13 +358,13 @@ public class LoopPlugin extends PluginBase {
lastRun.smbSetByPump = waiting;
MainApp.bus().post(new EventLoopUpdateGui());
FabricPrivacy.getInstance().logCustom(new CustomEvent("APSRequest"));
MainApp.getConfigBuilder().applyTBRRequest(resultAfterConstraints, profile, new Callback() {
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
public void run() {
if (result.enacted || result.success) {
lastRun.tbrSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun;
MainApp.getConfigBuilder().applySMBRequest(resultAfterConstraints, new Callback() {
applySMBRequest(resultAfterConstraints, new Callback() {
@Override
public void run() {
//Callback is only called if a bolus was acutally requested
@ -425,7 +436,7 @@ public class LoopPlugin extends PluginBase {
MainApp.bus().post(new EventLoopUpdateGui());
} finally {
if (Config.logFunctionCalls)
if (L.isEnabled(L.APS))
log.debug("invoke end");
}
}
@ -453,4 +464,168 @@ public class LoopPlugin extends PluginBase {
FabricPrivacy.getInstance().logCustom(new CustomEvent("AcceptTemp"));
}
/**
* expect absolute request and allow both absolute and percent response based on pump capabilities
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return;
}
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
request.rateConstraint = new Constraint<>(request.rate);
request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value();
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: " + request.toString());
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = activeTreatments.getTempBasalFromHistory(now);
if ((request.rate == 0 && request.duration == 0) || Math.abs(request.rate - pump.getBaseBasalRate()) < pump.getPumpDescription().basalStep) {
if (activeTemp != null) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: cancelTempBasal()");
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(false, callback);
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(request.rate).duration(0)
.enacted(false).success(true).comment(MainApp.gs(R.string.basal_set_correctly))).run();
}
}
} else if (activeTemp != null
&& activeTemp.getPlannedRemainingMinutes() > 5
&& request.duration - activeTemp.getPlannedRemainingMinutes() < 30
&& Math.abs(request.rate - activeTemp.tempBasalConvertedToAbsolute(now, profile)) < pump.getPumpDescription().basalStep) {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: Temp basal set correctly");
if (callback != null) {
callback.result(new PumpEnactResult().absolute(activeTemp.tempBasalConvertedToAbsolute(now, profile))
.enacted(false).success(true).duration(activeTemp.getPlannedRemainingMinutes())
.comment(MainApp.gs(R.string.let_temp_basal_run))).run();
}
} else {
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: setTempBasalAbsolute()");
MainApp.getConfigBuilder().getCommandQueue().tempBasalAbsolute(request.rate, request.duration, false, profile, callback);
}
}
public void applySMBRequest(APSResult request, Callback callback) {
if (!request.bolusRequested) {
return;
}
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
long lastBolusTime = activeTreatments.getLastBolusTime();
if (lastBolusTime != 0 && lastBolusTime + 3 * 60 * 1000 > System.currentTimeMillis()) {
if (L.isEnabled(L.APS))
log.debug("SMB requested but still in 3 min interval");
if (callback != null) {
callback.result(new PumpEnactResult()
.comment(MainApp.gs(R.string.smb_frequency_exceeded))
.enacted(false).success(false)).run();
}
return;
}
if (!pump.isInitialized()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
}
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
}
return;
}
if (L.isEnabled(L.APS))
log.debug("applySMBRequest: " + request.toString());
// deliver SMB
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.lastKnownBolusTime = activeTreatments.getLastBolusTime();
detailedBolusInfo.eventType = CareportalEvent.CORRECTIONBOLUS;
detailedBolusInfo.insulin = request.smb;
detailedBolusInfo.isSMB = true;
detailedBolusInfo.source = Source.USER;
detailedBolusInfo.deliverAt = request.deliverAt;
if (L.isEnabled(L.APS))
log.debug("applyAPSRequest: bolus()");
MainApp.getConfigBuilder().getCommandQueue().bolus(detailedBolusInfo, callback);
}
public void disconnectPump(int durationInMinutes, Profile profile) {
PumpInterface pump = MainApp.getConfigBuilder().getActivePump();
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
MainApp.getConfigBuilder().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
MainApp.getConfigBuilder().getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
}
}
});
}
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
public void suspendLoop(int durationInMinutes) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000);
MainApp.getConfigBuilder().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (!result.success) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
}
}
});
NSUpload.uploadOpenAPSOffline(durationInMinutes);
}
}

View file

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

View file

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

View file

@ -1,4 +1,4 @@
package info.nightscout.utils;
package info.nightscout.androidaps.plugins.NSClientInternal;
import android.content.Context;
import android.content.Intent;
@ -23,7 +23,9 @@ import java.util.Locale;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
@ -37,13 +39,16 @@ import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.DeviceStatus;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.data.DbLogger;
import info.nightscout.utils.BatteryLevel;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP;
/**
* Created by mike on 26.05.2017.
*/
public class NSUpload {
private static Logger log = LoggerFactory.getLogger(NSUpload.class);
private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) {
try {
@ -79,7 +84,7 @@ public class NSUpload {
if (useAbsolute) {
TemporaryBasal t = temporaryBasal.clone();
t.isAbsolute = true;
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile != null) {
t.absoluteRate = profile.getBasal(temporaryBasal.date) * temporaryBasal.percentRate / 100d;
uploadTempBasalStartAbsolute(t, null);
@ -191,8 +196,8 @@ public class NSUpload {
}
public static void uploadDeviceStatus() {
Profile profile = MainApp.getConfigBuilder().getProfile();
String profileName = MainApp.getConfigBuilder().getProfileName();
Profile profile = ProfileFunctions.getInstance().getProfile();
String profileName = ProfileFunctions.getInstance().getProfileName();
if (profile == null || profileName == null) {
log.error("Profile is null. Skipping upload");
@ -232,7 +237,8 @@ public class NSUpload {
deviceStatus.enacted.put("requested", requested);
}
} else {
log.debug("OpenAPS data too old to upload");
if (L.isEnabled(L.NSCLIENT))
log.debug("OpenAPS data too old to upload");
}
deviceStatus.device = "openaps://" + Build.MANUFACTURER + " " + Build.MODEL;
JSONObject pumpstatus = ConfigBuilderPlugin.getActivePump().getJSONStatus(profile, profileName);
@ -298,7 +304,7 @@ public class NSUpload {
public static void uploadTempTarget(TempTarget tempTarget) {
try {
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) {
log.error("Profile is null. Skipping upload");
@ -490,7 +496,7 @@ public class NSUpload {
try {
data.put("eventType", "Note");
data.put("created_at", DateUtil.toISOString(new Date()));
data.put("notes", MainApp.gs(R.string.androidaps_start)+" - "+ Build.MANUFACTURER + " "+ Build.MODEL);
data.put("notes", MainApp.gs(R.string.androidaps_start) + " - " + Build.MANUFACTURER + " " + Build.MODEL);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@ -500,7 +506,7 @@ public class NSUpload {
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
DbLogger.dbAdd(intent, data.toString());
}
}
}
public static void uploadEvent(String careportalEvent, long time, @Nullable String notes) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -2,45 +2,20 @@ package info.nightscout.androidaps.plugins.NSClientInternal.broadcasts;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP;
public class BroadcastDeviceStatus {
private static Logger log = LoggerFactory.getLogger(BroadcastDeviceStatus.class);
public static void handleNewDeviceStatus(JSONObject status, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("devicestatus", status.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
bundle = new Bundle();
bundle.putString("devicestatus", status.toString());
bundle.putBoolean("delta", isDelta);
intent = new Intent(Intents.ACTION_NEW_DEVICESTATUS);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
}
}
public static void handleNewDeviceStatus(JSONArray statuses, Context context, boolean isDelta) {
List<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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSTreatment;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP;
/**
* Created by mike on 20.02.2016.
*/
public class BroadcastFood {
private static Logger log = LoggerFactory.getLogger(BroadcastFood.class);
public static void handleNewFood(JSONArray foods, Context context, boolean isDelta) {
List<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.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP;
/**
* Created by mike on 26.06.2016.
*/
public class BroadcastMbgs {
private static Logger log = LoggerFactory.getLogger(BroadcastMbgs.class);
public static void handleNewMbg(JSONArray mbgs, Context context, boolean isDelta) {
Bundle bundle = new Bundle();

View file

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

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.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP;
/**
* Created by mike on 22.02.2016.
*/
public class BroadcastSgvs {
private static Logger log = LoggerFactory.getLogger(BroadcastSgvs.class);
public static void handleNewSgv(JSONObject sgv, Context context, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("sgv", sgv.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if(SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
bundle = new Bundle();
bundle.putString("sgv", sgv.toString());
bundle.putBoolean("delta", isDelta);
intent = new Intent(Intents.ACTION_NEW_SGV);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
context.sendBroadcast(intent);
}
}
public static void handleNewSgv(JSONArray sgvs, Context context, boolean isDelta) {
List<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.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
import info.nightscout.utils.SP;
@ -23,7 +21,7 @@ import info.nightscout.utils.SP;
* Created by mike on 24.02.2016.
*/
public class BroadcastStatus {
private static Logger log = LoggerFactory.getLogger(BroadcastStatus.class);
private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static void handleNewStatus(NSSettingsStatus status, Context context, boolean isDelta) {
LocalBroadcastManager.getInstance(MainApp.instance())

View file

@ -15,14 +15,15 @@ import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.Intents;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.SP;
/**
* Created by mike on 20.02.2016.
*/
public class BroadcastTreatment {
private static Logger log = LoggerFactory.getLogger(BroadcastTreatment.class);
private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
public static void handleNewTreatment(JSONObject treatment, boolean isDelta, boolean isLocalBypass) {
@ -73,28 +74,6 @@ public class BroadcastTreatment {
}
}
public void handleChangedTreatment(JSONObject treatment, boolean isDelta) {
Bundle bundle = new Bundle();
bundle.putString("treatment", treatment.toString());
bundle.putBoolean("delta", isDelta);
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(MainApp.instance()).sendBroadcast(intent);
if (SP.getBoolean(R.string.key_nsclient_localbroadcasts, true)) {
bundle = new Bundle();
bundle.putString("treatment", treatment.toString());
bundle.putBoolean("delta", isDelta);
intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
MainApp.instance().getApplicationContext().sendBroadcast(intent);
}
}
public static void handleChangedTreatment(JSONArray treatments, boolean isDelta) {
List<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) {
Bundle bundle = new Bundle();

View file

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

View file

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

View file

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

View file

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

View file

@ -1,8 +1,11 @@
package info.nightscout.androidaps.plugins.NSClientInternal.data;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@ -13,7 +16,10 @@ import java.util.Iterator;
import java.util.Map;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.logging.BundleLogger;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.Round;
import info.nightscout.utils.SP;
@ -73,7 +79,7 @@ import info.nightscout.utils.SP;
}
*/
public class NSDeviceStatus {
private static Logger log = LoggerFactory.getLogger(NSDeviceStatus.class);
private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
private static NSDeviceStatus instance = null;
@ -88,6 +94,41 @@ public class NSDeviceStatus {
public NSDeviceStatus() {
}
public void handleNewData(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
if (L.isEnabled(L.NSCLIENT))
log.debug("Got NS devicestatus: " + BundleLogger.log(bundle));
try {
if (bundle.containsKey("devicestatus")) {
JSONObject devicestatusJson = new JSONObject(bundle.getString("devicestatus"));
setData(devicestatusJson);
if (devicestatusJson.has("pump")) {
// Objectives 0
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
}
}
if (bundle.containsKey("devicestatuses")) {
String devicestatusesstring = bundle.getString("devicestatuses");
JSONArray jsonArray = new JSONArray(devicestatusesstring);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject devicestatusJson = jsonArray.getJSONObject(i);
setData(devicestatusJson);
if (devicestatusJson.has("pump")) {
// Objectives 0
ObjectivesPlugin.pumpStatusIsAvailableInNS = true;
ObjectivesPlugin.saveProgress();
}
}
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
public NSDeviceStatus setData(JSONObject obj) {
this.data = obj;
updatePumpData(obj);

View file

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

View file

@ -1,5 +1,8 @@
package info.nightscout.androidaps.plugins.NSClientInternal.data;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import org.json.JSONException;
@ -10,6 +13,16 @@ import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Objects;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.logging.BundleLogger;
/*
{
"status": "ok",
@ -101,7 +114,7 @@ import java.util.Objects;
}
*/
public class NSSettingsStatus {
private static Logger log = LoggerFactory.getLogger(NSSettingsStatus.class);
private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
private static NSSettingsStatus instance = null;
@ -111,6 +124,8 @@ public class NSSettingsStatus {
return instance;
}
public String nightscoutVersionName = "";
private JSONObject data = null;
public NSSettingsStatus() {
@ -121,6 +136,59 @@ public class NSSettingsStatus {
return this;
}
public void handleNewData(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
if (L.isEnabled(L.NSCLIENT))
log.debug("Got NS status: " + BundleLogger.log(bundle));
if (bundle.containsKey("nsclientversioncode")) {
Integer nightscoutVersionCode = bundle.getInt("nightscoutversioncode");
nightscoutVersionName = bundle.getString("nightscoutversionname");
Integer nsClientVersionCode = bundle.getInt("nsclientversioncode");
String nsClientVersionName = bundle.getString("nsclientversionname");
if (L.isEnabled(L.NSCLIENT))
log.debug("Got versions: NSClient: " + nsClientVersionName + " Nightscout: " + nightscoutVersionName);
try {
if (nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
}
} catch (PackageManager.NameNotFoundException e) {
log.error("Unhandled exception", e);
}
if (nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
} else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS));
}
} else {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
}
if (bundle.containsKey("status")) {
try {
JSONObject statusJson = new JSONObject(bundle.getString("status"));
setData(statusJson);
if (L.isEnabled(L.NSCLIENT))
log.debug("Received status: " + statusJson.toString());
Double targetHigh = getThreshold("bgTargetTop");
Double targetlow = getThreshold("bgTargetBottom");
if (targetHigh != null)
OverviewPlugin.bgTargetHigh = targetHigh;
if (targetlow != null)
OverviewPlugin.bgTargetLow = targetlow;
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
}
public String getName() {
return getStringOrNull("name");
}
@ -134,7 +202,7 @@ public class NSSettingsStatus {
}
public Date getServerTime() {
return getDateOrNull("versionNum");
return getDateOrNull("serverTime");
}
public boolean getApiEnabled() {
@ -202,13 +270,11 @@ public class NSSettingsStatus {
if (settingsO.has("thresholds")) {
JSONObject tObject = settingsO.getJSONObject("thresholds");
if (tObject.has(what)) {
Double result = tObject.getDouble(what);
return result;
return tObject.getDouble(what);
}
}
if (settingsO.has("alarmTimeagoWarnMins") && Objects.equals(what, "alarmTimeagoWarnMins")) {
Double result = settingsO.getDouble(what);
return result;
return settingsO.getDouble(what);
}
}
} catch (JSONException e) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -4,10 +4,8 @@ import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Date;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
@ -21,7 +19,9 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
@ -39,7 +39,7 @@ import static info.nightscout.utils.HardLimits.verifyHardLimits;
* Created by mike on 05.08.2016.
*/
public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
private static Logger log = LoggerFactory.getLogger(OpenAPSMAPlugin.class);
private static Logger log = LoggerFactory.getLogger(L.APS);
private static OpenAPSMAPlugin openAPSMAPlugin;
@ -90,37 +90,33 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
@Override
public void invoke(String initiator, boolean tempBasalFallback) {
log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
if (L.isEnabled(L.APS))
log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null;
DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null;
try {
determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
} catch (IOException e) {
log.error(e.getMessage(), e);
return;
}
determineBasalAdapterMAJS = new DetermineBasalAdapterMAJS(new ScriptReader(MainApp.instance().getBaseContext()));
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
Profile profile = MainApp.getConfigBuilder().getProfile();
Profile profile = ProfileFunctions.getInstance().getProfile();
PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (Config.logAPSResult)
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (Config.logAPSResult)
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (Config.logAPSResult)
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return;
}
@ -147,7 +143,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value();
Profiler.log(log, "MA data gathering", start);
if (L.isEnabled(L.APS))
Profiler.log(log, "MA data gathering", start);
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
@ -177,7 +174,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
Profiler.log(log, "MA calculation", start);
if (L.isEnabled(L.APS))
Profiler.log(log, "MA calculation", start);
long now = System.currentTimeMillis();

View file

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

View file

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

View file

@ -5,11 +5,12 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult;
import info.nightscout.utils.DateUtil;
public class DetermineBasalResultSMB extends APSResult {
private static final Logger log = LoggerFactory.getLogger(DetermineBasalResultSMB.class);
private static final Logger log = LoggerFactory.getLogger(L.APS);
private double eventualBG;
private double snoozeBG;

View file

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

View file

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

View file

@ -23,6 +23,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SafeParse;
@ -63,7 +64,7 @@ public class CalibrationDialog extends DialogFragment implements View.OnClickLis
view.findViewById(R.id.ok).setOnClickListener(this);
view.findViewById(R.id.cancel).setOnClickListener(this);
String units = MainApp.getConfigBuilder().getProfileUnits();
String units = ProfileFunctions.getInstance().getProfileUnits();
Double bg = Profile.fromMgdlToUnits(GlucoseStatus.getGlucoseStatusData() != null ? GlucoseStatus.getGlucoseStatusData().glucose : 0d, units);
bgNumber = (NumberPicker) view.findViewById(R.id.overview_calibration_bg);

View file

@ -15,7 +15,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.Services.AlarmSoundService;
import info.nightscout.androidaps.services.AlarmSoundService;
public class ErrorDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(ErrorDialog.class);

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