Merge pull request #17 from MilosKozak/startupwizard

Startupwizard
This commit is contained in:
Roumen Georgiev 2018-05-08 09:11:29 +03:00 committed by GitHub
commit 7832411d9c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
214 changed files with 4056 additions and 2463 deletions

View file

@ -63,7 +63,7 @@ android {
targetSdkVersion 25 targetSdkVersion 25
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "1.60d-dev" version "1.60e-dev"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", generateGitBuild() buildConfigField "String", "BUILDVERSION", generateGitBuild()
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
@ -172,7 +172,6 @@ configurations {
} }
dependencies { dependencies {
implementation 'com.android.support:support-v4:27.1.1'
wearApp project(':wear') wearApp project(':wear')
implementation fileTree(include: ['*.jar'], dir: 'libs') implementation fileTree(include: ['*.jar'], dir: 'libs')
@ -210,7 +209,7 @@ dependencies {
implementation("com.google.android:flexbox:0.3.0") { implementation("com.google.android:flexbox:0.3.0") {
exclude group: "com.android.support" exclude group: "com.android.support"
} }
implementation("io.socket:socket.io-client:0.8.3") { implementation("io.socket:socket.io-client:1.0.0") {
// excluding org.json which is provided by Android // excluding org.json which is provided by Android
exclude group: "org.json", module: "json" exclude group: "org.json", module: "json"
} }

Binary file not shown.

View file

@ -15,9 +15,11 @@
<uses-permission android:name="android.permission.SEND_MMS" /> <uses-permission android:name="android.permission.SEND_MMS" />
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" /> <uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="sugar.free.sightremote.HISTORY_BROADCASTS" />
<uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" /> <uses-permission-sdk-23 android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
@ -114,6 +116,14 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- Network change local receiver -->
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
<!-- Service processing incomming data --> <!-- Service processing incomming data -->
<service <service
android:name=".Services.DataService" android:name=".Services.DataService"
@ -160,8 +170,7 @@
<activity <activity
android:name=".startupwizard.SetupWizardActivity" android:name=".startupwizard.SetupWizardActivity"
android:configChanges="orientation|keyboardHidden|screenSize" android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_setup_wizard" android:label="@string/title_activity_setup_wizard"></activity>
android:theme="@style/FullscreenTheme"></activity>
</application> </application>
</manifest> </manifest>

View file

@ -23,8 +23,6 @@ public class Config {
public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER; public static final boolean SMSCOMMUNICATORENABLED = !BuildConfig.NSCLIENTOLNY && !BuildConfig.G5UPLOADER;
public static final boolean displayDeviationSlope = false;
public static final boolean detailedLog = true; public static final boolean detailedLog = true;
public static final boolean logFunctionCalls = true; public static final boolean logFunctionCalls = true;
public static final boolean logIncommingData = true; public static final boolean logIncommingData = true;

View file

@ -59,6 +59,7 @@ public class Constants {
//Autosens //Autosens
public static final double DEVIATION_TO_BE_EQUAL = 2.0; public static final double DEVIATION_TO_BE_EQUAL = 2.0;
public static final double DEFAULT_MAX_ABSORPTION_TIME = 6.0;
// Pump // Pump
public static final int PUMP_MAX_CONNECTION_TIME_IN_SECONDS = 120 - 1; public static final int PUMP_MAX_CONNECTION_TIME_IN_SECONDS = 120 - 1;

View file

@ -46,7 +46,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
ImageButton chartButton; ImageButton chartButton;
boolean showBasal = true; boolean showBasal = true;
boolean showIob, showCob, showDev, showRat; boolean showIob, showCob, showDev, showRat, showDevslope;
@BindView(R.id.historybrowse_date) @BindView(R.id.historybrowse_date)
@ -267,6 +267,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
boolean useCobForScale = false; boolean useCobForScale = false;
boolean useDevForScale = false; boolean useDevForScale = false;
boolean useRatioForScale = false; boolean useRatioForScale = false;
boolean useDevSlopeForScale = false;
if (showIob) { if (showIob) {
useIobForScale = true; useIobForScale = true;
@ -276,6 +277,8 @@ public class HistoryBrowseActivity extends AppCompatActivity {
useDevForScale = true; useDevForScale = true;
} else if (showRat) { } else if (showRat) {
useRatioForScale = true; useRatioForScale = true;
} else if (showDevslope) {
useDevSlopeForScale = true;
} }
if (showIob) if (showIob)
@ -286,6 +289,8 @@ public class HistoryBrowseActivity extends AppCompatActivity {
secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d); secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d);
if (showRat) if (showRat)
secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d); secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d);
if (showDevslope)
secondGraphData.addDeviationSlope(fromTime, toTime, useDevSlopeForScale, 1d);
// **** NOW line **** // **** NOW line ****
// set manual x bounds to have nice steps // set manual x bounds to have nice steps
@ -293,7 +298,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
secondGraphData.addNowLine(pointer); secondGraphData.addNowLine(pointer);
// do GUI update // do GUI update
if (showIob || showCob || showDev || showRat) { if (showIob || showCob || showDev || showRat || showDevslope) {
iobGraph.setVisibility(View.VISIBLE); iobGraph.setVisibility(View.VISIBLE);
} else { } else {
iobGraph.setVisibility(View.GONE); iobGraph.setVisibility(View.GONE);
@ -354,23 +359,31 @@ public class HistoryBrowseActivity extends AppCompatActivity {
item.setCheckable(true); item.setCheckable(true);
item.setChecked(showRat); item.setChecked(showRat);
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showDevslope);
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override @Override
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) { if (item.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) {
showBasal = !item.isChecked(); showBasal = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) { } else if (item.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) {
showIob = !item.isChecked(); showIob = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) { } else if (item.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) {
showCob = !item.isChecked(); showCob = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) { } else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) {
showDev = !item.isChecked(); showDev = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) { } else if (item.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) {
showRat = !item.isChecked(); showRat = !item.isChecked();
} else if (item.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) {
showDevslope = !item.isChecked();
} }
updateGUI("onGraphCheckboxesCheckedChanged"); updateGUI("onGraphCheckboxesCheckedChanged");
return true; return true;

View file

@ -248,7 +248,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
if (!pm.isIgnoringBatteryOptimizations(packageName)) { if (!pm.isIgnoringBatteryOptimizations(packageName)) {
log.debug("Requesting ignore battery optimization"); log.debug("Requesting ignore battery optimization");
OKDialog.show(this, getString(R.string.pleaseallowpermission), String.format(getString(R.string.needwhitelisting), getString(R.string.app_name)), new Runnable() { OKDialog.show(this, MainApp.gs(R.string.pleaseallowpermission), String.format(MainApp.gs(R.string.needwhitelisting), MainApp.gs(R.string.app_name)), new Runnable() {
@Override @Override
public void run() { public void run() {
@ -261,7 +261,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
startActivity(intent); startActivity(intent);
} catch (ActivityNotFoundException e) { } catch (ActivityNotFoundException e) {
final String msg = getString(R.string.batteryoptimalizationerror); final String msg = MainApp.gs(R.string.batteryoptimalizationerror);
ToastUtils.showToastInUiThread(getApplicationContext(), msg); ToastUtils.showToastInUiThread(getApplicationContext(), msg);
log.error(msg); log.error(msg);
} }
@ -403,21 +403,21 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
break; break;
case R.id.nav_about: case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle(getString(R.string.app_name) + " " + BuildConfig.VERSION); builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION);
if (Config.NSCLIENT || Config.G5UPLOADER) if (Config.NSCLIENT || Config.G5UPLOADER)
builder.setIcon(R.mipmap.yellowowl); builder.setIcon(R.mipmap.yellowowl);
else else
builder.setIcon(R.mipmap.blueowl); builder.setIcon(R.mipmap.blueowl);
String message = "Build: " + BuildConfig.BUILDVERSION + "\n"; String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n"; message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += getString(R.string.configbuilder_nightscoutversion_label) + " " + ConfigBuilderPlugin.nightscoutVersionName; message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + ConfigBuilderPlugin.nightscoutVersionName;
if (MainApp.engineeringMode) if (MainApp.engineeringMode)
message += "\n" + MainApp.gs(R.string.engineering_mode_enabled); message += "\n" + MainApp.gs(R.string.engineering_mode_enabled);
message += getString(R.string.about_link_urls); message += MainApp.gs(R.string.about_link_urls);
final SpannableString messageSpanned = new SpannableString(message); final SpannableString messageSpanned = new SpannableString(message);
Linkify.addLinks(messageSpanned, Linkify.WEB_URLS); Linkify.addLinks(messageSpanned, Linkify.WEB_URLS);
builder.setMessage(messageSpanned); builder.setMessage(messageSpanned);
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null); builder.setPositiveButton(MainApp.gs(R.string.ok), null);
AlertDialog alertDialog = builder.create(); AlertDialog alertDialog = builder.create();
alertDialog.show(); alertDialog.show();
((TextView)alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView)alertDialog.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());

View file

@ -155,8 +155,7 @@ public class MainApp extends Application {
pluginsList.add(CareportalPlugin.getPlugin()); pluginsList.add(CareportalPlugin.getPlugin());
if (Config.HWPUMPS && engineeringMode) if (Config.HWPUMPS && engineeringMode)
pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here
if (Config.HWPUMPS && engineeringMode) if (Config.HWPUMPS) pluginsList.add(ComboPlugin.getPlugin());
pluginsList.add(ComboPlugin.getPlugin()); // <-- Enable Combo plugin here
if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin()); if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin()); pluginsList.add(VirtualPumpPlugin.getPlugin());
if (Config.APS) pluginsList.add(LoopPlugin.getPlugin()); if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
@ -246,12 +245,27 @@ public class MainApp extends Application {
} }
} }
public void stopKeepAliveService() { public void stopKeepAliveService() {
if (keepAliveReceiver != null) if (keepAliveReceiver != null)
KeepAliveReceiver.cancelAlarm(this); KeepAliveReceiver.cancelAlarm(this);
} }
public static void subscribe(Object subscriber) {
try {
bus().register(subscriber);
} catch (IllegalArgumentException e) {
// already registered
}
}
public static void unsubscribe(Object subscriber) {
try {
bus().unregister(subscriber);
} catch (IllegalArgumentException e) {
// already unregistered
}
}
public static Bus bus() { public static Bus bus() {
return sBus; return sBus;
} }
@ -372,6 +386,10 @@ public class MainApp extends Application {
return engineeringMode || !devBranch; return engineeringMode || !devBranch;
} }
public static boolean isDev() {
return devBranch;
}
public String getLogDirectory() { public String getLogDirectory() {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
return lc.getProperty("EXT_FILES_DIR"); return lc.getProperty("EXT_FILES_DIR");

View file

@ -23,10 +23,12 @@ import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.SensitivityOref0.SensitivityOref0Plugin;
@ -67,7 +69,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
MainApp.bus().post(new EventRefreshGui()); MainApp.bus().post(new EventRefreshGui());
} }
if (key.equals(MainApp.gs(R.string.key_openapsama_useautosens)) && SP.getBoolean(R.string.key_openapsama_useautosens, false)) { if (key.equals(MainApp.gs(R.string.key_openapsama_useautosens)) && SP.getBoolean(R.string.key_openapsama_useautosens, false)) {
OKDialog.show(this, MainApp.sResources.getString(R.string.configbuilder_sensitivity), MainApp.sResources.getString(R.string.sensitivity_warning), null); OKDialog.show(this, MainApp.gs(R.string.configbuilder_sensitivity), MainApp.gs(R.string.sensitivity_warning), null);
} }
updatePrefSummary(myPreferenceFragment.getPreference(key)); updatePrefSummary(myPreferenceFragment.getPreference(key));
} }
@ -81,13 +83,13 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
EditTextPreference editTextPref = (EditTextPreference) pref; EditTextPreference editTextPref = (EditTextPreference) pref;
if (pref.getKey().contains("password") || pref.getKey().contains("secret")) { if (pref.getKey().contains("password") || pref.getKey().contains("secret")) {
pref.setSummary("******"); pref.setSummary("******");
} else if (pref.getKey().equals(MainApp.sResources.getString(R.string.key_danars_name))) { } else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) {
pref.setSummary(SP.getString(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 && !editTextPref.getText().equals("")) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage()); ((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText()); pref.setSummary(editTextPref.getText());
} else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) { } else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) {
pref.setSummary(MainApp.sResources.getString(R.string.smscommunicator_allowednumbers_summary)); pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary));
} }
} }
} }
@ -127,9 +129,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
if (id != -1) { if (id != -1) {
addPreferencesFromResource(id); addPreferencesFromResource(id);
addPreferencesFromResource(R.xml.pref_advanced);
} else { } else {
addPreferencesFromResource(R.xml.pref_overview);
if (!Config.NSCLIENT && !Config.G5UPLOADER) { if (!Config.NSCLIENT && !Config.G5UPLOADER) {
addPreferencesFromResource(R.xml.pref_password); addPreferencesFromResource(R.xml.pref_password);
@ -137,9 +137,8 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResource(R.xml.pref_age); addPreferencesFromResource(R.xml.pref_age);
addPreferencesFromResource(R.xml.pref_language); addPreferencesFromResource(R.xml.pref_language);
if (!Config.NSCLIENT && !Config.G5UPLOADER) { addPreferencesFromResource(R.xml.pref_overview);
addPreferencesFromResource(R.xml.pref_quickwizard);
}
addPreferencesFromResourceIfEnabled(SourceDexcomG5Plugin.getPlugin(), PluginType.BGSOURCE); addPreferencesFromResourceIfEnabled(SourceDexcomG5Plugin.getPlugin(), PluginType.BGSOURCE);
addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginType.CONSTRAINTS); addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginType.CONSTRAINTS);
@ -159,6 +158,8 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(InsightPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP);
if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE) if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE) || DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE)
@ -180,7 +181,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
if (!Config.NSCLIENT && !Config.G5UPLOADER) { if (!Config.NSCLIENT && !Config.G5UPLOADER) {
addPreferencesFromResource(R.xml.pref_others); addPreferencesFromResource(R.xml.pref_others);
} }
addPreferencesFromResource(R.xml.pref_advanced); addPreferencesFromResource(R.xml.pref_datachoices);
addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(WearPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL);

View file

@ -130,7 +130,7 @@ public class DataService extends IntentService {
handleNewDataFromDexcomG5(intent); handleNewDataFromDexcomG5(intent);
} }
} else if (Intents.ACTION_NEW_SGV.equals(action)) { } else if (Intents.ACTION_NEW_SGV.equals(action)) {
if (nsClientEnabled || SP.getBoolean(R.string.ns_autobackfill, true)) if (nsClientEnabled || SP.getBoolean(R.string.key_ns_autobackfill, true))
handleNewDataFromNSClient(intent); handleNewDataFromNSClient(intent);
// Objectives 0 // Objectives 0
ObjectivesPlugin.bgIsAvailableInNS = true; ObjectivesPlugin.bgIsAvailableInNS = true;
@ -304,7 +304,7 @@ public class DataService extends IntentService {
log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName); log.debug("Got versions: NSClient: " + ConfigBuilderPlugin.nsClientVersionName + " Nightscout: " + ConfigBuilderPlugin.nightscoutVersionName);
try { try {
if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) { if (ConfigBuilderPlugin.nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.sResources.getString(R.string.unsupportedclientver), Notification.URGENT); Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT)); MainApp.bus().post(new EventDismissNotification(Notification.OLD_NSCLIENT));
@ -313,13 +313,13 @@ public class DataService extends IntentService {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) { if (ConfigBuilderPlugin.nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.sResources.getString(R.string.unsupportednsversion), Notification.NORMAL); Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS)); MainApp.bus().post(new EventDismissNotification(Notification.OLD_NS));
} }
} else { } else {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.sResources.getString(R.string.unsupportedclientver), Notification.URGENT); Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} }
if (bundles.containsKey("status")) { if (bundles.containsKey("status")) {

View file

@ -141,27 +141,27 @@ public class TDDStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
TextView label_date = new TextView(this); TextView label_date = new TextView(this);
label_date.setText(getString(R.string.danar_stats_date)); label_date.setText(MainApp.gs(R.string.danar_stats_date));
label_date.setTextColor(Color.WHITE); label_date.setTextColor(Color.WHITE);
tr_head.addView(label_date); tr_head.addView(label_date);
TextView label_basalrate = new TextView(this); TextView label_basalrate = new TextView(this);
label_basalrate.setText(getString(R.string.danar_stats_basalrate)); label_basalrate.setText(MainApp.gs(R.string.danar_stats_basalrate));
label_basalrate.setTextColor(Color.WHITE); label_basalrate.setTextColor(Color.WHITE);
tr_head.addView(label_basalrate); tr_head.addView(label_basalrate);
TextView label_bolus = new TextView(this); TextView label_bolus = new TextView(this);
label_bolus.setText(getString(R.string.danar_stats_bolus)); label_bolus.setText(MainApp.gs(R.string.danar_stats_bolus));
label_bolus.setTextColor(Color.WHITE); label_bolus.setTextColor(Color.WHITE);
tr_head.addView(label_bolus); tr_head.addView(label_bolus);
TextView label_tdd = new TextView(this); TextView label_tdd = new TextView(this);
label_tdd.setText(getString(R.string.danar_stats_tdd)); label_tdd.setText(MainApp.gs(R.string.danar_stats_tdd));
label_tdd.setTextColor(Color.WHITE); label_tdd.setTextColor(Color.WHITE);
tr_head.addView(label_tdd); tr_head.addView(label_tdd);
TextView label_ratio = new TextView(this); TextView label_ratio = new TextView(this);
label_ratio.setText(getString(R.string.danar_stats_ratio)); label_ratio.setText(MainApp.gs(R.string.danar_stats_ratio));
label_ratio.setTextColor(Color.WHITE); label_ratio.setTextColor(Color.WHITE);
tr_head.addView(label_ratio); tr_head.addView(label_ratio);
@ -179,17 +179,17 @@ public class TDDStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
TextView label_cum_amount_days = new TextView(this); TextView label_cum_amount_days = new TextView(this);
label_cum_amount_days.setText(getString(R.string.danar_stats_amount_days)); label_cum_amount_days.setText(MainApp.gs(R.string.danar_stats_amount_days));
label_cum_amount_days.setTextColor(Color.WHITE); label_cum_amount_days.setTextColor(Color.WHITE);
ctr_head.addView(label_cum_amount_days); ctr_head.addView(label_cum_amount_days);
TextView label_cum_tdd = new TextView(this); TextView label_cum_tdd = new TextView(this);
label_cum_tdd.setText(getString(R.string.danar_stats_tdd)); label_cum_tdd.setText(MainApp.gs(R.string.danar_stats_tdd));
label_cum_tdd.setTextColor(Color.WHITE); label_cum_tdd.setTextColor(Color.WHITE);
ctr_head.addView(label_cum_tdd); ctr_head.addView(label_cum_tdd);
TextView label_cum_ratio = new TextView(this); TextView label_cum_ratio = new TextView(this);
label_cum_ratio.setText(getString(R.string.danar_stats_ratio)); label_cum_ratio.setText(MainApp.gs(R.string.danar_stats_ratio));
label_cum_ratio.setTextColor(Color.WHITE); label_cum_ratio.setTextColor(Color.WHITE);
ctr_head.addView(label_cum_ratio); ctr_head.addView(label_cum_ratio);
@ -207,17 +207,17 @@ public class TDDStatsActivity extends Activity {
TableLayout.LayoutParams.WRAP_CONTENT)); TableLayout.LayoutParams.WRAP_CONTENT));
TextView label_exp_weight = new TextView(this); TextView label_exp_weight = new TextView(this);
label_exp_weight.setText(getString(R.string.danar_stats_weight)); label_exp_weight.setText(MainApp.gs(R.string.danar_stats_weight));
label_exp_weight.setTextColor(Color.WHITE); label_exp_weight.setTextColor(Color.WHITE);
etr_head.addView(label_exp_weight); etr_head.addView(label_exp_weight);
TextView label_exp_tdd = new TextView(this); TextView label_exp_tdd = new TextView(this);
label_exp_tdd.setText(getString(R.string.danar_stats_tdd)); label_exp_tdd.setText(MainApp.gs(R.string.danar_stats_tdd));
label_exp_tdd.setTextColor(Color.WHITE); label_exp_tdd.setTextColor(Color.WHITE);
etr_head.addView(label_exp_tdd); etr_head.addView(label_exp_tdd);
TextView label_exp_ratio = new TextView(this); TextView label_exp_ratio = new TextView(this);
label_exp_ratio.setText(getString(R.string.danar_stats_ratio)); label_exp_ratio.setText(MainApp.gs(R.string.danar_stats_ratio));
label_exp_ratio.setTextColor(Color.WHITE); label_exp_ratio.setTextColor(Color.WHITE);
etr_head.addView(label_exp_ratio); etr_head.addView(label_exp_ratio);
@ -235,7 +235,7 @@ public class TDDStatsActivity extends Activity {
reloadButton.setVisibility(View.GONE); reloadButton.setVisibility(View.GONE);
statusView.setVisibility(View.VISIBLE); statusView.setVisibility(View.VISIBLE);
statsMessage.setVisibility(View.VISIBLE); statsMessage.setVisibility(View.VISIBLE);
statsMessage.setText(getString(R.string.danar_stats_warning_Message)); statsMessage.setText(MainApp.gs(R.string.danar_stats_warning_Message));
} }
}); });
ConfigBuilderPlugin.getCommandQueue().loadTDDs( new Callback() { ConfigBuilderPlugin.getCommandQueue().loadTDDs( new Callback() {
@ -441,7 +441,7 @@ public class TDDStatsActivity extends Activity {
if (isOldData(historyList) && ConfigBuilderPlugin.getActivePump().getPumpDescription().needsManualTDDLoad) { if (isOldData(historyList) && ConfigBuilderPlugin.getActivePump().getPumpDescription().needsManualTDDLoad) {
statsMessage.setVisibility(View.VISIBLE); statsMessage.setVisibility(View.VISIBLE);
statsMessage.setText(getString(R.string.danar_stats_olddata_Message)); statsMessage.setText(MainApp.gs(R.string.danar_stats_olddata_Message));
} else { } else {
tl.setBackgroundColor(Color.TRANSPARENT); tl.setBackgroundColor(Color.TRANSPARENT);

View file

@ -11,4 +11,5 @@ public class MealData {
public double slopeFromMinDeviation = 999; public double slopeFromMinDeviation = 999;
public long lastBolusTime; public long lastBolusTime;
public long lastCarbTime = 0L; public long lastCarbTime = 0L;
public double usedMinCarbsImpact = 0d;
} }

View file

@ -11,7 +11,7 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
@ -79,14 +79,10 @@ public class QuickWizardEntry {
// COB // COB
double cob = 0d; double cob = 0d;
AutosensData autosensData; if (useCOB() == YES) {
if (_synchronized) CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(_synchronized, "QuickWizard COB");
autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("QuickWizard COB"); if (cobInfo.displayCob != null)
else cob = cobInfo.displayCob;
autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensData("QuickWizard COB");
if (autosensData != null && useCOB() == YES) {
cob = autosensData.cob;
} }
// Temp target // Temp target

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.db; package info.nightscout.androidaps.db;
import android.content.res.Resources;
import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTable;
@ -195,8 +197,7 @@ public class BgReading implements DataPointWithLabelInterface {
@Override @Override
public float getSize() { public float getSize() {
boolean isTablet = MainApp.sResources.getBoolean(R.bool.isTablet); return 1;
return isTablet ? 8 : 5;
} }
@Override @Override
@ -212,7 +213,7 @@ public class BgReading implements DataPointWithLabelInterface {
} }
int color = MainApp.sResources.getColor(R.color.inrange); int color = MainApp.sResources.getColor(R.color.inrange);
if (isPrediction()) if (isPrediction())
color = MainApp.sResources.getColor(R.color.prediction); return getPredectionColor();
else if (valueToUnits(units) < lowLine) else if (valueToUnits(units) < lowLine)
color = MainApp.sResources.getColor(R.color.low); color = MainApp.sResources.getColor(R.color.low);
else if (valueToUnits(units) > highLine) else if (valueToUnits(units) > highLine)
@ -220,8 +221,7 @@ public class BgReading implements DataPointWithLabelInterface {
return color; return color;
} }
@Override public int getPredectionColor() {
public int getSecondColor() {
if (isIOBPrediction) if (isIOBPrediction)
return MainApp.sResources.getColor(R.color.iob); return MainApp.sResources.getColor(R.color.iob);
if (isCOBPrediction) if (isCOBPrediction)

View file

@ -95,7 +95,7 @@ public class CareportalEvent implements DataPointWithLabelInterface {
if (OverviewFragment.shorttextmode) if (OverviewFragment.shorttextmode)
return diff.get(TimeUnit.DAYS) +"d" + diff.get(TimeUnit.HOURS) + "h"; return diff.get(TimeUnit.DAYS) +"d" + diff.get(TimeUnit.HOURS) + "h";
else else
return diff.get(TimeUnit.DAYS) + " " + MainApp.sResources.getString(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.sResources.getString(R.string.hours); return diff.get(TimeUnit.DAYS) + " " + MainApp.gs(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.gs(R.string.hours);
} }
public boolean isOlderThan(double hours) { public boolean isOlderThan(double hours) {
@ -263,9 +263,4 @@ public class CareportalEvent implements DataPointWithLabelInterface {
return Color.GRAY; return Color.GRAY;
} }
@Override
public int getSecondColor() {
return 0;
}
} }

View file

@ -297,8 +297,4 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
return Color.CYAN; return Color.CYAN;
} }
@Override
public int getSecondColor() {
return 0;
}
} }

View file

@ -263,11 +263,6 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
return Color.CYAN; return Color.CYAN;
} }
@Override
public int getSecondColor() {
return 0;
}
public String toString() { public String toString() {
return "ProfileSwitch{" + return "ProfileSwitch{" +
"date=" + date + "date=" + date +

View file

@ -0,0 +1,13 @@
package info.nightscout.androidaps.events;
public class EventChargingState {
public boolean isCharging = false;
public EventChargingState() {}
public EventChargingState(boolean isCharging) {
this.isCharging = isCharging;
}
}

View file

@ -0,0 +1,14 @@
package info.nightscout.androidaps.events;
public class EventNetworkChange extends Event {
public boolean mobileConnected = false;
public boolean wifiConnected = false;
public String ssid = "";
public boolean roaming = false;
public String getSsid() {
return ssid.replace("SSID: ","").replaceAll("\"","");
}
}

View file

@ -12,11 +12,11 @@ public class EventPreferenceChange extends Event {
} }
public EventPreferenceChange(int resourceID) { public EventPreferenceChange(int resourceID) {
changedKey = MainApp.sResources.getString(resourceID); changedKey = MainApp.gs(resourceID);
} }
public boolean isChanged(int id) { public boolean isChanged(int id) {
return changedKey.equals(MainApp.sResources.getString(id)); return changedKey.equals(MainApp.gs(id));
} }
public boolean isChanged(String id) { public boolean isChanged(String id) {

View file

@ -46,13 +46,13 @@ public class EventPumpStatusChanged extends Event {
public String textStatus() { public String textStatus() {
if (sStatus == CONNECTING) if (sStatus == CONNECTING)
return String.format(MainApp.sResources.getString(R.string.danar_history_connectingfor), sSecondsElapsed); return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed);
else if (sStatus == CONNECTED) else if (sStatus == CONNECTED)
return MainApp.sResources.getString(R.string.connected); return MainApp.gs(R.string.connected);
else if (sStatus == PERFORMING) else if (sStatus == PERFORMING)
return sPerfomingAction; return sPerfomingAction;
else if (sStatus == DISCONNECTING) else if (sStatus == DISCONNECTING)
return MainApp.sResources.getString(R.string.disconnecting); return MainApp.gs(R.string.disconnecting);
else if (sStatus == DISCONNECTED) else if (sStatus == DISCONNECTED)
return ""; return "";
return ""; return "";

View file

@ -11,5 +11,5 @@ public interface APSInterface {
public APSResult getLastAPSResult(); public APSResult getLastAPSResult();
public Date getLastAPSRun(); public Date getLastAPSRun();
public void invoke(String initiator); public void invoke(String initiator, boolean tempBasalFallback);
} }

View file

@ -158,7 +158,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
if (activeExtendedBolus != null) { if (activeExtendedBolus != null) {
extendedBolus.setVisibility(View.GONE); extendedBolus.setVisibility(View.GONE);
extendedBolusCancel.setVisibility(View.VISIBLE); extendedBolusCancel.setVisibility(View.VISIBLE);
extendedBolusCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + activeExtendedBolus.toString()); extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
} else { } else {
extendedBolus.setVisibility(View.VISIBLE); extendedBolus.setVisibility(View.VISIBLE);
extendedBolusCancel.setVisibility(View.GONE); extendedBolusCancel.setVisibility(View.GONE);
@ -174,7 +174,7 @@ public class ActionsFragment extends SubscriberFragment implements View.OnClickL
if (activeTemp != null) { if (activeTemp != null) {
tempBasal.setVisibility(View.GONE); tempBasal.setVisibility(View.GONE);
tempBasalCancel.setVisibility(View.VISIBLE); tempBasalCancel.setVisibility(View.VISIBLE);
tempBasalCancel.setText(MainApp.instance().getString(R.string.cancel) + " " + activeTemp.toStringShort()); tempBasalCancel.setText(MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort());
} else { } else {
tempBasal.setVisibility(View.VISIBLE); tempBasal.setVisibility(View.VISIBLE);
tempBasalCancel.setVisibility(View.GONE); tempBasalCancel.setVisibility(View.GONE);

View file

@ -179,10 +179,10 @@ public class FillDialog extends DialogFragment implements OnClickListener {
} }
if (pumpSiteChangeCheckbox.isChecked()) if (pumpSiteChangeCheckbox.isChecked())
confirmMessage.add("" + "<font color='" + MainApp.sResources.getColor(R.color.high) + "'>" + getString(R.string.record_pump_site_change) + "</font>"); confirmMessage.add("" + "<font color='" + MainApp.sResources.getColor(R.color.high) + "'>" + MainApp.gs(R.string.record_pump_site_change) + "</font>");
if (insulinCartridgeChangeCheckbox.isChecked()) if (insulinCartridgeChangeCheckbox.isChecked())
confirmMessage.add("" + "<font color='" + MainApp.sResources.getColor(R.color.high) + "'>" + getString(R.string.record_insulin_cartridge_change) + "</font>"); confirmMessage.add("" + "<font color='" + MainApp.sResources.getColor(R.color.high) + "'>" + MainApp.gs(R.string.record_insulin_cartridge_change) + "</font>");
final String notes = notesEdit.getText().toString(); final String notes = notesEdit.getText().toString();
if (!notes.isEmpty()) { if (!notes.isEmpty()) {
@ -197,7 +197,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
builder.setTitle(MainApp.gs(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
if (insulinAfterConstraints > 0 || pumpSiteChangeCheckbox.isChecked() || insulinCartridgeChangeCheckbox.isChecked()) { if (insulinAfterConstraints > 0 || pumpSiteChangeCheckbox.isChecked() || insulinCartridgeChangeCheckbox.isChecked()) {
builder.setMessage(Html.fromHtml(Joiner.on("<br/>").join(confirmMessage))); builder.setMessage(Html.fromHtml(Joiner.on("<br/>").join(confirmMessage)));
builder.setPositiveButton(getString(R.string.primefill), (dialog, id) -> { builder.setPositiveButton(MainApp.gs(R.string.primefill), (dialog, id) -> {
if (finalInsulinAfterConstraints > 0) { if (finalInsulinAfterConstraints > 0) {
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo(); DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.insulin = finalInsulinAfterConstraints; detailedBolusInfo.insulin = finalInsulinAfterConstraints;
@ -212,7 +212,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment); i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror)); i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); MainApp.instance().startActivity(i);
} }
@ -228,7 +228,7 @@ public class FillDialog extends DialogFragment implements OnClickListener {
} else { } else {
builder.setMessage(MainApp.gs(R.string.no_action_selected)); builder.setMessage(MainApp.gs(R.string.no_action_selected));
} }
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
dismiss(); dismiss();
} catch (RuntimeException e) { } catch (RuntimeException e) {

View file

@ -12,6 +12,7 @@ import android.view.ViewGroup;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import org.mozilla.javascript.tools.jsc.Main;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,7 +40,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
getDialog().setTitle(getString(R.string.overview_extendedbolus_button)); getDialog().setTitle(MainApp.gs(R.string.overview_extendedbolus_button));
View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false); View view = inflater.inflate(R.layout.overview_newextendedbolus_dialog, container, false);
@ -68,13 +69,13 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
Double insulin = SafeParse.stringToDouble(editInsulin.getText()); Double insulin = SafeParse.stringToDouble(editInsulin.getText());
int durationInMinutes = SafeParse.stringToInt(editDuration.getText()); int durationInMinutes = SafeParse.stringToInt(editDuration.getText());
String confirmMessage = getString(R.string.setextendedbolusquestion); String confirmMessage = MainApp.gs(R.string.setextendedbolusquestion);
Double insulinAfterConstraint = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value(); Double insulinAfterConstraint = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(insulin)).value();
confirmMessage += " " + insulinAfterConstraint + " U "; confirmMessage += " " + insulinAfterConstraint + " U ";
confirmMessage += getString(R.string.duration) + " " + durationInMinutes + "min ?"; confirmMessage += MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (insulinAfterConstraint - insulin != 0d) if (insulinAfterConstraint - insulin != 0d)
confirmMessage += "\n" + getString(R.string.constraintapllied); confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
insulin = insulinAfterConstraint; insulin = insulinAfterConstraint;
final Double finalInsulin = insulin; final Double finalInsulin = insulin;
@ -82,9 +83,9 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
final Context context = getContext(); final Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getString(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
ConfigBuilderPlugin.getCommandQueue().extendedBolus(finalInsulin, finalDurationInMinutes, new Callback() { ConfigBuilderPlugin.getCommandQueue().extendedBolus(finalInsulin, finalDurationInMinutes, new Callback() {
@Override @Override
@ -93,7 +94,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment); i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror)); i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); MainApp.instance().startActivity(i);
} }
@ -102,7 +103,7 @@ public class NewExtendedBolusDialog extends DialogFragment implements View.OnCli
FabricPrivacy.getInstance().logCustom(new CustomEvent("ExtendedBolus")); FabricPrivacy.getInstance().logCustom(new CustomEvent("ExtendedBolus"));
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
dismiss(); dismiss();

View file

@ -52,7 +52,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
getDialog().setTitle(getString(R.string.overview_tempbasal_button)); getDialog().setTitle(MainApp.gs(R.string.overview_tempbasal_button));
View view = inflater.inflate(R.layout.overview_newtempbasal_dialog, container, false); View view = inflater.inflate(R.layout.overview_newtempbasal_dialog, container, false);
@ -122,21 +122,21 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
if (profile == null) if (profile == null)
return; return;
String confirmMessage = getString(R.string.setbasalquestion); String confirmMessage = MainApp.gs(R.string.setbasalquestion);
if (setAsPercent) { if (setAsPercent) {
int basalPercentInput = SafeParse.stringToInt(basalPercent.getText()); int basalPercentInput = SafeParse.stringToInt(basalPercent.getText());
percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(basalPercentInput), profile).value(); percent = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(basalPercentInput), profile).value();
confirmMessage += "\n" + percent + "% "; confirmMessage += "\n" + percent + "% ";
confirmMessage += "\n" + getString(R.string.duration) + " " + durationInMinutes + "min ?"; confirmMessage += "\n" + MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (percent != basalPercentInput) if (percent != basalPercentInput)
confirmMessage += "\n" + getString(R.string.constraintapllied); confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
} else { } else {
Double basalAbsoluteInput = SafeParse.stringToDouble(basalAbsolute.getText()); Double basalAbsoluteInput = SafeParse.stringToDouble(basalAbsolute.getText());
absolute = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(basalAbsoluteInput), profile).value(); absolute = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(basalAbsoluteInput), profile).value();
confirmMessage += "\n" + absolute + " U/h "; confirmMessage += "\n" + absolute + " U/h ";
confirmMessage += "\n" + getString(R.string.duration) + " " + durationInMinutes + "min ?"; confirmMessage += "\n" + MainApp.gs(R.string.duration) + " " + durationInMinutes + "min ?";
if (absolute - basalAbsoluteInput != 0d) if (absolute - basalAbsoluteInput != 0d)
confirmMessage += "\n" + getString(R.string.constraintapllied); confirmMessage += "\n" + MainApp.gs(R.string.constraintapllied);
} }
final int finalBasalPercent = percent; final int finalBasalPercent = percent;
@ -144,9 +144,9 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
final int finalDurationInMinutes = durationInMinutes; final int finalDurationInMinutes = durationInMinutes;
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(this.getContext().getString(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
Callback callback = new Callback() { Callback callback = new Callback() {
@Override @Override
@ -155,7 +155,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment); i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.tempbasaldeliveryerror)); i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); MainApp.instance().startActivity(i);
} }
@ -169,7 +169,7 @@ public class NewTempBasalDialog extends DialogFragment implements View.OnClickLi
FabricPrivacy.getInstance().logCustom(new CustomEvent("TempBasal")); FabricPrivacy.getInstance().logCustom(new CustomEvent("TempBasal"));
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
dismiss(); dismiss();

View file

@ -216,8 +216,8 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
CareportalEvent careportalEvent; CareportalEvent careportalEvent;
NSSettingsStatus nsSettings = new NSSettingsStatus().getInstance(); NSSettingsStatus nsSettings = new NSSettingsStatus().getInstance();
double iageUrgent = nsSettings.getExtendedWarnValue("iage", "urgent", 72); double iageUrgent = nsSettings.getExtendedWarnValue("iage", "urgent", 96);
double iageWarn = nsSettings.getExtendedWarnValue("iage", "warn", 48); double iageWarn = nsSettings.getExtendedWarnValue("iage", "warn", 72);
double cageUrgent = nsSettings.getExtendedWarnValue("cage", "urgent", 72); double cageUrgent = nsSettings.getExtendedWarnValue("cage", "urgent", 72);
double cageWarn = nsSettings.getExtendedWarnValue("cage", "warn", 48); double cageWarn = nsSettings.getExtendedWarnValue("cage", "warn", 48);
double sageUrgent = nsSettings.getExtendedWarnValue("sage", "urgent", 166); double sageUrgent = nsSettings.getExtendedWarnValue("sage", "urgent", 166);
@ -225,7 +225,7 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
double pbageUrgent = nsSettings.getExtendedWarnValue("pgage", "urgent", 360); double pbageUrgent = nsSettings.getExtendedWarnValue("pgage", "urgent", 360);
double pbageWarn = nsSettings.getExtendedWarnValue("pgage", "warn", 240); double pbageWarn = nsSettings.getExtendedWarnValue("pgage", "warn", 240);
String notavailable = OverviewFragment.shorttextmode ? "-" : MainApp.sResources.getString(R.string.notavailable); String notavailable = OverviewFragment.shorttextmode ? "-" : MainApp.gs(R.string.notavailable);
if (sage != null) { if (sage != null) {
careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE); careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(CareportalEvent.SENSORCHANGE);
if (careportalEvent != null) { if (careportalEvent != null) {

View file

@ -715,14 +715,26 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
FabricPrivacy.getInstance().logCustom(new CustomEvent("TempTarget")); FabricPrivacy.getInstance().logCustom(new CustomEvent("TempTarget"));
} }
} else { } else {
NSUpload.uploadCareportalEntryToNS(data); if (JsonHelper.safeGetString(data, "eventType").equals(CareportalEvent.PROFILESWITCH)) {
ProfileSwitch profileSwitch = prepareProfileSwitch(
profileStore,
JsonHelper.safeGetString(data, "profile"),
JsonHelper.safeGetInt(data, "duration"),
JsonHelper.safeGetInt(data, "percentage"),
JsonHelper.safeGetInt(data, "timeshift"),
eventTime.getTime()
);
NSUpload.uploadProfileSwitch(profileSwitch);
} else {
NSUpload.uploadCareportalEntryToNS(data);
}
FabricPrivacy.getInstance().logCustom(new CustomEvent("NSTreatment")); FabricPrivacy.getInstance().logCustom(new CustomEvent("NSTreatment"));
} }
} }
public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) { public static ProfileSwitch prepareProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, long date) {
ProfileSwitch profileSwitch = new ProfileSwitch(); ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis(); profileSwitch.date = date;
profileSwitch.source = Source.USER; profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName; profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString(); profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
@ -731,6 +743,11 @@ public class NewNSTreatmentDialog extends DialogFragment implements View.OnClick
profileSwitch.isCPP = percentage != 100 || timeshift != 0; profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift; profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage; profileSwitch.percentage = percentage;
return profileSwitch;
}
public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) {
ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeshift, System.currentTimeMillis());
TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch); TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch);
FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch")); FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} }

View file

@ -285,7 +285,7 @@ public class ConfigBuilderFragment extends SubscriberFragment {
holder.checkboxEnabled.setEnabled(false); holder.checkboxEnabled.setEnabled(false);
} }
if (plugin.pluginDescription.alwayVisible) { if (plugin.pluginDescription.alwayVisible) {
holder.checkboxEnabled.setEnabled(false); holder.checkboxEnabled.setEnabled(false);
} }
@ -339,7 +339,7 @@ public class ConfigBuilderFragment extends SubscriberFragment {
} }
void onEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) { public static void processOnEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
ArrayList<PluginBase> pluginsInCategory = null; ArrayList<PluginBase> pluginsInCategory = null;
switch (type) { switch (type) {
// Multiple selection allowed // Multiple selection allowed
@ -391,10 +391,14 @@ public class ConfigBuilderFragment extends SubscriberFragment {
else else
pluginsInCategory.get(0).setPluginEnabled(type, true); pluginsInCategory.get(0).setPluginEnabled(type, true);
} }
updateGUI();
} }
} }
void onEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
processOnEnabledCategoryChanged(changedPlugin, type);
updateGUI();
}
/**** /****
* Method for Setting the Height of the ListView dynamically. * Method for Setting the Height of the ListView dynamically.
* *** Hack to fix the issue of not showing all the items of the ListView * *** Hack to fix the issue of not showing all the items of the ListView

View file

@ -417,6 +417,9 @@ public class ConfigBuilderPlugin extends PluginBase {
*/ */
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) { public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
if (!request.tempBasalRequested) { if (!request.tempBasalRequested) {
if (callback != null) {
callback.result(new PumpEnactResult().enacted(false).success(true).comment(MainApp.gs(R.string.nochangerequested))).run();
}
return; return;
} }
@ -426,17 +429,17 @@ public class ConfigBuilderPlugin extends PluginBase {
request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value(); request.rate = MainApp.getConstraintChecker().applyBasalConstraints(request.rateConstraint, profile).value();
if (!pump.isInitialized()) { if (!pump.isInitialized()) {
log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpNotInitialized)); log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) { if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
} }
return; return;
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
log.debug("applyAPSRequest: " + MainApp.sResources.getString(R.string.pumpsuspended)); log.debug("applyAPSRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) { if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpsuspended)).enacted(false).success(false)).run(); callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
} }
return; return;
} }
@ -496,17 +499,17 @@ public class ConfigBuilderPlugin extends PluginBase {
PumpInterface pump = getActivePump(); PumpInterface pump = getActivePump();
if (!pump.isInitialized()) { if (!pump.isInitialized()) {
log.debug("applySMBRequest: " + MainApp.sResources.getString(R.string.pumpNotInitialized)); log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpNotInitialized));
if (callback != null) { if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpNotInitialized)).enacted(false).success(false)).run(); callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpNotInitialized)).enacted(false).success(false)).run();
} }
return; return;
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
log.debug("applySMBRequest: " + MainApp.sResources.getString(R.string.pumpsuspended)); log.debug("applySMBRequest: " + MainApp.gs(R.string.pumpsuspended));
if (callback != null) { if (callback != null) {
callback.result(new PumpEnactResult().comment(MainApp.sResources.getString(R.string.pumpsuspended)).enacted(false).success(false)).run(); callback.result(new PumpEnactResult().comment(MainApp.gs(R.string.pumpsuspended)).enacted(false).success(false)).run();
} }
return; return;
} }
@ -535,7 +538,7 @@ public class ConfigBuilderPlugin extends PluginBase {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment); i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.failedupdatebasalprofile)); i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); MainApp.instance().startActivity(i);
} }

View file

@ -19,13 +19,13 @@ public class DetailedBolusInfoStorage {
private static Logger log = LoggerFactory.getLogger(DetailedBolusInfoStorage.class); private static Logger log = LoggerFactory.getLogger(DetailedBolusInfoStorage.class);
private static List<DetailedBolusInfo> store = new ArrayList<>(); private static List<DetailedBolusInfo> store = new ArrayList<>();
public static void add(DetailedBolusInfo detailedBolusInfo) { public static synchronized void add(DetailedBolusInfo detailedBolusInfo) {
log.debug("Stored bolus info: " + detailedBolusInfo); log.debug("Stored bolus info: " + detailedBolusInfo);
store.add(detailedBolusInfo); store.add(detailedBolusInfo);
} }
@Nullable @Nullable
public static DetailedBolusInfo findDetailedBolusInfo(long bolustime) { public static synchronized DetailedBolusInfo findDetailedBolusInfo(long bolustime) {
DetailedBolusInfo found = null; DetailedBolusInfo found = null;
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; long infoTime = store.get(i).date;
@ -38,7 +38,7 @@ public class DetailedBolusInfoStorage {
return found; return found;
} }
public static void remove(long bolustime) { public static synchronized void remove(long bolustime) {
for (int i = 0; i < store.size(); i++) { for (int i = 0; i < store.size(); i++) {
long infoTime = store.get(i).date; long infoTime = store.get(i).date;
if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) { if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {

View file

@ -26,6 +26,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.T;
public class ObjectivesFragment extends SubscriberFragment { public class ObjectivesFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class); private static Logger log = LoggerFactory.getLogger(ObjectivesFragment.class);
@ -58,7 +59,7 @@ public class ObjectivesFragment extends SubscriberFragment {
holder.position.setText(String.valueOf(position + 1)); holder.position.setText(String.valueOf(position + 1));
holder.objective.setText(o.objective); holder.objective.setText(o.objective);
holder.gate.setText(o.gate); holder.gate.setText(o.gate);
holder.duration.setText(context.getString(R.string.objectives_minimalduration) + " " + o.durationInDays + " " + context.getString(R.string.days)); holder.duration.setText(MainApp.gs(R.string.objectives_minimalduration) + " " + o.durationInDays + " " + MainApp.gs(R.string.days));
holder.progress.setText(requirementsMet.comment); holder.progress.setText(requirementsMet.comment);
holder.started.setText(o.started.toLocaleString()); holder.started.setText(o.started.toLocaleString());
holder.accomplished.setText(o.accomplished.toLocaleString()); holder.accomplished.setText(o.accomplished.toLocaleString());
@ -204,7 +205,7 @@ public class ObjectivesFragment extends SubscriberFragment {
return 1; return 1;
} else if (objectiveStartedTime > 0 && !enableFakeValue } else if (objectiveStartedTime > 0 && !enableFakeValue
&& objectiveAccomplishedTime == 0 && objectiveAccomplishedTime == 0
&& !(objectiveStartedTime + durationInDays * 24 * 60 * 60 * 1000 >= now && requirementsMet)) { && !(objectiveStartedTime + T.days(durationInDays).msecs() < now && requirementsMet)) {
return 2; return 2;
} else if (objectiveAccomplishedTime == 0) { } else if (objectiveAccomplishedTime == 0) {
return 3; return 3;
@ -240,20 +241,20 @@ public class ObjectivesFragment extends SubscriberFragment {
}); });
// Add correct translations to array after app is initialized // Add correct translations to array after app is initialized
ObjectivesPlugin.objectives.get(0).objective = MainApp.sResources.getString(R.string.objectives_0_objective); ObjectivesPlugin.objectives.get(0).objective = MainApp.gs(R.string.objectives_0_objective);
ObjectivesPlugin.objectives.get(1).objective = MainApp.sResources.getString(R.string.objectives_1_objective); ObjectivesPlugin.objectives.get(1).objective = MainApp.gs(R.string.objectives_1_objective);
ObjectivesPlugin.objectives.get(2).objective = MainApp.sResources.getString(R.string.objectives_2_objective); ObjectivesPlugin.objectives.get(2).objective = MainApp.gs(R.string.objectives_2_objective);
ObjectivesPlugin.objectives.get(3).objective = MainApp.sResources.getString(R.string.objectives_3_objective); ObjectivesPlugin.objectives.get(3).objective = MainApp.gs(R.string.objectives_3_objective);
ObjectivesPlugin.objectives.get(4).objective = MainApp.sResources.getString(R.string.objectives_4_objective); ObjectivesPlugin.objectives.get(4).objective = MainApp.gs(R.string.objectives_4_objective);
ObjectivesPlugin.objectives.get(5).objective = MainApp.sResources.getString(R.string.objectives_5_objective); ObjectivesPlugin.objectives.get(5).objective = MainApp.gs(R.string.objectives_5_objective);
ObjectivesPlugin.objectives.get(6).objective = MainApp.sResources.getString(R.string.objectives_6_objective); ObjectivesPlugin.objectives.get(6).objective = MainApp.gs(R.string.objectives_6_objective);
ObjectivesPlugin.objectives.get(7).objective = MainApp.sResources.getString(R.string.objectives_7_objective); ObjectivesPlugin.objectives.get(7).objective = MainApp.gs(R.string.objectives_7_objective);
ObjectivesPlugin.objectives.get(0).gate = MainApp.sResources.getString(R.string.objectives_0_gate); ObjectivesPlugin.objectives.get(0).gate = MainApp.gs(R.string.objectives_0_gate);
ObjectivesPlugin.objectives.get(1).gate = MainApp.sResources.getString(R.string.objectives_1_gate); ObjectivesPlugin.objectives.get(1).gate = MainApp.gs(R.string.objectives_1_gate);
ObjectivesPlugin.objectives.get(2).gate = MainApp.sResources.getString(R.string.objectives_2_gate); ObjectivesPlugin.objectives.get(2).gate = MainApp.gs(R.string.objectives_2_gate);
ObjectivesPlugin.objectives.get(3).gate = MainApp.sResources.getString(R.string.objectives_3_gate); ObjectivesPlugin.objectives.get(3).gate = MainApp.gs(R.string.objectives_3_gate);
ObjectivesPlugin.objectives.get(4).gate = MainApp.sResources.getString(R.string.objectives_4_gate); ObjectivesPlugin.objectives.get(4).gate = MainApp.gs(R.string.objectives_4_gate);
ObjectivesPlugin.objectives.get(5).gate = MainApp.sResources.getString(R.string.objectives_5_gate); ObjectivesPlugin.objectives.get(5).gate = MainApp.gs(R.string.objectives_5_gate);
updateGUI(); updateGUI();

View file

@ -54,7 +54,7 @@ public class FoodFragment extends SubscriberFragment {
ArrayList<CharSequence> categories; ArrayList<CharSequence> categories;
ArrayList<CharSequence> subcategories; ArrayList<CharSequence> subcategories;
final String EMPTY = MainApp.sResources.getString(R.string.none); final String EMPTY = MainApp.gs(R.string.none);
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
@ -158,7 +158,7 @@ public class FoodFragment extends SubscriberFragment {
// make it unique // make it unique
categories = new ArrayList<>(catSet); categories = new ArrayList<>(catSet);
categories.add(0, MainApp.sResources.getString(R.string.none)); categories.add(0, MainApp.gs(R.string.none));
ArrayAdapter<CharSequence> adapterCategories = new ArrayAdapter<>(getContext(), ArrayAdapter<CharSequence> adapterCategories = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, categories); R.layout.spinner_centered, categories);
@ -180,7 +180,7 @@ public class FoodFragment extends SubscriberFragment {
// make it unique // make it unique
subcategories = new ArrayList<>(subCatSet); subcategories = new ArrayList<>(subCatSet);
subcategories.add(0, MainApp.sResources.getString(R.string.none)); subcategories.add(0, MainApp.gs(R.string.none));
ArrayAdapter<CharSequence> adapterSubcategories = new ArrayAdapter<>(getContext(), ArrayAdapter<CharSequence> adapterSubcategories = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, subcategories); R.layout.spinner_centered, subcategories);
@ -242,14 +242,14 @@ public class FoodFragment extends SubscriberFragment {
holder.ns.setVisibility(food._id != null ? View.VISIBLE : View.GONE); holder.ns.setVisibility(food._id != null ? View.VISIBLE : View.GONE);
holder.name.setText(food.name); holder.name.setText(food.name);
holder.portion.setText(food.portion + food.units); holder.portion.setText(food.portion + food.units);
holder.carbs.setText(food.carbs + MainApp.sResources.getString(R.string.shortgramm)); holder.carbs.setText(food.carbs + MainApp.gs(R.string.shortgramm));
holder.fat.setText(MainApp.sResources.getString(R.string.shortfat) + ": " + food.fat + MainApp.sResources.getString(R.string.shortgramm)); holder.fat.setText(MainApp.gs(R.string.shortfat) + ": " + food.fat + MainApp.gs(R.string.shortgramm));
if (food.fat == 0) if (food.fat == 0)
holder.fat.setVisibility(View.INVISIBLE); holder.fat.setVisibility(View.INVISIBLE);
holder.protein.setText(MainApp.sResources.getString(R.string.shortprotein) + ": " + food.protein + MainApp.sResources.getString(R.string.shortgramm)); holder.protein.setText(MainApp.gs(R.string.shortprotein) + ": " + food.protein + MainApp.gs(R.string.shortgramm));
if (food.protein == 0) if (food.protein == 0)
holder.protein.setVisibility(View.INVISIBLE); holder.protein.setVisibility(View.INVISIBLE);
holder.energy.setText(MainApp.sResources.getString(R.string.shortenergy) + ": " + food.energy + MainApp.sResources.getString(R.string.shortkilojoul)); holder.energy.setText(MainApp.gs(R.string.shortenergy) + ": " + food.energy + MainApp.gs(R.string.shortkilojoul));
if (food.energy == 0) if (food.energy == 0)
holder.energy.setVisibility(View.INVISIBLE); holder.energy.setVisibility(View.INVISIBLE);
holder.remove.setTag(food); holder.remove.setTag(food);
@ -291,9 +291,9 @@ public class FoodFragment extends SubscriberFragment {
case R.id.food_remove: case R.id.food_remove:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.sResources.getString(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(MainApp.sResources.getString(R.string.removerecord) + "\n" + food.name); builder.setMessage(MainApp.gs(R.string.removerecord) + "\n" + food.name);
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
final String _id = food._id; final String _id = food._id;
if (_id != null && !_id.equals("")) { if (_id != null && !_id.equals("")) {
@ -302,7 +302,7 @@ public class FoodFragment extends SubscriberFragment {
MainApp.getSpecificPlugin(FoodPlugin.class).getService().delete(food); MainApp.getSpecificPlugin(FoodPlugin.class).getService().delete(food);
} }
}); });
builder.setNegativeButton(MainApp.sResources.getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
break; break;

View file

@ -56,7 +56,7 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli
} }
public String getNotificationPattern() { public String getNotificationPattern() {
return MainApp.sResources.getString(R.string.dia_too_short); return MainApp.gs(R.string.dia_too_short);
} }
public double getUserDefinedDia() { public double getUserDefinedDia() {
@ -98,7 +98,7 @@ public abstract class InsulinOrefBasePlugin extends PluginBase implements Insuli
String comment = commentStandardText(); String comment = commentStandardText();
double userDia = getUserDefinedDia(); double userDia = getUserDefinedDia();
if (userDia < MIN_DIA) { if (userDia < MIN_DIA) {
comment += "\n" + String.format(MainApp.sResources.getString(R.string.dia_too_short), userDia, MIN_DIA); comment += "\n" + String.format(MainApp.gs(R.string.dia_too_short), userDia, MIN_DIA);
} }
return comment; return comment;
} }

View file

@ -33,12 +33,12 @@ public class InsulinOrefFreePeakPlugin extends InsulinOrefBasePlugin {
} }
public String getFriendlyName() { public String getFriendlyName() {
return MainApp.sResources.getString(R.string.free_peak_oref); return MainApp.gs(R.string.free_peak_oref);
} }
@Override @Override
public String commentStandardText() { public String commentStandardText() {
return MainApp.sResources.getString(R.string.insulin_peak_time) + ": " + getPeak(); return MainApp.gs(R.string.insulin_peak_time) + ": " + getPeak();
} }
@Override @Override

View file

@ -32,12 +32,12 @@ public class InsulinOrefRapidActingPlugin extends InsulinOrefBasePlugin {
@Override @Override
public String getFriendlyName() { public String getFriendlyName() {
return MainApp.sResources.getString(R.string.rapid_acting_oref); return MainApp.gs(R.string.rapid_acting_oref);
} }
@Override @Override
public String commentStandardText() { public String commentStandardText() {
return MainApp.sResources.getString(R.string.fastactinginsulincomment); return MainApp.gs(R.string.fastactinginsulincomment);
} }
@Override @Override

View file

@ -32,17 +32,17 @@ public class InsulinOrefUltraRapidActingPlugin extends InsulinOrefBasePlugin {
@Override @Override
public String getName() { public String getName() {
return MainApp.sResources.getString(R.string.ultrarapid_oref); return MainApp.gs(R.string.ultrarapid_oref);
} }
@Override @Override
public String getFriendlyName() { public String getFriendlyName() {
return MainApp.sResources.getString(R.string.ultrarapid_oref); return MainApp.gs(R.string.ultrarapid_oref);
} }
@Override @Override
public String commentStandardText() { public String commentStandardText() {
return MainApp.sResources.getString(R.string.ultrafastactinginsulincomment); return MainApp.gs(R.string.ultrafastactinginsulincomment);
} }
@Override @Override

View file

@ -7,22 +7,31 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.Scale;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
/** /**
* Created by mike on 25.04.2017. * Created by mike on 25.04.2017.
*/ */
public class AutosensData { public class AutosensData implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(AutosensData.class); private static Logger log = LoggerFactory.getLogger(AutosensData.class);
public void setChartTime(long chartTime) {
this.chartTime = chartTime;
}
static class CarbsInPast { static class CarbsInPast {
long time = 0L; long time = 0L;
double carbs = 0d; double carbs = 0d;
@ -34,19 +43,20 @@ public class AutosensData {
carbs = t.carbs; carbs = t.carbs;
remaining = t.carbs; remaining = t.carbs;
if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) { if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) {
double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, 4d); double maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME);
Profile profile = MainApp.getConfigBuilder().getProfile(t.date); Profile profile = MainApp.getConfigBuilder().getProfile(t.date);
double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits()); double sens = Profile.toMgdl(profile.getIsf(t.date), profile.getUnits());
double ic = profile.getIc(t.date); double ic = profile.getIc(t.date);
min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic; min5minCarbImpact = t.carbs / (maxAbsorptionHours * 60 / 5) * sens / ic;
log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic); log.debug("Min 5m carbs impact for " + carbs + "g @" + new Date(t.date).toLocaleString() + " for " + maxAbsorptionHours + "h calculated to " + min5minCarbImpact + " ISF: " + sens + " IC: " + ic);
} else { } else {
min5minCarbImpact = SP.getDouble("openapsama_min_5m_carbimpact", 3.0); min5minCarbImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact);
} }
} }
} }
public long time = 0L; public long time = 0L;
long chartTime;
public String pastSensitivity = ""; public String pastSensitivity = "";
public double deviation = 0d; public double deviation = 0d;
boolean nonCarbsDeviation = false; boolean nonCarbsDeviation = false;
@ -63,25 +73,33 @@ public class AutosensData {
public double autosensRatio = 1d; public double autosensRatio = 1d;
public double slopeFromMaxDeviation = 0; public double slopeFromMaxDeviation = 0;
public double slopeFromMinDeviation = 999; public double slopeFromMinDeviation = 999;
public double usedMinCarbsImpact = 0d;
public boolean failoverToMinAbsorbtionRate = false;
@Override @Override
public String toString() { public String toString() {
return "AutosensData: " + new Date(time).toLocaleString() + " " + pastSensitivity + " Delta=" + delta + " avgDelta=" + avgDelta + " Bgi=" + bgi + " Deviation=" + deviation + " avgDeviation=" + avgDeviation + " Absorbed=" + absorbed + " CarbsFromBolus=" + carbsFromBolus + " COB=" + cob + " autosensRatio=" + autosensRatio + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation =" + slopeFromMinDeviation ; return "AutosensData: " + new Date(time).toLocaleString() + " " + pastSensitivity + " Delta=" + delta + " avgDelta=" + avgDelta + " Bgi=" + bgi + " Deviation=" + deviation + " avgDeviation=" + avgDeviation + " Absorbed=" + absorbed + " CarbsFromBolus=" + carbsFromBolus + " COB=" + cob + " autosensRatio=" + autosensRatio + " slopeFromMaxDeviation=" + slopeFromMaxDeviation + " slopeFromMinDeviation =" + slopeFromMinDeviation;
} }
public int minOld() { public int minOld() {
return (int) ((System.currentTimeMillis() - time) / 1000 / 60); return (int) ((System.currentTimeMillis() - time) / 1000 / 60);
} }
// remove carbs older than 4h // remove carbs older than timeframe
public void removeOldCarbs(long toTime) { public void removeOldCarbs(long toTime) {
double maxAbsorptionHours = Constants.DEFAULT_MAX_ABSORPTION_TIME;
if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) {
maxAbsorptionHours = SP.getDouble(R.string.key_absorption_maxtime, Constants.DEFAULT_MAX_ABSORPTION_TIME);
} else {
maxAbsorptionHours = SP.getDouble(R.string.key_absorption_cutoff, Constants.DEFAULT_MAX_ABSORPTION_TIME);
}
for (int i = 0; i < activeCarbsList.size(); i++) { for (int i = 0; i < activeCarbsList.size(); i++) {
CarbsInPast c = activeCarbsList.get(i); CarbsInPast c = activeCarbsList.get(i);
if (c.time + 4 * 60 * 60 * 1000L < toTime) { if (c.time + maxAbsorptionHours * 60 * 60 * 1000L < toTime) {
activeCarbsList.remove(i--); activeCarbsList.remove(i--);
if (c.remaining > 0) if (c.remaining > 0)
cob -= c.remaining; cob -= c.remaining;
log.debug("Removing carbs at "+ new Date(toTime).toLocaleString() + " + after 4h :" + new Date(c.time).toLocaleString()); log.debug("Removing carbs at " + new Date(toTime).toLocaleString() + " + after " + maxAbsorptionHours + "h :" + new Date(c.time).toLocaleString());
} }
} }
} }
@ -98,4 +116,52 @@ public class AutosensData {
} }
} }
// ------- DataPointWithLabelInterface ------
private Scale scale;
public void setScale(Scale scale) {
this.scale = scale;
}
@Override
public double getX() {
return chartTime;
}
@Override
public double getY() {
return scale.transform(cob);
}
@Override
public void setY(double y) {
}
@Override
public String getLabel() {
return null;
}
@Override
public long getDuration() {
return 0;
}
@Override
public PointsWithLabelGraphSeries.Shape getShape() {
return PointsWithLabelGraphSeries.Shape.COBFAILOVER;
}
@Override
public float getSize() {
return 0.5f;
}
@Override
public int getColor() {
return MainApp.gc(R.color.cob);
}
} }

View file

@ -0,0 +1,31 @@
package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import info.nightscout.utils.DecimalFormatter;
public class CobInfo {
/** All COB up to now, including carbs not yet processed by IobCob calculation. */
@Nullable
public final Double displayCob;
public final double futureCarbs;
public CobInfo(@Nullable Double displayCob, double futureCarbs) {
this.displayCob = displayCob;
this.futureCarbs = futureCarbs;
}
@NonNull
public String generateCOBString() {
String cobStringResult = "--g";
if (displayCob != null) {
cobStringResult = DecimalFormatter.to0Decimal(displayCob);
if (futureCarbs > 0) {
cobStringResult += "(" + DecimalFormatter.to0Decimal(futureCarbs) + ")";
}
cobStringResult += "g";
}
return cobStringResult;
}
}

View file

@ -1,6 +1,7 @@
package info.nightscout.androidaps.plugins.IobCobCalculator; package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.os.SystemClock; import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray; import android.support.v4.util.LongSparseArray;
@ -34,9 +35,12 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import static info.nightscout.utils.DateUtil.now;
/** /**
* Created by mike on 24.04.2017. * Created by mike on 24.04.2017.
*/ */
@ -74,7 +78,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
.neverVisible(true) .neverVisible(true)
.alwaysEnabled(true) .alwaysEnabled(true)
); );
} }
@Override @Override
protected void onStart() { protected void onStart() {
@ -309,7 +313,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
//log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString()); //log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
} }
IobTotal bolusIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTreatments(time).round(); IobTotal bolusIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTreatments(time).round();
IobTotal basalIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTempBasals(time, profile).round(); IobTotal basalIob = TreatmentsPlugin.getPlugin().getCalculationToTimeTempBasals(time, profile, true, now).round();
if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) { if (OpenAPSSMBPlugin.getPlugin().isEnabled(PluginType.APS)) {
// Add expected zero temp basal for next 240 mins // Add expected zero temp basal for next 240 mins
IobTotal basalIobWithZeroTemp = basalIob.copy(); IobTotal basalIobWithZeroTemp = basalIob.copy();
@ -322,7 +326,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
basalIobWithZeroTemp.plus(calc); basalIobWithZeroTemp.plus(calc);
} }
basalIob.iobWithZeroTemp = basalIobWithZeroTemp; basalIob.iobWithZeroTemp = IobTotal.combine(bolusIob, basalIobWithZeroTemp).round();
} }
IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round(); IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
@ -402,6 +406,33 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
@NonNull
public CobInfo getCobInfo(boolean _synchronized, String reason) {
AutosensData autosensData = _synchronized ? getLastAutosensDataSynchronized(reason) : getLastAutosensData(reason);
Double displayCob = null;
double futureCarbs = 0;
long now = now();
List<Treatment> treatments = TreatmentsPlugin.getPlugin().getTreatmentsFromHistory();
if (autosensData != null) {
displayCob = autosensData.cob;
for (Treatment treatment : treatments) {
if (!treatment.isValid) continue;
if (IobCobCalculatorPlugin.roundUpTime(treatment.date) > IobCobCalculatorPlugin.roundUpTime(autosensData.time)
&& treatment.date <= now && treatment.carbs > 0) {
displayCob += treatment.carbs;
}
}
}
for (Treatment treatment : treatments) {
if (!treatment.isValid) continue;
if (treatment.date > now && treatment.carbs > 0) {
futureCarbs += treatment.carbs;
}
}
return new CobInfo(displayCob, futureCarbs);
}
@Nullable @Nullable
public AutosensData getLastAutosensData(String reason) { public AutosensData getLastAutosensData(String reason) {
if (autosensDataTable.size() < 1) { if (autosensDataTable.size() < 1) {
@ -548,7 +579,9 @@ public class IobCobCalculatorPlugin extends PluginBase {
} }
if (ev.isChanged(R.string.key_openapsama_autosens_period) || if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
ev.isChanged(R.string.key_age) || ev.isChanged(R.string.key_age) ||
ev.isChanged(R.string.key_absorption_maxtime) ev.isChanged(R.string.key_absorption_maxtime) ||
ev.isChanged(R.string.key_openapsama_min_5m_carbimpact) ||
ev.isChanged(R.string.key_absorption_cutoff)
) { ) {
stopCalculation("onEventPreferenceChange"); stopCalculation("onEventPreferenceChange");
synchronized (dataLock) { synchronized (dataLock) {

View file

@ -17,15 +17,24 @@ import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.SensitivityAAPS.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.SensitivityWeightedAverage.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.SP;
import static info.nightscout.utils.DateUtil.now;
/** /**
* Created by mike on 23.01.2018. * Created by mike on 23.01.2018.
@ -69,28 +78,29 @@ public class IobCobThread extends Thread {
} }
//log.debug("Locking calculateSensitivityData"); //log.debug("Locking calculateSensitivityData");
Object dataLock = iobCobCalculatorPlugin.dataLock;
long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable(); long oldestTimeWithData = iobCobCalculatorPlugin.oldestDataAvailable();
synchronized (dataLock) { synchronized (iobCobCalculatorPlugin.dataLock) {
if (bgDataReload) { if (bgDataReload) {
iobCobCalculatorPlugin.loadBgData(start); iobCobCalculatorPlugin.loadBgData(start);
iobCobCalculatorPlugin.createBucketedData(); iobCobCalculatorPlugin.createBucketedData();
} }
List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData(); List<BgReading> bucketed_data = iobCobCalculatorPlugin.getBucketedData();
LongSparseArray<AutosensData> autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); LongSparseArray<AutosensData> autosensDataTable = IobCobCalculatorPlugin.getPlugin().getAutosensDataTable();
if (bucketed_data == null || bucketed_data.size() < 3) { if (bucketed_data == null || bucketed_data.size() < 3) {
log.debug("Aborting calculation thread (No bucketed data available): " + from); log.debug("Aborting calculation thread (No bucketed data available): " + from);
return; return;
} }
long prevDataTime = iobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date);
log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString()); log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString());
AutosensData previous = autosensDataTable.get(prevDataTime); AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob // start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) { for (int i = bucketed_data.size() - 4; i >= 0; i--) {
String progress = i + (MainApp.isDev() ? " (" + from + ")" : "");
MainApp.bus().post(new EventIobCalculationProgress(progress));
if (iobCobCalculatorPlugin.stopCalculationTrigger) { if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false; iobCobCalculatorPlugin.stopCalculationTrigger = false;
log.debug("Aborting calculation thread (trigger): " + from); log.debug("Aborting calculation thread (trigger): " + from);
@ -98,10 +108,9 @@ public class IobCobThread extends Thread {
} }
// check if data already exists // check if data already exists
long bgTime = bucketed_data.get(i).date; long bgTime = bucketed_data.get(i).date;
bgTime = iobCobCalculatorPlugin.roundUpTime(bgTime); bgTime = IobCobCalculatorPlugin.roundUpTime(bgTime);
if (bgTime > System.currentTimeMillis()) if (bgTime > IobCobCalculatorPlugin.roundUpTime(now()))
continue; continue;
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
AutosensData existing; AutosensData existing;
if ((existing = autosensDataTable.get(bgTime)) != null) { if ((existing = autosensDataTable.get(bgTime)) != null) {
@ -109,6 +118,7 @@ public class IobCobThread extends Thread {
continue; continue;
} }
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
if (profile == null) { if (profile == null) {
log.debug("Aborting calculation thread (no profile): " + from); log.debug("Aborting calculation thread (no profile): " + from);
return; // profile not set yet return; // profile not set yet
@ -152,7 +162,7 @@ public class IobCobThread extends Thread {
// https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169 // https://github.com/openaps/oref0/blob/master/lib/determine-basal/cob-autosens.js#L169
if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope if (i < bucketed_data.size() - 16) { // we need 1h of data to calculate minDeviationSlope
long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L; long hourago = bgTime + 10 * 1000 - 60 * 60 * 1000L;
AutosensData hourAgoData = iobCobCalculatorPlugin.getAutosensData(hourago); AutosensData hourAgoData = IobCobCalculatorPlugin.getPlugin().getAutosensData(hourago);
if (hourAgoData != null) { if (hourAgoData != null) {
int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time); int initialIndex = autosensDataTable.indexOfKey(hourAgoData.time);
if (Config.logAutosensData) if (Config.logAutosensData)
@ -199,18 +209,27 @@ public class IobCobThread extends Thread {
if (previous != null && previous.cob > 0) { if (previous != null && previous.cob > 0) {
// calculate sum of min carb impact from all active treatments // calculate sum of min carb impact from all active treatments
double totalMinCarbsImpact = 0d; double totalMinCarbsImpact = 0d;
for (int ii = 0; ii < autosensData.activeCarbsList.size(); ++ii) { if (SensitivityAAPSPlugin.getPlugin().isEnabled(PluginType.SENSITIVITY) || SensitivityWeightedAveragePlugin.getPlugin().isEnabled(PluginType.SENSITIVITY)) {
AutosensData.CarbsInPast c = autosensData.activeCarbsList.get(ii); //when the impact depends on a max time, sum them up as smaller carb sizes make them smaller
totalMinCarbsImpact += c.min5minCarbImpact; for (int ii = 0; ii < autosensData.activeCarbsList.size(); ++ii) {
AutosensData.CarbsInPast c = autosensData.activeCarbsList.get(ii);
totalMinCarbsImpact += c.min5minCarbImpact;
}
} else {
//Oref sensitivity
totalMinCarbsImpact = SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact);
} }
// figure out how many carbs that represents // figure out how many carbs that represents
// but always assume at least 3mg/dL/5m (default) absorption per active treatment // but always assume at least 3mg/dL/5m (default) absorption per active treatment
double ci = Math.max(deviation, totalMinCarbsImpact); double ci = Math.max(deviation, totalMinCarbsImpact);
if (ci != deviation)
autosensData.failoverToMinAbsorbtionRate = true;
autosensData.absorbed = ci * profile.getIc(bgTime) / sens; autosensData.absorbed = ci * profile.getIc(bgTime) / sens;
// and add that to the running total carbsAbsorbed // and add that to the running total carbsAbsorbed
autosensData.cob = Math.max(previous.cob - autosensData.absorbed, 0d); autosensData.cob = Math.max(previous.cob - autosensData.absorbed, 0d);
autosensData.substractAbosorbedCarbs(); autosensData.substractAbosorbedCarbs();
autosensData.usedMinCarbsImpact = totalMinCarbsImpact;
} }
autosensData.removeOldCarbs(bgTime); autosensData.removeOldCarbs(bgTime);
autosensData.cob += autosensData.carbsFromBolus; autosensData.cob += autosensData.carbsFromBolus;
@ -254,6 +273,7 @@ public class IobCobThread extends Thread {
log.debug("Finishing calculation thread: " + from); log.debug("Finishing calculation thread: " + from);
} finally { } finally {
mWakeLock.release(); mWakeLock.release();
MainApp.bus().post(new EventIobCalculationProgress(""));
} }
} }

View file

@ -0,0 +1,11 @@
package info.nightscout.androidaps.plugins.IobCobCalculator.events;
import info.nightscout.androidaps.events.Event;
public class EventIobCalculationProgress extends Event {
public String progress;
public EventIobCalculationProgress(String progress) {
this.progress = progress;
}
}

View file

@ -52,23 +52,23 @@ public class APSResult {
String ret; String ret;
// rate // rate
if (rate == 0 && duration == 0) if (rate == 0 && duration == 0)
ret = MainApp.sResources.getString(R.string.canceltemp) + "\n"; ret = MainApp.gs(R.string.canceltemp) + "\n";
else if (rate == -1) else if (rate == -1)
ret = MainApp.sResources.getString(R.string.let_temp_basal_run) + "\n"; ret = MainApp.gs(R.string.let_temp_basal_run) + "\n";
else else
ret = MainApp.sResources.getString(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " + ret = MainApp.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) \n" + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) \n" +
MainApp.sResources.getString(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n"; MainApp.gs(R.string.duration) + ": " + DecimalFormatter.to2Decimal(duration) + " min\n";
// smb // smb
if (smb != 0) if (smb != 0)
ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U\n"); ret += ("SMB: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U\n");
// reason // reason
ret += MainApp.sResources.getString(R.string.reason) + ": " + reason; ret += MainApp.gs(R.string.reason) + ": " + reason;
return ret; return ret;
} else } else
return MainApp.sResources.getString(R.string.nochangerequested); return MainApp.gs(R.string.nochangerequested);
} }
public Spanned toSpanned() { public Spanned toSpanned() {
@ -77,23 +77,23 @@ public class APSResult {
String ret; String ret;
// rate // rate
if (rate == 0 && duration == 0) if (rate == 0 && duration == 0)
ret = MainApp.sResources.getString(R.string.canceltemp) + "<br>"; ret = MainApp.gs(R.string.canceltemp) + "<br>";
else if (rate == -1) else if (rate == -1)
ret = MainApp.sResources.getString(R.string.let_temp_basal_run) + "<br>"; ret = MainApp.gs(R.string.let_temp_basal_run) + "<br>";
else else
ret = "<b>" + MainApp.sResources.getString(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " + ret = "<b>" + MainApp.gs(R.string.rate) + "</b>: " + DecimalFormatter.to2Decimal(rate) + " U/h " +
"(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) <br>" + "(" + DecimalFormatter.to2Decimal(rate / pump.getBaseBasalRate() * 100) + "%) <br>" +
"<b>" + MainApp.sResources.getString(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>"; "<b>" + MainApp.gs(R.string.duration) + "</b>: " + DecimalFormatter.to2Decimal(duration) + " min<br>";
// smb // smb
if (smb != 0) if (smb != 0)
ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U<br>"); ret += ("<b>" + "SMB" + "</b>: " + DecimalFormatter.toPumpSupportedBolus(smb) + " U<br>");
// reason // reason
ret += "<b>" + MainApp.sResources.getString(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;"); ret += "<b>" + MainApp.gs(R.string.reason) + "</b>: " + reason.replace("<", "&lt;").replace(">", "&gt;");
return Html.fromHtml(ret); return Html.fromHtml(ret);
} else } else
return Html.fromHtml(MainApp.sResources.getString(R.string.nochangerequested)); return Html.fromHtml(MainApp.gs(R.string.nochangerequested));
} }
public APSResult() { public APSResult() {

View file

@ -65,7 +65,7 @@ public class LoopFragment extends SubscriberFragment {
@OnClick(R.id.loop_run) @OnClick(R.id.loop_run)
void onRunClick() { void onRunClick() {
lastRunView.setText(MainApp.sResources.getString(R.string.executing)); lastRunView.setText(MainApp.gs(R.string.executing));
new Thread(() -> LoopPlugin.getPlugin().invoke("Loop button", true)).start(); new Thread(() -> LoopPlugin.getPlugin().invoke("Loop button", true)).start();
FabricPrivacy.getInstance().logCustom(new CustomEvent("Loop_Run")); FabricPrivacy.getInstance().logCustom(new CustomEvent("Loop_Run"));
} }

View file

@ -9,6 +9,7 @@ import android.app.TaskStackBuilder;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.os.Build; import android.os.Build;
import android.os.SystemClock;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationCompat;
@ -27,6 +28,9 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
@ -54,6 +58,7 @@ public class LoopPlugin extends PluginBase {
public static final String CHANNEL_ID = "AndroidAPS-Openloop"; public static final String CHANNEL_ID = "AndroidAPS-Openloop";
long lastBgTriggeredRun = 0;
protected static LoopPlugin loopPlugin; protected static LoopPlugin loopPlugin;
@ -126,18 +131,33 @@ public class LoopPlugin extends PluginBase {
return pump == null || pump.getPumpDescription().isTempBasalCapable; return pump == null || pump.getPumpDescription().isTempBasalCapable;
} }
@Subscribe /**
public void onStatusEvent(final EventTreatmentChange ev) { * This method is triggered once autosens calculation has completed, so the LoopPlugin
if (ev.treatment == null || !ev.treatment.isSMB) { * has current data to work with. However, autosens calculation can be triggered by multiple
invoke("EventTreatmentChange", true); * 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.
*/
@Subscribe @Subscribe
public void onStatusEvent(final EventAutosensCalculationFinished ev) { public void onStatusEvent(final EventAutosensCalculationFinished ev) {
if (ev.cause instanceof EventNewBG) { if (!(ev.cause instanceof EventNewBG)) {
invoke(ev.getClass().getSimpleName() + "(" + ev.cause.getClass().getSimpleName() + ")", true); // Autosens calculation not triggered by a new BG
return;
} }
BgReading bgReading = DatabaseHelper.actualBg();
if (bgReading == null) {
// BG outdated
return;
}
if (bgReading.date <= lastBgTriggeredRun) {
// already looped with that value
return;
}
lastBgTriggeredRun = bgReading.date;
invoke("AutosenseCalculation for " + bgReading, true);
} }
public long suspendedTo() { public long suspendedTo() {
@ -227,14 +247,18 @@ public class LoopPlugin extends PluginBase {
return isDisconnected; return isDisconnected;
} }
public 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 { try {
if (Config.logFunctionCalls) if (Config.logFunctionCalls)
log.debug("invoke from " + initiator); log.debug("invoke from " + initiator);
Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed(); Constraint<Boolean> loopEnabled = MainApp.getConstraintChecker().isLoopInvokationAllowed();
if (!loopEnabled.value()) { if (!loopEnabled.value()) {
String message = MainApp.sResources.getString(R.string.loopdisabled) + "\n" + loopEnabled.getReasons(); String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
log.debug(message); log.debug(message);
MainApp.bus().post(new EventLoopSetLastRunGui(message)); MainApp.bus().post(new EventLoopSetLastRunGui(message));
return; return;
@ -248,8 +272,8 @@ public class LoopPlugin extends PluginBase {
Profile profile = MainApp.getConfigBuilder().getProfile(); Profile profile = MainApp.getConfigBuilder().getProfile();
if (!MainApp.getConfigBuilder().isProfileValid("Loop")) { if (!MainApp.getConfigBuilder().isProfileValid("Loop")) {
log.debug(MainApp.sResources.getString(R.string.noprofileselected)); log.debug(MainApp.gs(R.string.noprofileselected));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.noprofileselected))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return; return;
} }
@ -258,13 +282,13 @@ public class LoopPlugin extends PluginBase {
APSInterface usedAPS = ConfigBuilderPlugin.getActiveAPS(); APSInterface usedAPS = ConfigBuilderPlugin.getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) { if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS)) {
usedAPS.invoke(initiator); usedAPS.invoke(initiator, tempBasalFallback);
result = usedAPS.getLastAPSResult(); result = usedAPS.getLastAPSResult();
} }
// Check if we have any result // Check if we have any result
if (result == null) { if (result == null) {
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.noapsselected))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
return; return;
} }
@ -293,14 +317,14 @@ public class LoopPlugin extends PluginBase {
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
if (isSuspended()) { if (isSuspended()) {
log.debug(MainApp.sResources.getString(R.string.loopsuspended)); log.debug(MainApp.gs(R.string.loopsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.loopsuspended))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return; return;
} }
if (pump.isSuspended()) { if (pump.isSuspended()) {
log.debug(MainApp.sResources.getString(R.string.pumpsuspended)); log.debug(MainApp.gs(R.string.pumpsuspended));
MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.sResources.getString(R.string.pumpsuspended))); MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return; return;
} }
@ -322,16 +346,23 @@ public class LoopPlugin extends PluginBase {
if (result.enacted || result.success) { if (result.enacted || result.success) {
lastRun.tbrSetByPump = result; lastRun.tbrSetByPump = result;
lastRun.lastEnact = lastRun.lastAPSRun; lastRun.lastEnact = lastRun.lastAPSRun;
} MainApp.getConfigBuilder().applySMBRequest(resultAfterConstraints, new Callback() {
MainApp.bus().post(new EventLoopUpdateGui()); @Override
} public void run() {
}); //Callback is only called if a bolus was acutally requested
MainApp.getConfigBuilder().applySMBRequest(resultAfterConstraints, new Callback() { if (result.enacted || result.success) {
@Override lastRun.smbSetByPump = result;
public void run() { lastRun.lastEnact = lastRun.lastAPSRun;
if (result.enacted || result.success) { } else {
lastRun.smbSetByPump = result; new Thread(() -> {
lastRun.lastEnact = lastRun.lastAPSRun; SystemClock.sleep(1000);
LoopPlugin.getPlugin().invoke("tempBasalFallback", allowNotification, true);
}).start();
FabricPrivacy.getInstance().logCustom(new CustomEvent("Loop_Run_TempBasalFallback"));
}
MainApp.bus().post(new EventLoopUpdateGui());
}
});
} }
MainApp.bus().post(new EventLoopUpdateGui()); MainApp.bus().post(new EventLoopUpdateGui());
} }
@ -345,7 +376,7 @@ public class LoopPlugin extends PluginBase {
NotificationCompat.Builder builder = NotificationCompat.Builder builder =
new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID); new NotificationCompat.Builder(MainApp.instance().getApplicationContext(), CHANNEL_ID);
builder.setSmallIcon(R.drawable.notif_icon) builder.setSmallIcon(R.drawable.notif_icon)
.setContentTitle(MainApp.sResources.getString(R.string.openloop_newsuggestion)) .setContentTitle(MainApp.gs(R.string.openloop_newsuggestion))
.setContentText(resultAfterConstraints.toString()) .setContentText(resultAfterConstraints.toString())
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH) .setPriority(Notification.PRIORITY_HIGH)

View file

@ -110,16 +110,16 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
final Context context = getContext(); final Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(this.getContext().getString(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage("Clear queue? All data in queue will be lost!"); builder.setMessage("Clear queue? All data in queue will be lost!");
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
UploadQueue.clearQueue(); UploadQueue.clearQueue();
updateGUI(); updateGUI();
FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientClearQueue")); FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientClearQueue"));
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
break; break;
case R.id.nsclientinternal_showqueue: case R.id.nsclientinternal_showqueue:
@ -165,7 +165,7 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
logScrollview.fullScroll(ScrollView.FOCUS_DOWN); logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
} }
urlTextView.setText(NSClientPlugin.getPlugin().url()); urlTextView.setText(NSClientPlugin.getPlugin().url());
Spanned queuetext = Html.fromHtml(MainApp.sResources.getString(R.string.queue) + " <b>" + UploadQueue.size() + "</b>"); Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " <b>" + UploadQueue.size() + "</b>");
queueTextView.setText(queuetext); queueTextView.setText(queuetext);
statusTextView.setText(NSClientPlugin.getPlugin().status); statusTextView.setText(NSClientPlugin.getPlugin().status);
} }

View file

@ -18,12 +18,14 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventChargingState;
import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
@ -58,7 +60,9 @@ public class NSClientPlugin extends PluginBase {
public NSClientService nsClientService = null; public NSClientService nsClientService = null;
public NSClientPlugin() { private NsClientReceiverDelegate nsClientReceiverDelegate;
private NSClientPlugin() {
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.GENERAL) .mainType(PluginType.GENERAL)
.fragmentClass(NSClientFragment.class.getName()) .fragmentClass(NSClientFragment.class.getName())
@ -78,8 +82,16 @@ public class NSClientPlugin extends PluginBase {
handlerThread.start(); handlerThread.start();
handler = new Handler(handlerThread.getLooper()); handler = new Handler(handlerThread.getLooper());
} }
nsClientReceiverDelegate =
new NsClientReceiverDelegate(MainApp.instance().getApplicationContext(), MainApp.bus());
} }
public boolean isAllowed() {
return nsClientReceiverDelegate.allowed;
}
@Override @Override
protected void onStart() { protected void onStart() {
MainApp.bus().register(this); MainApp.bus().register(this);
@ -87,6 +99,8 @@ public class NSClientPlugin extends PluginBase {
Intent intent = new Intent(context, NSClientService.class); Intent intent = new Intent(context, NSClientService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
super.onStart(); super.onStart();
nsClientReceiverDelegate.registerReceivers();
} }
@Override @Override
@ -94,8 +108,26 @@ public class NSClientPlugin extends PluginBase {
MainApp.bus().unregister(this); MainApp.bus().unregister(this);
Context context = MainApp.instance().getApplicationContext(); Context context = MainApp.instance().getApplicationContext();
context.unbindService(mConnection); context.unbindService(mConnection);
nsClientReceiverDelegate.unregisterReceivers();
} }
@Subscribe
public void onStatusEvent(EventPreferenceChange ev) {
nsClientReceiverDelegate.onStatusEvent(ev);
}
@Subscribe
public void onStatusEvent(final EventChargingState ev) {
nsClientReceiverDelegate.onStatusEvent(ev);
}
@Subscribe
public void onStatusEvent(final EventNetworkChange ev) {
nsClientReceiverDelegate.onStatusEvent(ev);
}
private ServiceConnection mConnection = new ServiceConnection() { private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
@ -111,11 +143,12 @@ public class NSClientPlugin extends PluginBase {
} }
}; };
@SuppressWarnings("UnusedParameters")
@Subscribe @Subscribe
public void onStatusEvent(final EventAppExit e) { public void onStatusEvent(final EventAppExit ignored) {
if (nsClientService != null) if (nsClientService != null) {
MainApp.instance().getApplicationContext().unbindService(mConnection); MainApp.instance().getApplicationContext().unbindService(mConnection);
nsClientReceiverDelegate.unregisterReceivers();
}
} }
@Subscribe @Subscribe

View file

@ -0,0 +1,138 @@
package info.nightscout.androidaps.plugins.NSClientInternal;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import com.squareup.otto.Bus;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventChargingState;
import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.receivers.ChargingStateReceiver;
import info.nightscout.androidaps.receivers.NetworkChangeReceiver;
import info.nightscout.utils.SP;
class NsClientReceiverDelegate {
private final Context context;
private final Bus bus;
private NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
private ChargingStateReceiver chargingStateReceiver = new ChargingStateReceiver();
private boolean allowedChargingState = true;
private boolean allowedNetworkState = true;
boolean allowed = true;
NsClientReceiverDelegate(Context context, Bus bus) {
this.context = context;
this.bus = bus;
}
void registerReceivers() {
Context context = MainApp.instance().getApplicationContext();
// register NetworkChangeReceiver --> https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
// Nougat is not providing Connectivity-Action anymore ;-(
context.registerReceiver(networkChangeReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
context.registerReceiver(networkChangeReceiver,
new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(context);
if (event != null)
bus.post(event);
context.registerReceiver(chargingStateReceiver,
new IntentFilter(Intent.ACTION_POWER_CONNECTED));
context.registerReceiver(chargingStateReceiver,
new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
EventChargingState eventChargingState = chargingStateReceiver.grabChargingState(context);
if (eventChargingState != null)
bus.post(eventChargingState);
}
void unregisterReceivers() {
context.unregisterReceiver(networkChangeReceiver);
context.unregisterReceiver(chargingStateReceiver);
}
void onStatusEvent(EventPreferenceChange ev) {
if (ev.isChanged(R.string.key_ns_wifionly) ||
ev.isChanged(R.string.key_ns_wifi_ssids) ||
ev.isChanged(R.string.key_ns_allowroaming)
) {
EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext());
if (event != null)
bus.post(event);
} else if (ev.isChanged(R.string.key_ns_chargingonly)) {
EventChargingState event = chargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext());
if (event != null)
bus.post(event);
}
}
void onStatusEvent(final EventChargingState ev) {
boolean newChargingState = calculateStatus(ev);
if (newChargingState != allowedChargingState) {
allowedChargingState = newChargingState;
processStateChange();
}
}
void onStatusEvent(final EventNetworkChange ev) {
boolean newNetworkState = calculateStatus(ev);
if (newNetworkState != allowedNetworkState) {
allowedNetworkState = newNetworkState;
processStateChange();
}
}
void processStateChange() {
boolean newAllowedState = allowedChargingState && allowedNetworkState;
if (newAllowedState != allowed) {
allowed = newAllowedState;
bus.post(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
}
}
boolean calculateStatus(final EventChargingState ev) {
boolean chargingOnly = SP.getBoolean(R.string.key_ns_chargingonly, false);
boolean newAllowedState = true;
if (!ev.isCharging && chargingOnly) newAllowedState = false;
return newAllowedState;
}
boolean calculateStatus(final EventNetworkChange ev) {
boolean wifiOnly = SP.getBoolean(R.string.key_ns_wifionly, false);
String allowedSSIDs = SP.getString(R.string.key_ns_wifi_ssids, "");
boolean allowRoaming = SP.getBoolean(R.string.key_ns_allowroaming, true);
boolean newAllowedState = true;
if (ev.wifiConnected) {
if (!allowedSSIDs.trim().isEmpty() && !allowedSSIDs.contains(ev.ssid)) {
newAllowedState = false;
}
} else {
if ((!allowRoaming && ev.roaming) || wifiOnly) {
newAllowedState = false;
}
}
return newAllowedState;
}
}

View file

@ -22,7 +22,7 @@ public class DbLogger {
public static void dbAdd(Intent intent, String data) { public static void dbAdd(Intent intent, String data) {
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0);
if (q.size() < 1) { if (q.size() < 1) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.sResources.getString(R.string.nsclientnotinstalled)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.gs(R.string.nsclientnotinstalled));
log.error("DBADD No receivers"); log.error("DBADD No receivers");
} else if (Config.logNSUpload) } else if (Config.logNSUpload)
log.debug("DBADD dbAdd " + q.size() + " receivers " + data); log.debug("DBADD dbAdd " + q.size() + " receivers " + data);
@ -31,7 +31,7 @@ public class DbLogger {
public static void dbRemove(Intent intent, String data) { public static void dbRemove(Intent intent, String data) {
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0); List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(intent, 0);
if (q.size() < 1) { if (q.size() < 1) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.sResources.getString(R.string.nsclientnotinstalled)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(),MainApp.gs(R.string.nsclientnotinstalled));
log.error("DBREMOVE No receivers"); log.error("DBREMOVE No receivers");
} else if (Config.logNSUpload) } else if (Config.logNSUpload)
log.debug("DBREMOVE dbRemove " + q.size() + " receivers " + data); log.debug("DBREMOVE dbRemove " + q.size() + " receivers " + data);

View file

@ -33,7 +33,6 @@ import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue; import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
@ -203,7 +202,10 @@ public class NSClientService extends Service {
nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString();
MainApp.bus().post(new EventNSClientStatus("Initializing")); MainApp.bus().post(new EventNSClientStatus("Initializing"));
if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) { if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "not allowed"));
MainApp.bus().post(new EventNSClientStatus("Not allowed"));
} else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) {
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused")); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused"));
MainApp.bus().post(new EventNSClientStatus("Paused")); MainApp.bus().post(new EventNSClientStatus("Paused"));
} else if (!nsEnabled) { } else if (!nsEnabled) {
@ -248,6 +250,7 @@ public class NSClientService extends Service {
private Emitter.Listener onDisconnect = new Emitter.Listener() { private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override @Override
public void call(Object... args) { public void call(Object... args) {
log.debug("disconnect reason: {}", args);
MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event")); MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
} }
}; };
@ -306,7 +309,7 @@ public class NSClientService extends Service {
MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!")); MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!"));
} }
if (!hasWriteAuth) { if (!hasWriteAuth) {
Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.sResources.getString(R.string.nowritepermission), Notification.URGENT); Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(noperm)); MainApp.bus().post(new EventNewNotification(noperm));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)); MainApp.bus().post(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
@ -652,7 +655,7 @@ public class NSClientService extends Service {
} }
//MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); //MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
} finally { } finally {
if (wakeLock.isHeld()) wakeLock.release(); if (wakeLock.isHeld()) wakeLock.release();
} }
} }

View file

@ -212,9 +212,13 @@ public class DetermineBasalAdapterAMAJS {
mProfile.put("skip_neutral_temps", true); mProfile.put("skip_neutral_temps", true);
mProfile.put("current_basal", basalrate); mProfile.put("current_basal", basalrate);
mProfile.put("temptargetSet", tempTargetSet); mProfile.put("temptargetSet", tempTargetSet);
mProfile.put("autosens_adjust_targets", SP.getBoolean("openapsama_autosens_adjusttargets", true)); mProfile.put("autosens_adjust_targets", SP.getBoolean(R.string.key_openapsama_autosens_adjusttargets, true));
//TODO: align with max-absorption model in AMA sensitivity //align with max-absorption model in AMA sensitivity
mProfile.put("min_5m_carbimpact", SP.getDouble("openapsama_min_5m_carbimpact", SMBDefaults.min_5m_carbimpact)); 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));
}
if (units.equals(Constants.MMOL)) { if (units.equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L"); mProfile.put("out_units", "mmol/L");
@ -239,7 +243,7 @@ public class DetermineBasalAdapterAMAJS {
mGlucoseStatus = new JSONObject(); mGlucoseStatus = new JSONObject();
mGlucoseStatus.put("glucose", glucoseStatus.glucose); mGlucoseStatus.put("glucose", glucoseStatus.glucose);
if (SP.getBoolean("always_use_shortavg", false)) { if (SP.getBoolean(R.string.key_always_use_shortavg, false)) {
mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta); mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta);
} else { } else {
mGlucoseStatus.put("delta", glucoseStatus.delta); mGlucoseStatus.put("delta", glucoseStatus.delta);

View file

@ -72,7 +72,7 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli
public void onClick(View view) { public void onClick(View view) {
switch (view.getId()) { switch (view.getId()) {
case R.id.openapsma_run: case R.id.openapsma_run:
OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button"); OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button", false);
FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_AMA_Run")); FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_AMA_Run"));
break; break;
} }
@ -107,7 +107,7 @@ public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnCli
currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam())); currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam()));
try { try {
JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam()); JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam());
iobDataView.setText(String.format(MainApp.sResources.getString(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))); iobDataView.setText(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0)));
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
iobDataView.setText("JSONException"); iobDataView.setText("JSONException");

View file

@ -88,8 +88,8 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
} }
@Override @Override
public void invoke(String initiator) { public void invoke(String initiator, boolean tempBasalFallback) {
log.debug("invoke from " + initiator); log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS; DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS;
try { try {
@ -104,23 +104,23 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getActivePump(); PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (profile == null) { if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.noprofileselected))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.noprofileselected)); log.debug(MainApp.gs(R.string.noprofileselected));
return; return;
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_disabled))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_disabled)); log.debug(MainApp.gs(R.string.openapsma_disabled));
return; return;
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noglucosedata))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return; return;
} }

View file

@ -18,6 +18,7 @@ import java.lang.reflect.InvocationTargetException;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
@ -197,7 +198,7 @@ public class DetermineBasalAdapterMAJS {
mGlucoseStatus = new JSONObject(); mGlucoseStatus = new JSONObject();
mGlucoseStatus.put("glucose", glucoseStatus.glucose); mGlucoseStatus.put("glucose", glucoseStatus.glucose);
if (SP.getBoolean("always_use_shortavg", false)) { if (SP.getBoolean(R.string.key_always_use_shortavg, false)) {
mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta); mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta);
} else { } else {
mGlucoseStatus.put("delta", glucoseStatus.delta); mGlucoseStatus.put("delta", glucoseStatus.delta);

View file

@ -66,7 +66,7 @@ public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClic
public void onClick(View view) { public void onClick(View view) {
switch (view.getId()) { switch (view.getId()) {
case R.id.openapsma_run: case R.id.openapsma_run:
OpenAPSMAPlugin.getPlugin().invoke("OpenAPSMA button"); OpenAPSMAPlugin.getPlugin().invoke("OpenAPSMA button", false);
FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_MA_Run")); FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_MA_Run"));
break; break;
} }

View file

@ -88,8 +88,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
} }
@Override @Override
public void invoke(String initiator) { public void invoke(String initiator, boolean tempBasalFallback) {
log.debug("invoke from " + initiator); log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null; DetermineBasalAdapterMAJS determineBasalAdapterMAJS = null;
try { try {
@ -104,23 +104,23 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getActivePump(); PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (profile == null) { if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.noprofileselected))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.noprofileselected)); log.debug(MainApp.gs(R.string.noprofileselected));
return; return;
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_disabled))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_disabled)); log.debug(MainApp.gs(R.string.openapsma_disabled));
return; return;
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noglucosedata))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return; return;
} }

View file

@ -214,7 +214,7 @@ public class DetermineBasalAdapterSMBJS {
double autosensDataRatio, double autosensDataRatio,
boolean tempTargetSet, boolean tempTargetSet,
boolean microBolusAllowed, boolean microBolusAllowed,
boolean smbAlwaysAllowed boolean advancedFiltering
) throws JSONException { ) throws JSONException {
String units = profile.getUnits(); String units = profile.getUnits();
@ -243,23 +243,26 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target); mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target);
mProfile.put("maxCOB", SMBDefaults.maxCOB); mProfile.put("maxCOB", SMBDefaults.maxCOB);
mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps); mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps);
//TODO: align with max-absorption model in AMA sensitivity //align with max-absorption model in AMA sensitivity
mProfile.put("min_5m_carbimpact", SP.getDouble("openapsama_min_5m_carbimpact", SMBDefaults.min_5m_carbimpact)); 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));
}
mProfile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap); mProfile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap);
mProfile.put("enableUAM", SP.getBoolean(R.string.key_use_uam, false)); mProfile.put("enableUAM", SP.getBoolean(R.string.key_use_uam, false)&& advancedFiltering);
mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable); mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable);
mProfile.put("enableSMB_with_COB", SP.getBoolean(R.string.key_enableSMB_with_COB, false)); mProfile.put("enableSMB_with_COB", SP.getBoolean(R.string.key_enableSMB_with_COB, false));
mProfile.put("enableSMB_with_temptarget", SP.getBoolean(R.string.key_enableSMB_with_temptarget, false)); mProfile.put("enableSMB_with_temptarget", SP.getBoolean(R.string.key_enableSMB_with_temptarget, false));
mProfile.put("allowSMB_with_high_temptarget", SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false)); mProfile.put("allowSMB_with_high_temptarget", SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false));
mProfile.put("enableSMB_always", SP.getBoolean(R.string.key_enableSMB_always, false) && smbAlwaysAllowed); mProfile.put("enableSMB_always", SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering);
mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && smbAlwaysAllowed); mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering);
mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes));
mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold);
mProfile.put("current_basal", basalrate); mProfile.put("current_basal", basalrate);
mProfile.put("temptargetSet", tempTargetSet); mProfile.put("temptargetSet", tempTargetSet);
mProfile.put("autosens_max", SafeParse.stringToDouble(SP.getString("openapsama_autosens_max", "1.2"))); mProfile.put("autosens_max", SafeParse.stringToDouble(SP.getString(R.string.key_openapsama_autosens_max, "1.2")));
if (units.equals(Constants.MMOL)) { if (units.equals(Constants.MMOL)) {
mProfile.put("out_units", "mmol/L"); mProfile.put("out_units", "mmol/L");
@ -285,7 +288,7 @@ public class DetermineBasalAdapterSMBJS {
mGlucoseStatus = new JSONObject(); mGlucoseStatus = new JSONObject();
mGlucoseStatus.put("glucose", glucoseStatus.glucose); mGlucoseStatus.put("glucose", glucoseStatus.glucose);
if (SP.getBoolean("always_use_shortavg", false)) { if (SP.getBoolean(R.string.key_always_use_shortavg, false)) {
mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta); mGlucoseStatus.put("delta", glucoseStatus.short_avgdelta);
} else { } else {
mGlucoseStatus.put("delta", glucoseStatus.delta); mGlucoseStatus.put("delta", glucoseStatus.delta);
@ -312,7 +315,7 @@ public class DetermineBasalAdapterSMBJS {
mAutosensData.put("ratio", 1.0); mAutosensData.put("ratio", 1.0);
} }
mMicrobolusAllowed = microBolusAllowed; mMicrobolusAllowed = microBolusAllowed;
mSMBAlwaysAllowed = smbAlwaysAllowed; mSMBAlwaysAllowed = advancedFiltering;
} }

View file

@ -66,7 +66,7 @@ public class OpenAPSSMBFragment extends SubscriberFragment {
@OnClick(R.id.openapsma_run) @OnClick(R.id.openapsma_run)
public void onRunClick() { public void onRunClick() {
OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button"); OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button", false);
FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_SMB_Run")); FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_SMB_Run"));
} }
@ -99,7 +99,7 @@ public class OpenAPSSMBFragment extends SubscriberFragment {
currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim()); currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim());
try { try {
JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam()); JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam());
iobDataView.setText((String.format(MainApp.sResources.getString(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim()); iobDataView.setText((String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim());
} catch (JSONException e) { } catch (JSONException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
iobDataView.setText("JSONException see log for details"); iobDataView.setText("JSONException see log for details");

View file

@ -91,8 +91,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
} }
@Override @Override
public void invoke(String initiator) { public void invoke(String initiator, boolean tempBasalFallback) {
log.debug("invoke from " + initiator); log.debug("invoke from " + initiator + " tempBasalFallback: " + tempBasalFallback);
lastAPSResult = null; lastAPSResult = null;
DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = null; DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = null;
try { try {
@ -107,23 +107,23 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getActivePump(); PumpInterface pump = ConfigBuilderPlugin.getActivePump();
if (profile == null) { if (profile == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.noprofileselected))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.noprofileselected)); log.debug(MainApp.gs(R.string.noprofileselected));
return; return;
} }
if (!isEnabled(PluginType.APS)) { if (!isEnabled(PluginType.APS)) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_disabled))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_disabled)); log.debug(MainApp.gs(R.string.openapsma_disabled));
return; return;
} }
if (glucoseStatus == null) { if (glucoseStatus == null) {
MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.instance().getString(R.string.openapsma_noglucosedata))); MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (Config.logAPSResult) if (Config.logAPSResult)
log.debug(MainApp.instance().getString(R.string.openapsma_noglucosedata)); log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return; return;
} }
@ -184,13 +184,13 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
lastAutosensResult = new AutosensResult(); lastAutosensResult = new AutosensResult();
} }
Constraint<Boolean> smbAllowed = new Constraint<>(true); Constraint<Boolean> smbAllowed = new Constraint<>(!tempBasalFallback);
MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed); MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed);
inputConstraints.copyReasons(smbAllowed); inputConstraints.copyReasons(smbAllowed);
Constraint<Boolean> smbAlwaysEnabled = new Constraint<>(true); Constraint<Boolean> advancedFiltering = new Constraint<>(!tempBasalFallback);
MainApp.getConstraintChecker().isAdvancedFilteringEnabled(smbAlwaysEnabled); MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering);
inputConstraints.copyReasons(smbAlwaysEnabled); inputConstraints.copyReasons(advancedFiltering);
Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
Profiler.log(log, "SMB data gathering", start); Profiler.log(log, "SMB data gathering", start);
@ -201,7 +201,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
lastAutosensResult.ratio, //autosensDataRatio lastAutosensResult.ratio, //autosensDataRatio
isTempTarget, isTempTarget,
smbAllowed.value(), smbAllowed.value(),
smbAlwaysEnabled.value() advancedFiltering.value()
); );
} catch (JSONException e) { } catch (JSONException e) {
log.error(e.getMessage()); log.error(e.getMessage());
@ -255,9 +255,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (newvalue < lowLimit || newvalue > highLimit) { if (newvalue < lowLimit || newvalue > highLimit) {
newvalue = Math.max(newvalue, lowLimit); newvalue = Math.max(newvalue, lowLimit);
newvalue = Math.min(newvalue, highLimit); newvalue = Math.min(newvalue, highLimit);
String msg = String.format(MainApp.sResources.getString(R.string.valueoutofrange), valueName); String msg = String.format(MainApp.gs(R.string.valueoutofrange), valueName);
msg += ".\n"; msg += ".\n";
msg += String.format(MainApp.sResources.getString(R.string.valuelimitedto), value, newvalue); msg += String.format(MainApp.gs(R.string.valuelimitedto), value, newvalue);
log.error(msg); log.error(msg);
NSUpload.uploadError(msg); NSUpload.uploadError(msg);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), msg, R.raw.error);

View file

@ -42,7 +42,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
} }
public void setInsulin(double amount) { public void setInsulin(double amount) {
this.amount = amount; BolusProgressDialog.amount = amount;
bolusEnded = false; bolusEnded = false;
} }
@ -53,15 +53,15 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
getDialog().setTitle(String.format(MainApp.sResources.getString(R.string.overview_bolusprogress_goingtodeliver), amount)); getDialog().setTitle(String.format(MainApp.gs(R.string.overview_bolusprogress_goingtodeliver), amount));
View view = inflater.inflate(R.layout.overview_bolusprogress_dialog, container, false); View view = inflater.inflate(R.layout.overview_bolusprogress_dialog, container, false);
stopButton = (Button) view.findViewById(R.id.overview_bolusprogress_stop); stopButton = view.findViewById(R.id.overview_bolusprogress_stop);
statusView = (TextView) view.findViewById(R.id.overview_bolusprogress_status); statusView = view.findViewById(R.id.overview_bolusprogress_status);
stopPressedView = (TextView) view.findViewById(R.id.overview_bolusprogress_stoppressed); stopPressedView = view.findViewById(R.id.overview_bolusprogress_stoppressed);
progressBar = (ProgressBar) view.findViewById(R.id.overview_bolusprogress_progressbar); progressBar = view.findViewById(R.id.overview_bolusprogress_progressbar);
stopButton.setOnClickListener(this); stopButton.setOnClickListener(this);
progressBar.setMax(100); progressBar.setMax(100);
statusView.setText(MainApp.sResources.getString(R.string.waitingforpump)); statusView.setText(MainApp.gs(R.string.waitingforpump));
setCancelable(false); setCancelable(false);
stopPressed = false; stopPressed = false;
return view; return view;
@ -70,16 +70,25 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
@Override @Override
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
if (getDialog() != null) if (bolusEnded) {
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); dismiss();
MainApp.bus().register(this); } else {
running = true; if (getDialog() != null)
if (bolusEnded) dismiss(); getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
MainApp.subscribe(this);
running = true;
}
} }
@Override @Override
public void dismiss() { public void dismiss() {
super.dismiss(); try {
super.dismiss();
} catch (IllegalStateException e) {
// dialog not running yet. onResume will try again. Set bolusEnded to make extra
// sure onResume will catch this
bolusEnded = true;
}
if (helperActivity != null) { if (helperActivity != null) {
helperActivity.finish(); helperActivity.finish();
} }
@ -88,7 +97,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
@Override @Override
public void onPause() { public void onPause() {
super.onPause(); super.onPause();
MainApp.bus().unregister(this); MainApp.unsubscribe(this);
running = false; running = false;
} }
@ -109,16 +118,13 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
public void onStatusEvent(final EventOverviewBolusProgress ev) { public void onStatusEvent(final EventOverviewBolusProgress ev) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override log.debug("Status: " + ev.status + " Percent: " + ev.percent);
public void run() { statusView.setText(ev.status);
log.debug("Status: " + ev.status + " Percent: " + ev.percent); progressBar.setProgress(ev.percent);
statusView.setText(ev.status); if (ev.percent == 100) {
progressBar.setProgress(ev.percent); stopButton.setVisibility(View.INVISIBLE);
if (ev.percent == 100) { scheduleDismiss();
stopButton.setVisibility(View.INVISIBLE);
scheduleDismiss();
}
} }
}); });
} }
@ -133,41 +139,25 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
@Subscribe @Subscribe
public void onStatusEvent(final EventPumpStatusChanged c) { public void onStatusEvent(final EventPumpStatusChanged c) {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread( activity.runOnUiThread(() -> statusView.setText(c.textStatus()));
new Runnable() {
@Override
public void run() {
statusView.setText(c.textStatus());
}
}
);
} }
} }
private void scheduleDismiss() { private void scheduleDismiss() {
Thread t = new Thread(new Runnable() { Thread t = new Thread(() -> {
@Override SystemClock.sleep(5000);
public void run() { BolusProgressDialog.bolusEnded = true;
SystemClock.sleep(5000); Activity activity = getActivity();
BolusProgressDialog.bolusEnded = true; if (activity != null) {
Activity activity = getActivity(); activity.runOnUiThread(() -> {
if (activity != null) { try {
activity.runOnUiThread( dismiss();
new Runnable() { } catch (Exception e) {
@Override log.error("Unhandled exception", e);
public void run() { }
try { });
dismiss();
} catch (Exception e) {
log.error("Unhandled exception", e);
}
}
});
}
} }
}); });
t.start(); t.start();

View file

@ -149,13 +149,13 @@ public class EditQuickWizardDialog extends DialogFragment implements View.OnClic
int getSelection(Spinner spinner) { int getSelection(Spinner spinner) {
String value = spinner.getSelectedItem().toString(); String value = spinner.getSelectedItem().toString();
if (value.equals(MainApp.sResources.getString(R.string.yes))) if (value.equals(MainApp.gs(R.string.yes)))
return QuickWizardEntry.YES; return QuickWizardEntry.YES;
if (value.equals(MainApp.sResources.getString(R.string.no))) if (value.equals(MainApp.gs(R.string.no)))
return QuickWizardEntry.NO; return QuickWizardEntry.NO;
if (value.equals(MainApp.sResources.getString(R.string.positiveonly))) if (value.equals(MainApp.gs(R.string.positiveonly)))
return QuickWizardEntry.POSITIVE_ONLY; return QuickWizardEntry.POSITIVE_ONLY;
if (value.equals(MainApp.sResources.getString(R.string.negativeonly))) if (value.equals(MainApp.gs(R.string.negativeonly)))
return QuickWizardEntry.NEGATIVE_ONLY; return QuickWizardEntry.NEGATIVE_ONLY;
return QuickWizardEntry.NO; return QuickWizardEntry.NO;
} }
@ -164,19 +164,19 @@ public class EditQuickWizardDialog extends DialogFragment implements View.OnClic
String selection; String selection;
switch (value) { switch (value) {
case QuickWizardEntry.YES: case QuickWizardEntry.YES:
selection = MainApp.sResources.getString(R.string.yes); selection = MainApp.gs(R.string.yes);
break; break;
case QuickWizardEntry.NO: case QuickWizardEntry.NO:
selection = MainApp.sResources.getString(R.string.no); selection = MainApp.gs(R.string.no);
break; break;
case QuickWizardEntry.POSITIVE_ONLY: case QuickWizardEntry.POSITIVE_ONLY:
selection = MainApp.sResources.getString(R.string.positiveonly); selection = MainApp.gs(R.string.positiveonly);
break; break;
case QuickWizardEntry.NEGATIVE_ONLY: case QuickWizardEntry.NEGATIVE_ONLY:
selection = MainApp.sResources.getString(R.string.negativeonly); selection = MainApp.gs(R.string.negativeonly);
break; break;
default: default:
selection = MainApp.sResources.getString(R.string.no); selection = MainApp.gs(R.string.no);
break; break;
} }

View file

@ -133,9 +133,6 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C
editTime = view.findViewById(R.id.newcarbs_time); editTime = view.findViewById(R.id.newcarbs_time);
editTime.setParams(0d, -12 * 60d, 12 * 60d, 5d, new DecimalFormat("0"), false, textWatcher); editTime.setParams(0d, -12 * 60d, 12 * 60d, 5d, new DecimalFormat("0"), false, textWatcher);
LinearLayout durationLayout = view.findViewById(R.id.newcarbs_duration_layout);
durationLayout.setVisibility(MainApp.engineeringMode ? View.VISIBLE : View.GONE);
editDuration = view.findViewById(R.id.new_carbs_duration); editDuration = view.findViewById(R.id.new_carbs_duration);
editDuration.setParams(0d, 0d, 10d, 1d, new DecimalFormat("0"), false, textWatcher); editDuration.setParams(0d, 0d, 10d, 1d, new DecimalFormat("0"), false, textWatcher);
@ -406,7 +403,8 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C
long carbTime = time + i * 15 * 60 * 1000; long carbTime = time + i * 15 * 60 * 1000;
long smallCarbAmount = Math.round((1d * remainingCarbs) / (ticks-i)); //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs long smallCarbAmount = Math.round((1d * remainingCarbs) / (ticks-i)); //on last iteration (ticks-i) is 1 -> smallCarbAmount == remainingCarbs
remainingCarbs -= smallCarbAmount; remainingCarbs -= smallCarbAmount;
createCarb(smallCarbAmount, carbTime, notes); if (smallCarbAmount > 0)
createCarb(smallCarbAmount, carbTime, notes);
} }
} }
} }
@ -431,7 +429,7 @@ public class NewCarbsDialog extends DialogFragment implements OnClickListener, C
carbInfo.context = getContext(); carbInfo.context = getContext();
carbInfo.source = Source.USER; carbInfo.source = Source.USER;
carbInfo.notes = notes; carbInfo.notes = notes;
if (ConfigBuilderPlugin.getActivePump().getPumpDescription().storesCarbInfo) { if (ConfigBuilderPlugin.getActivePump().getPumpDescription().storesCarbInfo && carbInfo.date <= now()) {
ConfigBuilderPlugin.getCommandQueue().bolus(carbInfo, new Callback() { ConfigBuilderPlugin.getCommandQueue().bolus(carbInfo, new Callback() {
@Override @Override
public void run() { public void run() {

View file

@ -35,6 +35,7 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.utils.FabricPrivacy;
import info.nightscout.utils.NumberPicker; import info.nightscout.utils.NumberPicker;
import info.nightscout.utils.SafeParse; import info.nightscout.utils.SafeParse;
@ -104,7 +105,7 @@ public class NewTreatmentDialog extends DialogFragment implements OnClickListene
editInsulin = (NumberPicker) view.findViewById(R.id.treatments_newtreatment_insulinamount); editInsulin = (NumberPicker) view.findViewById(R.id.treatments_newtreatment_insulinamount);
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, textWatcher); editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, textWatcher);
editInsulin.setParams(0d, 0d, maxInsulin, ConfigBuilderPlugin.getActivePump().getPumpDescription().bolusStep, new DecimalFormat("0.00"), false, textWatcher); editInsulin.setParams(0d, 0d, maxInsulin, ConfigBuilderPlugin.getActivePump().getPumpDescription().bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, textWatcher);
recordOnlyCheckbox = (CheckBox) view.findViewById(R.id.newtreatment_record_only); recordOnlyCheckbox = (CheckBox) view.findViewById(R.id.newtreatment_record_only);

View file

@ -56,7 +56,7 @@ import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
@ -270,13 +270,13 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
} }
private void saveCheckedStates() { private void saveCheckedStates() {
SP.putBoolean(getString(R.string.key_wizard_include_cob), cobCheckbox.isChecked()); SP.putBoolean(MainApp.gs(R.string.key_wizard_include_cob), cobCheckbox.isChecked());
SP.putBoolean(getString(R.string.key_wizard_include_trend_bg), bgtrendCheckbox.isChecked()); SP.putBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), bgtrendCheckbox.isChecked());
} }
private void loadCheckedStates() { private void loadCheckedStates() {
bgtrendCheckbox.setChecked(SP.getBoolean(getString(R.string.key_wizard_include_trend_bg), false)); bgtrendCheckbox.setChecked(SP.getBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), false));
cobCheckbox.setChecked(SP.getBoolean(getString(R.string.key_wizard_include_cob), false)); cobCheckbox.setChecked(SP.getBoolean(MainApp.gs(R.string.key_wizard_include_cob), false));
} }
@Override @Override
@ -287,7 +287,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
@Override @Override
public void onNothingSelected(AdapterView<?> parent) { public void onNothingSelected(AdapterView<?> parent) {
ToastUtils.showToastInUiThread(context, MainApp.sResources.getString(R.string.noprofileselected)); ToastUtils.showToastInUiThread(context, MainApp.gs(R.string.noprofileselected));
okButton.setVisibility(View.GONE); okButton.setVisibility(View.GONE);
} }
@ -306,20 +306,20 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
if (profile != null && (calculatedTotalInsulin > 0d || calculatedCarbs > 0d)) { if (profile != null && (calculatedTotalInsulin > 0d || calculatedCarbs > 0d)) {
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00"); DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
String confirmMessage = getString(R.string.entertreatmentquestion); String confirmMessage = MainApp.gs(R.string.entertreatmentquestion);
Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(calculatedTotalInsulin)).value(); Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(calculatedCarbs)).value(); Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(calculatedCarbs)).value();
confirmMessage += "<br/>" + getString(R.string.bolus) + ": " + "<font color='" + MainApp.sResources.getColor(R.color.bolus) + "'>" + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U" + "</font>"; confirmMessage += "<br/>" + MainApp.gs(R.string.bolus) + ": " + "<font color='" + MainApp.sResources.getColor(R.color.bolus) + "'>" + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U" + "</font>";
confirmMessage += "<br/>" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g"; confirmMessage += "<br/>" + MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (insulinAfterConstraints - calculatedTotalInsulin != 0 || !carbsAfterConstraints.equals(calculatedCarbs)) { if (insulinAfterConstraints - calculatedTotalInsulin != 0 || !carbsAfterConstraints.equals(calculatedCarbs)) {
AlertDialog.Builder builder = new AlertDialog.Builder(context); AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.treatmentdeliveryerror)); builder.setTitle(MainApp.gs(R.string.treatmentdeliveryerror));
builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput)); builder.setMessage(MainApp.gs(R.string.constraints_violation) + "\n" + MainApp.gs(R.string.changeyourinput));
builder.setPositiveButton(MainApp.sResources.getString(R.string.ok), null); builder.setPositiveButton(MainApp.gs(R.string.ok), null);
builder.show(); builder.show();
return; return;
} }
@ -332,9 +332,9 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
final String finalNotes = notesEdit.getText().toString(); final String finalNotes = notesEdit.getText().toString();
final AlertDialog.Builder builder = new AlertDialog.Builder(context); final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(MainApp.sResources.getString(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(Html.fromHtml(confirmMessage)); builder.setMessage(Html.fromHtml(confirmMessage));
builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) { public void onClick(DialogInterface dialog, int id) {
synchronized (builder) { synchronized (builder) {
if (accepted) { if (accepted) {
@ -356,7 +356,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment); i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.tempbasaldeliveryerror)); i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); MainApp.instance().startActivity(i);
} }
@ -382,7 +382,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.boluserror); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("status", result.comment); i.putExtra("status", result.comment);
i.putExtra("title", MainApp.sResources.getString(R.string.treatmentdeliveryerror)); i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i); MainApp.instance().startActivity(i);
} }
@ -396,7 +396,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
} }
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
dismiss(); dismiss();
} }
@ -412,14 +412,14 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile(); ProfileStore profileStore = MainApp.getConfigBuilder().getActiveProfileInterface().getProfile();
if (profile == null) { if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.noprofile));
dismiss(); dismiss();
return; return;
} }
ArrayList<CharSequence> profileList; ArrayList<CharSequence> profileList;
profileList = profileStore.getProfileList(); profileList = profileStore.getProfileList();
profileList.add(0, MainApp.sResources.getString(R.string.active)); profileList.add(0, MainApp.gs(R.string.active));
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(getContext(), ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, profileList); R.layout.spinner_centered, profileList);
@ -458,7 +458,7 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
return; // not initialized yet return; // not initialized yet
String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString(); String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString();
Profile specificProfile; Profile specificProfile;
if (selectedAlternativeProfile.equals(MainApp.sResources.getString(R.string.active))) if (selectedAlternativeProfile.equals(MainApp.gs(R.string.active)))
specificProfile = MainApp.getConfigBuilder().getProfile(); specificProfile = MainApp.getConfigBuilder().getProfile();
else else
specificProfile = profileStore.getSpecificProfile(selectedAlternativeProfile); specificProfile = profileStore.getSpecificProfile(selectedAlternativeProfile);
@ -472,13 +472,13 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
c_correction = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(c_correction)).value(); c_correction = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(c_correction)).value();
if (c_correction - corrAfterConstraint != 0) { // c_correction != corrAfterConstraint doesn't work if (c_correction - corrAfterConstraint != 0) { // c_correction != corrAfterConstraint doesn't work
editCorr.setValue(0d); editCorr.setValue(0d);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), getString(R.string.bolusconstraintapplied)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.bolusconstraintapplied));
return; return;
} }
Integer carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(c_carbs)).value(); Integer carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(c_carbs)).value();
if (c_carbs - carbsAfterConstraint != 0) { if (c_carbs - carbsAfterConstraint != 0) {
editCarbs.setValue(0d); editCarbs.setValue(0d);
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), getString(R.string.carbsconstraintapplied)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.carbsconstraintapplied));
return; return;
} }
@ -488,11 +488,9 @@ public class WizardDialog extends DialogFragment implements OnClickListener, Com
// COB // COB
Double c_cob = 0d; Double c_cob = 0d;
if (cobCheckbox.isChecked()) { if (cobCheckbox.isChecked()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensData("Wizard COB"); CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "Wizard COB");
if (cobInfo != null && cobInfo.displayCob != null)
if (autosensData != null) { c_cob = cobInfo.displayCob;
c_cob = autosensData.cob;
}
} }
BolusWizard wizard = new BolusWizard(); BolusWizard wizard = new BolusWizard();

View file

@ -5,7 +5,6 @@ import android.app.Activity;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.content.ActivityNotFoundException; import android.content.ActivityNotFoundException;
import android.content.Context; import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.graphics.Color; import android.graphics.Color;
@ -15,10 +14,8 @@ import android.os.Handler;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat; import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog; import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu; import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView;
@ -33,7 +30,6 @@ import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import android.widget.CompoundButton; import android.widget.CompoundButton;
import android.widget.ImageButton; import android.widget.ImageButton;
@ -52,8 +48,6 @@ import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
@ -94,12 +88,12 @@ import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialo
import info.nightscout.androidaps.plugins.Careportal.OptionsToShow; import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.broadcasts.BroadcastAckAlarm;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.NSClientInternal.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.CalibrationDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
@ -108,10 +102,8 @@ import info.nightscout.androidaps.plugins.Overview.Dialogs.NewInsulinDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.NewTreatmentDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.NewTreatmentDialog;
import info.nightscout.androidaps.plugins.Overview.Dialogs.WizardDialog; import info.nightscout.androidaps.plugins.Overview.Dialogs.WizardDialog;
import info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity; import info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventSetWakeLock; import info.nightscout.androidaps.plugins.Overview.events.EventSetWakeLock;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData; import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationRecyclerViewAdapter; import info.nightscout.androidaps.plugins.Overview.notifications.NotificationRecyclerViewAdapter;
import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore; import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
@ -150,6 +142,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
TextView pumpDeviceStatusView; TextView pumpDeviceStatusView;
TextView openapsDeviceStatusView; TextView openapsDeviceStatusView;
TextView uploaderDeviceStatusView; TextView uploaderDeviceStatusView;
TextView iobCalculationProgressView;
LinearLayout loopStatusLayout; LinearLayout loopStatusLayout;
LinearLayout pumpStatusLayout; LinearLayout pumpStatusLayout;
GraphView bgGraph; GraphView bgGraph;
@ -191,9 +184,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final Object updateSync = new Object(); final Object updateSync = new Object();
public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN} public enum CHARTTYPE {PRE, BAS, IOB, COB, DEV, SEN, DEVSLOPE}
;
private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledUpdate = null; private static ScheduledFuture<?> scheduledUpdate = null;
@ -245,6 +236,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump); pumpDeviceStatusView = (TextView) view.findViewById(R.id.overview_pump);
openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps); openapsDeviceStatusView = (TextView) view.findViewById(R.id.overview_openaps);
uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader); uploaderDeviceStatusView = (TextView) view.findViewById(R.id.overview_uploader);
iobCalculationProgressView = (TextView) view.findViewById(R.id.overview_iobcalculationprogess);
loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout); loopStatusLayout = (LinearLayout) view.findViewById(R.id.overview_looplayout);
pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout); pumpStatusLayout = (LinearLayout) view.findViewById(R.id.overview_pumpstatuslayout);
@ -416,26 +408,33 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
item.setCheckable(true); item.setCheckable(true);
item.setChecked(SP.getBoolean("showratios", false)); item.setChecked(SP.getBoolean("showratios", false));
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(SP.getBoolean("showdevslope", false));
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override @Override
public boolean onMenuItemClick(MenuItem item) { public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == CHARTTYPE.PRE.ordinal()) { if (item.getItemId() == CHARTTYPE.PRE.ordinal()) {
SP.putBoolean("showprediction", !item.isChecked()); SP.putBoolean("showprediction", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.BAS.ordinal()) { } else if (item.getItemId() == CHARTTYPE.BAS.ordinal()) {
SP.putBoolean("showbasals", !item.isChecked()); SP.putBoolean("showbasals", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.IOB.ordinal()) { } else if (item.getItemId() == CHARTTYPE.IOB.ordinal()) {
SP.putBoolean("showiob", !item.isChecked()); SP.putBoolean("showiob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.COB.ordinal()) { } else if (item.getItemId() == CHARTTYPE.COB.ordinal()) {
SP.putBoolean("showcob", !item.isChecked()); SP.putBoolean("showcob", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEV.ordinal()) { } else if (item.getItemId() == CHARTTYPE.DEV.ordinal()) {
SP.putBoolean("showdeviations", !item.isChecked()); SP.putBoolean("showdeviations", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.SEN.ordinal()) { } else if (item.getItemId() == CHARTTYPE.SEN.ordinal()) {
SP.putBoolean("showratios", !item.isChecked()); SP.putBoolean("showratios", !item.isChecked());
} else if (item.getItemId() == CHARTTYPE.DEVSLOPE.ordinal()) {
SP.putBoolean("showdevslope", !item.isChecked());
} }
scheduleUpdateGUI("onGraphCheckboxesCheckedChanged"); scheduleUpdateGUI("onGraphCheckboxesCheckedChanged");
return true; return true;
@ -679,9 +678,9 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun; final LoopPlugin.LastRun finalLastRun = LoopPlugin.lastRun;
if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.isChangeRequested()) { if (finalLastRun != null && finalLastRun.lastAPSRun != null && finalLastRun.constraintsProcessed.isChangeRequested()) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(getContext().getString(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed); builder.setMessage(MainApp.gs(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
builder.setPositiveButton(getContext().getString(R.string.ok), (dialog, id) -> { builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
hideTempRecommendation(); hideTempRecommendation();
clearNotification(); clearNotification();
MainApp.getConfigBuilder().applyTBRRequest(finalLastRun.constraintsProcessed, profile, new Callback() { MainApp.getConfigBuilder().applyTBRRequest(finalLastRun.constraintsProcessed, profile, new Callback() {
@ -703,7 +702,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}); });
FabricPrivacy.getInstance().logCustom(new CustomEvent("AcceptTemp")); FabricPrivacy.getInstance().logCustom(new CustomEvent("AcceptTemp"));
}); });
builder.setNegativeButton(getContext().getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
} }
} }
@ -743,18 +742,18 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
} }
if (wizard.calculatedTotalInsulin > 0d && quickWizardEntry.carbs() > 0d) { if (wizard.calculatedTotalInsulin > 0d && quickWizardEntry.carbs() > 0d) {
DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00"); DecimalFormat formatNumber2decimalplaces = new DecimalFormat("0.00");
String confirmMessage = getString(R.string.entertreatmentquestion); String confirmMessage = MainApp.gs(R.string.entertreatmentquestion);
Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value(); Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(wizard.calculatedTotalInsulin)).value();
Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value(); Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(quickWizardEntry.carbs())).value();
confirmMessage += "\n" + getString(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U"; confirmMessage += "\n" + MainApp.gs(R.string.bolus) + ": " + formatNumber2decimalplaces.format(insulinAfterConstraints) + "U";
confirmMessage += "\n" + getString(R.string.carbs) + ": " + carbsAfterConstraints + "g"; confirmMessage += "\n" + MainApp.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g";
if (!insulinAfterConstraints.equals(wizard.calculatedTotalInsulin) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) { if (!insulinAfterConstraints.equals(wizard.calculatedTotalInsulin) || !carbsAfterConstraints.equals(quickWizardEntry.carbs())) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(MainApp.gs(R.string.treatmentdeliveryerror)); builder.setTitle(MainApp.gs(R.string.treatmentdeliveryerror));
builder.setMessage(getString(R.string.constraints_violation) + "\n" + getString(R.string.changeyourinput)); builder.setMessage(MainApp.gs(R.string.constraints_violation) + "\n" + MainApp.gs(R.string.changeyourinput));
builder.setPositiveButton(MainApp.gs(R.string.ok), null); builder.setPositiveButton(MainApp.gs(R.string.ok), null);
builder.show(); builder.show();
return; return;
@ -767,7 +766,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
accepted = false; accepted = false;
builder.setTitle(MainApp.gs(R.string.confirmation)); builder.setTitle(MainApp.gs(R.string.confirmation));
builder.setMessage(confirmMessage); builder.setMessage(confirmMessage);
builder.setPositiveButton(getString(R.string.ok), (dialog, id) -> { builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
synchronized (builder) { synchronized (builder) {
if (accepted) { if (accepted) {
log.debug("guarding: already accepted"); log.debug("guarding: already accepted");
@ -802,24 +801,28 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
detailedBolusInfo.context = context; detailedBolusInfo.context = context;
detailedBolusInfo.boluscalc = boluscalcJSON; detailedBolusInfo.boluscalc = boluscalcJSON;
detailedBolusInfo.source = Source.USER; detailedBolusInfo.source = Source.USER;
ConfigBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, new Callback() { if (finalInsulinAfterConstraints > 0 || ConfigBuilderPlugin.getActivePump().getPumpDescription().storesCarbInfo) {
@Override ConfigBuilderPlugin.getCommandQueue().bolus(detailedBolusInfo, new Callback() {
public void run() { @Override
if (!result.success) { public void run() {
Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); if (!result.success) {
i.putExtra("soundid", R.raw.boluserror); Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
i.putExtra("status", result.comment); i.putExtra("soundid", R.raw.boluserror);
i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)); i.putExtra("status", result.comment);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
MainApp.instance().startActivity(i); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
}
} }
} });
}); } else {
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo);
}
FabricPrivacy.getInstance().logCustom(new CustomEvent("QuickWizard")); FabricPrivacy.getInstance().logCustom(new CustomEvent("QuickWizard"));
} }
} }
}); });
builder.setNegativeButton(getString(R.string.cancel), null); builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show(); builder.show();
} }
} }
@ -911,15 +914,22 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
activity.runOnUiThread(() -> updatePumpStatus(s.textStatus())); activity.runOnUiThread(() -> updatePumpStatus(s.textStatus()));
} }
@Subscribe
public void onStatusEvent(final EventIobCalculationProgress e) {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(() -> {
if (iobCalculationProgressView != null)
iobCalculationProgressView.setText(e.progress);
});
}
private void hideTempRecommendation() { private void hideTempRecommendation() {
Activity activity = getActivity(); Activity activity = getActivity();
if (activity != null) if (activity != null)
activity.runOnUiThread(new Runnable() { activity.runOnUiThread(() -> {
@Override if (acceptTempLayout != null)
public void run() { acceptTempLayout.setVisibility(View.GONE);
if (acceptTempLayout != null)
acceptTempLayout.setVisibility(View.GONE);
}
}); });
} }
@ -1081,7 +1091,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) { if (showAcceptButton && pump.isInitialized() && !pump.isSuspended() && LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
acceptTempLayout.setVisibility(View.VISIBLE); acceptTempLayout.setVisibility(View.VISIBLE);
acceptTempButton.setText(getContext().getString(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed); acceptTempButton.setText(MainApp.gs(R.string.setbasalquestion) + "\n" + finalLastRun.constraintsProcessed);
} else { } else {
acceptTempLayout.setVisibility(View.GONE); acceptTempLayout.setVisibility(View.GONE);
} }
@ -1168,7 +1178,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
extendedBolusView.setText(extendedBolusText); extendedBolusView.setText(extendedBolusText);
} }
if (extendedBolusText.equals("")) if (extendedBolusText.equals(""))
extendedBolusView.setVisibility(View.INVISIBLE); extendedBolusView.setVisibility(View.GONE);
else else
extendedBolusView.setVisibility(View.VISIBLE); extendedBolusView.setVisibility(View.VISIBLE);
} }
@ -1259,14 +1269,14 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
iobView.setText(iobtext); iobView.setText(iobtext);
iobView.setOnClickListener(v -> { iobView.setOnClickListener(v -> {
String iobtext1 = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U\n" String iobtext1 = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U\n"
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U\n" + MainApp.gs(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U\n"
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U\n"; + MainApp.gs(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U\n";
OKDialog.show(getActivity(), MainApp.gs(R.string.iob), iobtext1, null); OKDialog.show(getActivity(), MainApp.gs(R.string.iob), iobtext1, null);
}); });
} else if (MainApp.sResources.getBoolean(R.bool.isTablet)) { } else if (MainApp.sResources.getBoolean(R.bool.isTablet)) {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U " + MainApp.gs(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)"; + MainApp.gs(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
iobView.setText(iobtext); iobView.setText(iobtext);
} else { } else {
String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U (" String iobtext = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
@ -1277,10 +1287,13 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// cob // cob
if (cobView != null) { // view must not exists if (cobView != null) { // view must not exists
String cobText = ""; String cobText = MainApp.gs(R.string.value_unavailable_short);
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensData("Overview COB"); CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "Overview COB");
if (autosensData != null) if (cobInfo.displayCob != null) {
cobText = (int) autosensData.cob + " g"; cobText = DecimalFormatter.to0Decimal(cobInfo.displayCob);
if (cobInfo.futureCarbs > 0)
cobText += "(" + DecimalFormatter.to0Decimal(cobInfo.futureCarbs) + ")";
}
cobView.setText(cobText); cobView.setText(cobText);
} }
@ -1346,7 +1359,8 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
// **** BG **** // **** BG ****
if (predictionsAvailable && SP.getBoolean("showprediction", false)) if (predictionsAvailable && SP.getBoolean("showprediction", false))
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, finalLastRun.constraintsProcessed); graphData.addBgReadings(fromTime, toTime, lowLine, highLine,
finalLastRun.constraintsProcessed.getPredictions());
else else
graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null); graphData.addBgReadings(fromTime, toTime, lowLine, highLine, null);
@ -1386,7 +1400,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
useDevForScale = true; useDevForScale = true;
} else if (SP.getBoolean("showratios", false)) { } else if (SP.getBoolean("showratios", false)) {
useRatioForScale = true; useRatioForScale = true;
} else if (Config.displayDeviationSlope) { } else if (SP.getBoolean("showdevslope", false)) {
useDSForScale = true; useDSForScale = true;
} }
@ -1398,7 +1412,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
secondGraphData.addDeviations(fromTime, now, useDevForScale, 1d); secondGraphData.addDeviations(fromTime, now, useDevForScale, 1d);
if (SP.getBoolean("showratios", false)) if (SP.getBoolean("showratios", false))
secondGraphData.addRatio(fromTime, now, useRatioForScale, 1d); secondGraphData.addRatio(fromTime, now, useRatioForScale, 1d);
if (Config.displayDeviationSlope) if (SP.getBoolean("showdevslope", false))
secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1d); secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1d);
// **** NOW line **** // **** NOW line ****
@ -1410,7 +1424,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
FragmentActivity activity = getActivity(); FragmentActivity activity = getActivity();
if (activity != null) { if (activity != null) {
activity.runOnUiThread(() -> { activity.runOnUiThread(() -> {
if (SP.getBoolean("showiob", true) || SP.getBoolean("showcob", true) || SP.getBoolean("showdeviations", false) || SP.getBoolean("showratios", false) || Config.displayDeviationSlope) { if (SP.getBoolean("showiob", true)
|| SP.getBoolean("showcob", true)
|| SP.getBoolean("showdeviations", false)
|| SP.getBoolean("showratios", false)
|| SP.getBoolean("showdevslope", false)) {
iobGraph.setVisibility(View.VISIBLE); iobGraph.setVisibility(View.VISIBLE);
} else { } else {
iobGraph.setVisibility(View.GONE); iobGraph.setVisibility(View.GONE);

View file

@ -12,6 +12,7 @@ import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.Series; import com.jjoe64.graphview.series.Series;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
@ -61,7 +62,7 @@ public class GraphData {
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
} }
public void addBgReadings(long fromTime, long toTime, double lowLine, double highLine, APSResult apsResult) { public void addBgReadings(long fromTime, long toTime, double lowLine, double highLine, List<BgReading> predictions) {
double maxBgValue = 0d; double maxBgValue = 0d;
bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true); bgReadingsArray = MainApp.getDbHelper().getBgreadingsDataFromTime(fromTime, true);
List<DataPointWithLabelInterface> bgListArray = new ArrayList<>(); List<DataPointWithLabelInterface> bgListArray = new ArrayList<>();
@ -74,9 +75,12 @@ public class GraphData {
if (bg.value > maxBgValue) maxBgValue = bg.value; if (bg.value > maxBgValue) maxBgValue = bg.value;
bgListArray.add(bg); bgListArray.add(bg);
} }
if (apsResult != null) { if (predictions != null) {
List<BgReading> predArray = apsResult.getPredictions(); Collections.sort(predictions, (o1, o2) -> Double.compare(o1.getX(), o2.getX()));
bgListArray.addAll(predArray); for (BgReading prediction : predictions) {
if (prediction.value >= 40)
bgListArray.add(prediction);
}
} }
maxBgValue = Profile.fromMgdlToUnits(maxBgValue, units); maxBgValue = Profile.fromMgdlToUnits(maxBgValue, units);
@ -108,7 +112,7 @@ public class GraphData {
inRangeAreaSeries = new AreaGraphSeries<>(inRangeAreaDataPoints); inRangeAreaSeries = new AreaGraphSeries<>(inRangeAreaDataPoints);
inRangeAreaSeries.setColor(0); inRangeAreaSeries.setColor(0);
inRangeAreaSeries.setDrawBackground(true); inRangeAreaSeries.setDrawBackground(true);
inRangeAreaSeries.setBackgroundColor(MainApp.sResources.getColor(R.color.inrangebackground)); inRangeAreaSeries.setBackgroundColor(MainApp.gc(R.color.inrangebackground));
addSeries(inRangeAreaSeries); addSeries(inRangeAreaSeries);
} }
@ -184,14 +188,14 @@ public class GraphData {
baseBasal = baseBasalArray.toArray(baseBasal); baseBasal = baseBasalArray.toArray(baseBasal);
baseBasalsSeries = new LineGraphSeries<>(baseBasal); baseBasalsSeries = new LineGraphSeries<>(baseBasal);
baseBasalsSeries.setDrawBackground(true); baseBasalsSeries.setDrawBackground(true);
baseBasalsSeries.setBackgroundColor(MainApp.sResources.getColor(R.color.basebasal)); baseBasalsSeries.setBackgroundColor(MainApp.gc(R.color.basebasal));
baseBasalsSeries.setThickness(0); baseBasalsSeries.setThickness(0);
ScaledDataPoint[] tempBasal = new ScaledDataPoint[tempBasalArray.size()]; ScaledDataPoint[] tempBasal = new ScaledDataPoint[tempBasalArray.size()];
tempBasal = tempBasalArray.toArray(tempBasal); tempBasal = tempBasalArray.toArray(tempBasal);
tempBasalsSeries = new LineGraphSeries<>(tempBasal); tempBasalsSeries = new LineGraphSeries<>(tempBasal);
tempBasalsSeries.setDrawBackground(true); tempBasalsSeries.setDrawBackground(true);
tempBasalsSeries.setBackgroundColor(MainApp.sResources.getColor(R.color.tempbasal)); tempBasalsSeries.setBackgroundColor(MainApp.gc(R.color.tempbasal));
tempBasalsSeries.setThickness(0); tempBasalsSeries.setThickness(0);
ScaledDataPoint[] basalLine = new ScaledDataPoint[basalLineArray.size()]; ScaledDataPoint[] basalLine = new ScaledDataPoint[basalLineArray.size()];
@ -201,7 +205,7 @@ public class GraphData {
paint.setStyle(Paint.Style.STROKE); paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(MainApp.instance().getApplicationContext().getResources().getDisplayMetrics().scaledDensity * 2); paint.setStrokeWidth(MainApp.instance().getApplicationContext().getResources().getDisplayMetrics().scaledDensity * 2);
paint.setPathEffect(new DashPathEffect(new float[]{2, 4}, 0)); paint.setPathEffect(new DashPathEffect(new float[]{2, 4}, 0));
paint.setColor(MainApp.sResources.getColor(R.color.basal)); paint.setColor(MainApp.gc(R.color.basal));
basalsLineSeries.setCustomPaint(paint); basalsLineSeries.setCustomPaint(paint);
ScaledDataPoint[] absoluteBasalLine = new ScaledDataPoint[absoluteBasalLineArray.size()]; ScaledDataPoint[] absoluteBasalLine = new ScaledDataPoint[absoluteBasalLineArray.size()];
@ -210,7 +214,7 @@ public class GraphData {
Paint absolutePaint = new Paint(); Paint absolutePaint = new Paint();
absolutePaint.setStyle(Paint.Style.STROKE); absolutePaint.setStyle(Paint.Style.STROKE);
absolutePaint.setStrokeWidth(MainApp.instance().getApplicationContext().getResources().getDisplayMetrics().scaledDensity * 2); absolutePaint.setStrokeWidth(MainApp.instance().getApplicationContext().getResources().getDisplayMetrics().scaledDensity * 2);
absolutePaint.setColor(MainApp.sResources.getColor(R.color.basal)); absolutePaint.setColor(MainApp.gc(R.color.basal));
absoluteBasalsLineSeries.setCustomPaint(absolutePaint); absoluteBasalsLineSeries.setCustomPaint(absolutePaint);
basalScale.setMultiplier(maxY * scale / maxBasalValueFound); basalScale.setMultiplier(maxY * scale / maxBasalValueFound);
@ -259,7 +263,7 @@ public class GraphData {
targets = targetsSeriesArray.toArray(targets); targets = targetsSeriesArray.toArray(targets);
targetsSeries = new LineGraphSeries<>(targets); targetsSeries = new LineGraphSeries<>(targets);
targetsSeries.setDrawBackground(false); targetsSeries.setDrawBackground(false);
targetsSeries.setColor(MainApp.sResources.getColor(R.color.tempTargetBackground)); targetsSeries.setColor(MainApp.gc(R.color.tempTargetBackground));
targetsSeries.setThickness(2); targetsSeries.setThickness(2);
addSeries(targetsSeries); addSeries(targetsSeries);
@ -273,6 +277,7 @@ public class GraphData {
for (int tx = 0; tx < treatments.size(); tx++) { for (int tx = 0; tx < treatments.size(); tx++) {
Treatment t = treatments.get(tx); Treatment t = treatments.get(tx);
if (t.getX() < fromTime || t.getX() > endTime) continue; if (t.getX() < fromTime || t.getX() > endTime) continue;
if (t.isSMB && !t.isValid) continue;
t.setY(getNearestBg((long) t.getX())); t.setY(getNearestBg((long) t.getX()));
filteredTreatments.add(t); filteredTreatments.add(t);
} }
@ -351,8 +356,8 @@ public class GraphData {
iobData = iobArray.toArray(iobData); iobData = iobArray.toArray(iobData);
iobSeries = new FixedLineGraphSeries<>(iobData); iobSeries = new FixedLineGraphSeries<>(iobData);
iobSeries.setDrawBackground(true); iobSeries.setDrawBackground(true);
iobSeries.setBackgroundColor(0x80FFFFFF & MainApp.sResources.getColor(R.color.iob)); //50% iobSeries.setBackgroundColor(0x80FFFFFF & MainApp.gc(R.color.iob)); //50%
iobSeries.setColor(MainApp.sResources.getColor(R.color.iob)); iobSeries.setColor(MainApp.gc(R.color.iob));
iobSeries.setThickness(3); iobSeries.setThickness(3);
if (useForScale) if (useForScale)
@ -365,6 +370,7 @@ public class GraphData {
// scale in % of vertical size (like 0.3) // scale in % of vertical size (like 0.3)
public void addCob(long fromTime, long toTime, boolean useForScale, double scale) { public void addCob(long fromTime, long toTime, boolean useForScale, double scale) {
List<DataPointWithLabelInterface> minFailoverActiveList = new ArrayList<>();
FixedLineGraphSeries<ScaledDataPoint> cobSeries; FixedLineGraphSeries<ScaledDataPoint> cobSeries;
List<ScaledDataPoint> cobArray = new ArrayList<>(); List<ScaledDataPoint> cobArray = new ArrayList<>();
Double maxCobValueFound = 0d; Double maxCobValueFound = 0d;
@ -382,6 +388,11 @@ public class GraphData {
maxCobValueFound = Math.max(maxCobValueFound, cob); maxCobValueFound = Math.max(maxCobValueFound, cob);
lastCob = cob; lastCob = cob;
} }
if (autosensData.failoverToMinAbsorbtionRate) {
autosensData.setScale(cobScale);
autosensData.setChartTime(time);
minFailoverActiveList.add(autosensData);
}
} }
} }
@ -390,8 +401,8 @@ public class GraphData {
cobData = cobArray.toArray(cobData); cobData = cobArray.toArray(cobData);
cobSeries = new FixedLineGraphSeries<>(cobData); cobSeries = new FixedLineGraphSeries<>(cobData);
cobSeries.setDrawBackground(true); cobSeries.setDrawBackground(true);
cobSeries.setBackgroundColor(0xB0FFFFFF & MainApp.sResources.getColor(R.color.cob)); //50% cobSeries.setBackgroundColor(0x80FFFFFF & MainApp.gc(R.color.cob)); //50%
cobSeries.setColor(MainApp.sResources.getColor(R.color.cob)); cobSeries.setColor(MainApp.gc(R.color.cob));
cobSeries.setThickness(3); cobSeries.setThickness(3);
if (useForScale) if (useForScale)
@ -400,6 +411,10 @@ public class GraphData {
cobScale.setMultiplier(maxY * scale / maxCobValueFound); cobScale.setMultiplier(maxY * scale / maxCobValueFound);
addSeries(cobSeries); addSeries(cobSeries);
DataPointWithLabelInterface[] minFailover = new DataPointWithLabelInterface[minFailoverActiveList.size()];
minFailover = minFailoverActiveList.toArray(minFailover);
addSeries(new PointsWithLabelGraphSeries<>(minFailover));
} }
// scale in % of vertical size (like 0.3) // scale in % of vertical size (like 0.3)
@ -421,10 +436,10 @@ public class GraphData {
for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) { for (long time = fromTime; time <= toTime; time += 5 * 60 * 1000L) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time); AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getAutosensData(time);
if (autosensData != null) { if (autosensData != null) {
int color = Color.BLACK; // "=" int color = MainApp.gc(R.color.deviationblack); // "="
if (autosensData.pastSensitivity.equals("C")) color = Color.GRAY; if (autosensData.pastSensitivity.equals("C")) color = MainApp.gc(R.color.deviationgrey);
if (autosensData.pastSensitivity.equals("+")) color = Color.GREEN; if (autosensData.pastSensitivity.equals("+")) color = MainApp.gc(R.color.deviationgreen);
if (autosensData.pastSensitivity.equals("-")) color = Color.RED; if (autosensData.pastSensitivity.equals("-")) color = MainApp.gc(R.color.deviationred);
devArray.add(new DeviationDataPoint(time, autosensData.deviation, color, devScale)); devArray.add(new DeviationDataPoint(time, autosensData.deviation, color, devScale));
maxDevValueFound = Math.max(maxDevValueFound, Math.abs(autosensData.deviation)); maxDevValueFound = Math.max(maxDevValueFound, Math.abs(autosensData.deviation));
} }
@ -468,7 +483,7 @@ public class GraphData {
ScaledDataPoint[] ratioData = new ScaledDataPoint[ratioArray.size()]; ScaledDataPoint[] ratioData = new ScaledDataPoint[ratioArray.size()];
ratioData = ratioArray.toArray(ratioData); ratioData = ratioArray.toArray(ratioData);
ratioSeries = new LineGraphSeries<>(ratioData); ratioSeries = new LineGraphSeries<>(ratioData);
ratioSeries.setColor(MainApp.sResources.getColor(R.color.ratio)); ratioSeries.setColor(MainApp.gc(R.color.ratio));
ratioSeries.setThickness(3); ratioSeries.setThickness(3);
if (useForScale) if (useForScale)
@ -504,13 +519,13 @@ public class GraphData {
ScaledDataPoint[] ratioMaxData = new ScaledDataPoint[dsMaxArray.size()]; ScaledDataPoint[] ratioMaxData = new ScaledDataPoint[dsMaxArray.size()];
ratioMaxData = dsMaxArray.toArray(ratioMaxData); ratioMaxData = dsMaxArray.toArray(ratioMaxData);
dsMaxSeries = new LineGraphSeries<>(ratioMaxData); dsMaxSeries = new LineGraphSeries<>(ratioMaxData);
dsMaxSeries.setColor(Color.MAGENTA); dsMaxSeries.setColor(MainApp.gc(R.color.devslopepos));
dsMaxSeries.setThickness(3); dsMaxSeries.setThickness(3);
ScaledDataPoint[] ratioMinData = new ScaledDataPoint[dsMinArray.size()]; ScaledDataPoint[] ratioMinData = new ScaledDataPoint[dsMinArray.size()];
ratioMinData = dsMinArray.toArray(ratioMinData); ratioMinData = dsMinArray.toArray(ratioMinData);
dsMinSeries = new LineGraphSeries<>(ratioMinData); dsMinSeries = new LineGraphSeries<>(ratioMinData);
dsMinSeries.setColor(Color.YELLOW); dsMinSeries.setColor(MainApp.gc(R.color.devslopeneg));
dsMinSeries.setThickness(3); dsMinSeries.setThickness(3);
if (useForScale) if (useForScale)

View file

@ -55,5 +55,4 @@ public interface DataPointWithLabelInterface extends DataPointInterface{
PointsWithLabelGraphSeries.Shape getShape(); PointsWithLabelGraphSeries.Shape getShape();
float getSize(); float getSize();
int getColor(); int getColor();
int getSecondColor();
} }

View file

@ -3,42 +3,46 @@ package info.nightscout.androidaps.plugins.Overview.graphExtensions;
/** /**
* GraphView * GraphView
* Copyright (C) 2014 Jonas Gehring * Copyright (C) 2014 Jonas Gehring
* * <p>
* This program is free software; you can redistribute it and/or modify * This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, * the Free Software Foundation; either version 2 of the License,
* with the "Linking Exception", which can be found at the license.txt * with the "Linking Exception", which can be found at the license.txt
* file in this program. * file in this program.
* * <p>
* This program is distributed in the hope that it will be useful, * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details. * GNU General Public License for more details.
* * <p>
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* with the "Linking Exception" along with this program; if not, * with the "Linking Exception" along with this program; if not,
* write to the author Jonas Gehring <g.jjoe64@gmail.com>. * write to the author Jonas Gehring <g.jjoe64@gmail.com>.
* <p>
* Added by mike
*/ */
/** /**
* Added by mike * Added by mike
*/ */
import android.content.Context;
import android.graphics.Canvas; import android.graphics.Canvas;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.Path; import android.graphics.Path;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.Rect; import android.graphics.Rect;
import android.graphics.Typeface; import android.graphics.Typeface;
import android.util.TypedValue;
// Added by Rumen for scalable text
import android.content.Context;
import info.nightscout.androidaps.MainApp;
import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.BaseSeries; import com.jjoe64.graphview.series.BaseSeries;
import java.util.Iterator; import java.util.Iterator;
import info.nightscout.androidaps.MainApp;
// Added by Rumen for scalable text
/** /**
* Series that plots the data as points. * Series that plots the data as points.
* The points can be different shapes or a * The points can be different shapes or a
@ -74,7 +78,8 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
OPENAPSOFFLINE, OPENAPSOFFLINE,
EXERCISE, EXERCISE,
GENERAL, GENERAL,
GENERALWITHDURATION GENERALWITHDURATION,
COBFAILOVER
} }
/** /**
@ -148,7 +153,7 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
float scaleX = (float) (graphWidth / diffX); float scaleX = (float) (graphWidth / diffX);
int i=0; int i = 0;
while (values.hasNext()) { while (values.hasNext()) {
E value = values.next(); E value = values.next();
@ -182,7 +187,7 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
} }
/* Fix a bug that continue to show the DOT after Y axis */ /* Fix a bug that continue to show the DOT after Y axis */
if(x < 0) { if (x < 0) {
overdraw = true; overdraw = true;
} }
@ -197,34 +202,33 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
// draw data point // draw data point
if (!overdraw) { if (!overdraw) {
if (value.getShape() == Shape.BG) { if (value.getShape() == Shape.BG || value.getShape() == Shape.COBFAILOVER) {
mPaint.setStyle(Paint.Style.FILL); mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
canvas.drawCircle(endX, endY, scaledPxSize, mPaint); canvas.drawCircle(endX, endY, value.getSize() * scaledPxSize, mPaint);
} else if (value.getShape() == Shape.PREDICTION) { } else if (value.getShape() == Shape.PREDICTION) {
mPaint.setColor(value.getColor()); mPaint.setColor(value.getColor());
mPaint.setStyle(Paint.Style.FILL); mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
canvas.drawCircle(endX, endY, scaledPxSize, mPaint); canvas.drawCircle(endX, endY, scaledPxSize, mPaint);
mPaint.setColor(value.getSecondColor());
mPaint.setStyle(Paint.Style.FILL); mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
canvas.drawCircle(endX, endY, scaledPxSize / 3, mPaint); canvas.drawCircle(endX, endY, scaledPxSize / 3, mPaint);
} else if (value.getShape() == Shape.RECTANGLE) { } else if (value.getShape() == Shape.RECTANGLE) {
canvas.drawRect(endX-scaledPxSize, endY-scaledPxSize, endX+scaledPxSize, endY+scaledPxSize, mPaint); canvas.drawRect(endX - scaledPxSize, endY - scaledPxSize, endX + scaledPxSize, endY + scaledPxSize, mPaint);
} else if (value.getShape() == Shape.TRIANGLE) { } else if (value.getShape() == Shape.TRIANGLE) {
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
Point[] points = new Point[3]; Point[] points = new Point[3];
points[0] = new Point((int)endX, (int)(endY-scaledPxSize)); points[0] = new Point((int) endX, (int) (endY - scaledPxSize));
points[1] = new Point((int)(endX+scaledPxSize), (int)(endY+scaledPxSize*0.67)); points[1] = new Point((int) (endX + scaledPxSize), (int) (endY + scaledPxSize * 0.67));
points[2] = new Point((int)(endX-scaledPxSize), (int)(endY+scaledPxSize*0.67)); points[2] = new Point((int) (endX - scaledPxSize), (int) (endY + scaledPxSize * 0.67));
drawArrows(points, canvas, mPaint); drawArrows(points, canvas, mPaint);
} else if (value.getShape() == Shape.BOLUS) { } else if (value.getShape() == Shape.BOLUS) {
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
Point[] points = new Point[3]; Point[] points = new Point[3];
points[0] = new Point((int)endX, (int)(endY-scaledPxSize)); points[0] = new Point((int) endX, (int) (endY - scaledPxSize));
points[1] = new Point((int)(endX+scaledPxSize), (int)(endY+scaledPxSize*0.67)); points[1] = new Point((int) (endX + scaledPxSize), (int) (endY + scaledPxSize * 0.67));
points[2] = new Point((int)(endX-scaledPxSize), (int)(endY+scaledPxSize*0.67)); points[2] = new Point((int) (endX - scaledPxSize), (int) (endY + scaledPxSize * 0.67));
mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
drawArrows(points, canvas, mPaint); drawArrows(points, canvas, mPaint);
if (value.getLabel() != null) { if (value.getLabel() != null) {
@ -234,15 +238,15 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
mPaint.setStrokeWidth(2); mPaint.setStrokeWidth(2);
Point[] points = new Point[3]; Point[] points = new Point[3];
float size = value.getSize() * scaledPxSize; float size = value.getSize() * scaledPxSize;
points[0] = new Point((int)endX, (int)(endY-size)); points[0] = new Point((int) endX, (int) (endY - size));
points[1] = new Point((int)(endX+size), (int)(endY+size*0.67)); points[1] = new Point((int) (endX + size), (int) (endY + size * 0.67));
points[2] = new Point((int)(endX-size), (int)(endY+size*0.67)); points[2] = new Point((int) (endX - size), (int) (endY + size * 0.67));
mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
drawArrows(points, canvas, mPaint); drawArrows(points, canvas, mPaint);
} else if (value.getShape() == Shape.EXTENDEDBOLUS) { } else if (value.getShape() == Shape.EXTENDEDBOLUS) {
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
if (value.getLabel() != null) { if (value.getLabel() != null) {
Rect bounds = new Rect((int)endX, (int)endY + 3, (int) (xpluslength), (int) endY + 8); Rect bounds = new Rect((int) endX, (int) endY + 3, (int) (xpluslength), (int) endY + 8);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE); mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawRect(bounds, mPaint); canvas.drawRect(bounds, mPaint);
mPaint.setTextSize((float) (scaledTextSize)); mPaint.setTextSize((float) (scaledTextSize));
@ -254,7 +258,7 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
mPaint.setStrokeWidth(0); mPaint.setStrokeWidth(0);
if (value.getLabel() != null) { if (value.getLabel() != null) {
//mPaint.setTextSize((int) (scaledPxSize * 3)); //mPaint.setTextSize((int) (scaledPxSize * 3));
mPaint.setTextSize((float) (scaledTextSize*1.2)); mPaint.setTextSize((float) (scaledTextSize * 1.2));
mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD)); mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
Rect bounds = new Rect(); Rect bounds = new Rect();
mPaint.getTextBounds(value.getLabel(), 0, value.getLabel().length(), bounds); mPaint.getTextBounds(value.getLabel(), 0, value.getLabel().length(), bounds);
@ -355,7 +359,7 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
* @param paint paint object * @param paint paint object
*/ */
private void drawArrows(Point[] point, Canvas canvas, Paint paint) { private void drawArrows(Point[] point, Canvas canvas, Paint paint) {
float [] points = new float[8]; float[] points = new float[8];
points[0] = point[0].x; points[0] = point[0].x;
points[1] = point[0].y; points[1] = point[0].y;
points[2] = point[1].x; points[2] = point[1].x;
@ -368,10 +372,10 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
canvas.save(); canvas.save();
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint); canvas.drawVertices(Canvas.VertexMode.TRIANGLES, 8, points, 0, null, 0, null, 0, null, 0, 0, paint);
Path path = new Path(); Path path = new Path();
path.moveTo(point[0].x , point[0].y); path.moveTo(point[0].x, point[0].y);
path.lineTo(point[1].x,point[1].y); path.lineTo(point[1].x, point[1].y);
path.lineTo(point[2].x,point[2].y); path.lineTo(point[2].x, point[2].y);
canvas.drawPath(path,paint); canvas.drawPath(path, paint);
canvas.restore(); canvas.restore();
} }
@ -381,7 +385,7 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
float py = endY + scaledPxSize; float py = endY + scaledPxSize;
canvas.save(); canvas.save();
canvas.rotate(-45, px, py); canvas.rotate(-45, px, py);
mPaint.setTextSize((float) (scaledTextSize*0.8)); mPaint.setTextSize((float) (scaledTextSize * 0.8));
mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
mPaint.setFakeBoldText(true); mPaint.setFakeBoldText(true);
mPaint.setTextAlign(Paint.Align.RIGHT); mPaint.setTextAlign(Paint.Align.RIGHT);
@ -393,7 +397,7 @@ public class PointsWithLabelGraphSeries<E extends DataPointWithLabelInterface> e
float py = endY - scaledPxSize; float py = endY - scaledPxSize;
canvas.save(); canvas.save();
canvas.rotate(-45, px, py); canvas.rotate(-45, px, py);
mPaint.setTextSize((float) (scaledTextSize*0.8)); mPaint.setTextSize((float) (scaledTextSize * 0.8));
mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL)); mPaint.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.NORMAL));
mPaint.setFakeBoldText(true); mPaint.setFakeBoldText(true);
canvas.drawText(value.getLabel(), px + scaledPxSize, py, mPaint); canvas.drawText(value.getLabel(), px + scaledPxSize, py, mPaint);

View file

@ -94,7 +94,7 @@ public class NotificationRecyclerViewAdapter extends RecyclerView.Adapter<Notifi
} }
// Adding current time to snooze if we got staleData // Adding current time to snooze if we got staleData
log.debug("Notification text is: " + notification.text); log.debug("Notification text is: " + notification.text);
if (notification.text.equals(MainApp.sResources.getString(R.string.nsalarm_staledata))) { if (notification.text.equals(MainApp.gs(R.string.nsalarm_staledata))) {
NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore; NotificationStore nstore = OverviewPlugin.getPlugin().notificationStore;
long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L; long msToSnooze = SP.getInt("nsalarm_staledatavalue", 15) * 60 * 1000L;
log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis()); log.debug("snooze nsalarm_staledatavalue in minutes is " + SP.getInt("nsalarm_staledatavalue", 15) + "\n in ms is: " + msToSnooze + " currentTimeMillis is: " + System.currentTimeMillis());

View file

@ -37,6 +37,7 @@ public class NotificationStore {
private static Logger log = LoggerFactory.getLogger(NotificationStore.class); private static Logger log = LoggerFactory.getLogger(NotificationStore.class);
public List<Notification> store = new ArrayList<Notification>(); public List<Notification> store = new ArrayList<Notification>();
public long snoozedUntil = 0L; public long snoozedUntil = 0L;
private boolean usesChannels;
public NotificationStore() { public NotificationStore() {
createNotificationChannel(); createNotificationChannel();
@ -60,8 +61,14 @@ public class NotificationStore {
} }
store.add(n); store.add(n);
if (SP.getBoolean(MainApp.sResources.getString(R.string.key_raise_notifications_as_android_notifications), false)) { if (SP.getBoolean(MainApp.gs(R.string.key_raise_notifications_as_android_notifications), false)) {
raiseSystemNotification(n); raiseSystemNotification(n);
if (usesChannels && n.soundId != null) {
Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class);
alarm.putExtra("soundid", n.soundId);
MainApp.instance().startService(alarm);
}
} else { } else {
if (n.soundId != null) { if (n.soundId != null) {
Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class); Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class);
@ -105,7 +112,7 @@ public class NotificationStore {
public void unSnooze() { public void unSnooze() {
if (Notification.isAlarmForStaleData()) { if (Notification.isAlarmForStaleData()) {
Notification notification = new Notification(Notification.NSALARM, MainApp.sResources.getString(R.string.nsalarm_staledata), Notification.URGENT); Notification notification = new Notification(Notification.NSALARM, MainApp.gs(R.string.nsalarm_staledata), Notification.URGENT);
SP.putLong("snoozedTo", System.currentTimeMillis()); SP.putLong("snoozedTo", System.currentTimeMillis());
add(notification); add(notification);
log.debug("Snoozed to current time and added back notification!"); log.debug("Snoozed to current time and added back notification!");
@ -126,11 +133,11 @@ public class NotificationStore {
.setDeleteIntent(DismissNotificationService.deleteIntent(n.id)); .setDeleteIntent(DismissNotificationService.deleteIntent(n.id));
if (n.level == Notification.URGENT) { if (n.level == Notification.URGENT) {
notificationBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000}) notificationBuilder.setVibrate(new long[]{1000, 1000, 1000, 1000})
.setContentTitle(MainApp.sResources.getString(R.string.urgent_alarm)) .setContentTitle(MainApp.gs(R.string.urgent_alarm))
.setSound(sound, AudioAttributes.USAGE_ALARM); .setSound(sound, AudioAttributes.USAGE_ALARM);
} else { } else {
notificationBuilder.setVibrate(new long[]{0, 100, 50, 100, 50}) notificationBuilder.setVibrate(new long[]{0, 100, 50, 100, 50})
.setContentTitle(MainApp.sResources.getString(R.string.info)) .setContentTitle(MainApp.gs(R.string.info))
; ;
} }
mgr.notify(n.id, notificationBuilder.build()); mgr.notify(n.id, notificationBuilder.build());
@ -138,7 +145,7 @@ public class NotificationStore {
private void createNotificationChannel() { private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
usesChannels = true;
NotificationManager mNotificationManager = NotificationManager mNotificationManager =
(NotificationManager) MainApp.instance().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE); (NotificationManager) MainApp.instance().getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
@SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID, @SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID,

View file

@ -35,6 +35,8 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.utils.DecimalFormatter;
@ -92,7 +94,7 @@ public class PersistentNotificationPlugin extends PluginBase {
return; return;
} }
String line1 = ctx.getString(R.string.noprofile); String line1 = "";
if (MainApp.getConfigBuilder().getActiveProfileInterface() == null || !MainApp.getConfigBuilder().isProfileValid("Notificiation")) if (MainApp.getConfigBuilder().getActiveProfileInterface() == null || !MainApp.getConfigBuilder().isProfileValid("Notificiation"))
return; return;
@ -109,9 +111,11 @@ public class PersistentNotificationPlugin extends PluginBase {
+ " avgΔ" + deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units); + " avgΔ" + deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units);
} else { } else {
line1 += " " + line1 += " " +
ctx.getString(R.string.old_data) + MainApp.gs(R.string.old_data) +
" "; " ";
} }
} else {
line1 = MainApp.gs(R.string.missed_bg_readings);
} }
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
@ -125,10 +129,8 @@ public class PersistentNotificationPlugin extends PluginBase {
IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round(); IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round();
IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round(); IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round();
String line2 = ctx.getString(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ ctx.getString(R.string.bolus) + ": " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ ctx.getString(R.string.basal) + ": " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
String line2 = MainApp.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + MainApp.gs(R.string.cob)+": " + IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "PersistentNotificationPlugin").generateCOBString();;
String line3 = DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getActivePump().getBaseBasalRate()) + " U/h"; String line3 = DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getActivePump().getBaseBasalRate()) + " U/h";
@ -138,6 +140,7 @@ public class PersistentNotificationPlugin extends PluginBase {
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID); NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID);
builder.setOngoing(true); builder.setOngoing(true);
builder.setOnlyAlertOnce(true);
builder.setCategory(NotificationCompat.CATEGORY_STATUS); builder.setCategory(NotificationCompat.CATEGORY_STATUS);
builder.setSmallIcon(R.drawable.ic_notification); builder.setSmallIcon(R.drawable.ic_notification);
Bitmap largeIcon = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.blueowl); Bitmap largeIcon = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.blueowl);

View file

@ -57,7 +57,7 @@ public class LocalProfileFragment extends SubscriberFragment {
Runnable save = () -> { Runnable save = () -> {
doEdit(); doEdit();
if (basalView != null) { if (basalView != null) {
basalView.updateLabel(MainApp.sResources.getString(R.string.nsprofileview_basal_label) + ": " + getSumLabel()); basalView.updateLabel(MainApp.gs(R.string.nsprofileview_basal_label) + ": " + getSumLabel());
} }
}; };
@ -91,10 +91,10 @@ public class LocalProfileFragment extends SubscriberFragment {
diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch); diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch);
mgdlView = (RadioButton) layout.findViewById(R.id.localprofile_mgdl); mgdlView = (RadioButton) layout.findViewById(R.id.localprofile_mgdl);
mmolView = (RadioButton) layout.findViewById(R.id.localprofile_mmol); mmolView = (RadioButton) layout.findViewById(R.id.localprofile_mmol);
icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.sResources.getString(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save); icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.gs(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save);
isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.sResources.getString(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save); isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.gs(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save);
basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.sResources.getString(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save); basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.gs(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save);
targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.sResources.getString(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save); targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.gs(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save);
profileswitchButton = (Button) layout.findViewById(R.id.localprofile_profileswitch); profileswitchButton = (Button) layout.findViewById(R.id.localprofile_profileswitch);
resetButton = (Button) layout.findViewById(R.id.localprofile_reset); resetButton = (Button) layout.findViewById(R.id.localprofile_reset);
saveButton = (Button) layout.findViewById(R.id.localprofile_save); saveButton = (Button) layout.findViewById(R.id.localprofile_save);
@ -144,10 +144,10 @@ public class LocalProfileFragment extends SubscriberFragment {
mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl); mgdlView.setChecked(LocalProfilePlugin.getPlugin().mgdl);
mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol); mmolView.setChecked(LocalProfilePlugin.getPlugin().mmol);
diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch); diaView.setParams(LocalProfilePlugin.getPlugin().dia, 2d, 48d, 0.1d, new DecimalFormat("0.0"), false, textWatch);
icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.sResources.getString(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save); icView = new TimeListEdit(getContext(), layout, R.id.localprofile_ic, MainApp.gs(R.string.nsprofileview_ic_label) + ":", LocalProfilePlugin.getPlugin().ic, null, 0.5, 50d, 0.1d, new DecimalFormat("0.0"), save);
isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.sResources.getString(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save); isfView = new TimeListEdit(getContext(), layout, R.id.localprofile_isf, MainApp.gs(R.string.nsprofileview_isf_label) + ":", LocalProfilePlugin.getPlugin().isf, null, 0.5, 500d, 0.1d, new DecimalFormat("0.0"), save);
basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.sResources.getString(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save); basalView = new TimeListEdit(getContext(), layout, R.id.localprofile_basal, MainApp.gs(R.string.nsprofileview_basal_label) + ": " + getSumLabel(), LocalProfilePlugin.getPlugin().basal, null, pumpDescription.basalMinimumRate, 10, 0.01d, new DecimalFormat("0.00"), save);
targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.sResources.getString(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save); targetView = new TimeListEdit(getContext(), layout, R.id.localprofile_target, MainApp.gs(R.string.nsprofileview_target_label) + ":", LocalProfilePlugin.getPlugin().targetLow, LocalProfilePlugin.getPlugin().targetHigh, 3d, 200, 0.1d, new DecimalFormat("0.0"), save);
updateGUI(); updateGUI();
}); });
@ -199,22 +199,14 @@ public class LocalProfileFragment extends SubscriberFragment {
if (isValid) { if (isValid) {
invalidProfile.setVisibility(View.GONE); //show invalid profile invalidProfile.setVisibility(View.GONE); //show invalid profile
if (isEdited || !ConfigBuilderPlugin.getActivePump().isInitialized() || ConfigBuilderPlugin.getActivePump().isSuspended()) { if (isEdited) {
//edited profile -> save first //edited profile -> save first
//pump not initialized -> don't update profile yet
profileswitchButton.setVisibility(View.GONE); profileswitchButton.setVisibility(View.GONE);
} else {
profileswitchButton.setVisibility(View.VISIBLE);
}
if(isEdited){
saveButton.setVisibility(View.VISIBLE); saveButton.setVisibility(View.VISIBLE);
} else { } else {
profileswitchButton.setVisibility(View.VISIBLE);
saveButton.setVisibility(View.GONE); saveButton.setVisibility(View.GONE);
} }
} else { } else {
invalidProfile.setVisibility(View.VISIBLE); invalidProfile.setVisibility(View.VISIBLE);
profileswitchButton.setVisibility(View.GONE); profileswitchButton.setVisibility(View.GONE);

View file

@ -120,12 +120,18 @@ public class ComboFragment extends SubscriberFragment implements View.OnClickLis
// activity // activity
String activity = plugin.getPump().activity; String activity = plugin.getPump().activity;
if (StringUtils.isNotEmpty(activity)) { if (activity != null) {
activityView.setTextColor(Color.WHITE);
activityView.setTextSize(14); activityView.setTextSize(14);
activityView.setText(activity); activityView.setText(activity);
} else { } else if (plugin.isInitialized()){
activityView.setTextColor(Color.WHITE);
activityView.setTextSize(20); activityView.setTextSize(20);
activityView.setText("{fa-bed}"); activityView.setText("{fa-bed}");
} else {
activityView.setTextColor(Color.RED);
activityView.setTextSize(14);
activityView.setText(MainApp.gs(R.string.pump_unreachable));
} }
if (plugin.isInitialized()) { if (plugin.isInitialized()) {
@ -145,7 +151,7 @@ public class ComboFragment extends SubscriberFragment implements View.OnClickLis
// reservoir // reservoir
int reservoirLevel = plugin.getPump().reservoirLevel; int reservoirLevel = plugin.getPump().reservoirLevel;
if (reservoirLevel != -1) { if (reservoirLevel != -1) {
reservoirView.setText(reservoirLevel + " " + MainApp.sResources.getString(R.string.insulin_unit_shortname)); reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname));
} else if (ps.insulinState == PumpState.LOW) { } else if (ps.insulinState == PumpState.LOW) {
reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low)); reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low));
} else if (ps.insulinState == PumpState.EMPTY) { } else if (ps.insulinState == PumpState.EMPTY) {

View file

@ -151,7 +151,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
/** /**
* Cache of the last <=2 boluses on the pump. Used to detect changes in pump history, * Cache of the last <=2 boluses on the pump. Used to detect changes in pump history,
* requiring reading pump more history. This is read/set in {@link #checkHistory()} when changed * requiring reading more pump history. This is read/set in {@link #checkHistory()} when changed
* pump history was detected and was read, as well as in {@link #deliverBolus(DetailedBolusInfo)} * pump history was detected and was read, as well as in {@link #deliverBolus(DetailedBolusInfo)}
* after bolus delivery. Newest record is the first one. * after bolus delivery. Newest record is the first one.
*/ */
@ -326,7 +326,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
} }
/** /**
* Runs pump initializing if needed and reads the pump state from the main screen. * Runs pump initialization if needed and reads the pump state from the main screen.
*/ */
@Override @Override
public synchronized void getPumpStatus() { public synchronized void getPumpStatus() {
@ -442,8 +442,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
case STOPPED: case STOPPED:
event.status = MainApp.gs(R.string.bolusstopped); event.status = MainApp.gs(R.string.bolusstopped);
break; break;
case RECOVERING:
event.status = MainApp.gs(R.string.combo_error_bolus_recovery_progress);
} }
event.percent = percent; event.percent = percent;
MainApp.bus().post(event); MainApp.bus().post(event);
@ -460,7 +458,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
log.error("deliverTreatment: Invalid input"); log.error("deliverTreatment: Invalid input");
return new PumpEnactResult().success(false).enacted(false) return new PumpEnactResult().success(false).enacted(false)
.bolusDelivered(0d).carbsDelivered(0d) .bolusDelivered(0d).carbsDelivered(0d)
.comment(MainApp.instance().getString(R.string.danar_invalidinput)); .comment(MainApp.gs(R.string.danar_invalidinput));
} else if (detailedBolusInfo.insulin > 0) { } else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it // bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo); return deliverBolus(detailedBolusInfo);
@ -476,7 +474,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
return new PumpEnactResult().success(true).enacted(true) return new PumpEnactResult().success(true).enacted(true)
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(MainApp.instance().getString(R.string.virtualpump_resultok)); .comment(MainApp.gs(R.string.virtualpump_resultok));
} }
} finally { } finally {
MainApp.bus().post(new EventComboPumpUpdateGUI()); MainApp.bus().post(new EventComboPumpUpdateGUI());

View file

@ -95,22 +95,22 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
} }
if (!isInitialized()) { if (!isInitialized()) {
log.error("setNewBasalProfile not initialized"); log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet); result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
return result; return result;
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
} }
if (!sExecutionService.updateBasalsInPump(profile)) { if (!sExecutionService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.sResources.getString(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.sResources.getString(R.string.failedupdatebasalprofile); result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
return result; return result;
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.sResources.getString(R.string.profile_set_ok), Notification.INFO, 60); Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.success = true; result.success = true;
result.enacted = true; result.enacted = true;
@ -166,7 +166,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
result.isTempCancel = false; result.isTempCancel = false;
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput); result.comment = MainApp.gs(R.string.danar_invalidinput);
log.error("setTempBasalPercent: Invalid input"); log.error("setTempBasalPercent: Invalid input");
return result; return result;
} }
@ -178,7 +178,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
result.enacted = false; result.enacted = false;
result.success = true; result.success = true;
result.isTempCancel = false; result.isTempCancel = false;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
result.isPercent = true; result.isPercent = true;
@ -191,7 +191,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) { if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
@ -202,7 +202,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.tempbasaldeliveryerror); result.comment = MainApp.gs(R.string.tempbasaldeliveryerror);
log.error("setTempBasalPercent: Failed to set temp basal"); log.error("setTempBasalPercent: Failed to set temp basal");
return result; return result;
} }
@ -219,7 +219,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = false; result.enacted = false;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.duration = pump.extendedBolusRemainingMinutes; result.duration = pump.extendedBolusRemainingMinutes;
result.absolute = pump.extendedBolusAbsoluteRate; result.absolute = pump.extendedBolusAbsoluteRate;
result.isPercent = false; result.isPercent = false;
@ -232,7 +232,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAmount - insulin) < getPumpDescription().extendedBolusStep) { if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAmount - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.extendedBolusRemainingMinutes; result.duration = pump.extendedBolusRemainingMinutes;
result.absolute = pump.extendedBolusAbsoluteRate; result.absolute = pump.extendedBolusAbsoluteRate;
@ -245,7 +245,7 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
log.error("setExtendedBolus: Failed to extended bolus"); log.error("setExtendedBolus: Failed to extended bolus");
return result; return result;
} }
@ -261,13 +261,13 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
} }
if (!pump.isExtendedInProgress) { if (!pump.isExtendedInProgress) {
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("cancelExtendedBolus: OK"); log.debug("cancelExtendedBolus: OK");
return result; return result;
} else { } else {
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
log.error("cancelExtendedBolus: Failed to cancel extended bolus"); log.error("cancelExtendedBolus: Failed to cancel extended bolus");
return result; return result;
} }
@ -304,7 +304,11 @@ public abstract class AbstractDanaRPlugin extends PluginBase implements PumpInte
@Override @Override
public void getPumpStatus() { public void getPumpStatus() {
if (sExecutionService != null) sExecutionService.getPumpStatus(); if (sExecutionService != null) {
sExecutionService.getPumpStatus();
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
}
} }
@Override @Override

View file

@ -206,7 +206,7 @@ public class DanaRFragment extends SubscriberFragment {
if (pump.lastConnection != 0) { if (pump.lastConnection != 0) {
Long agoMsec = System.currentTimeMillis() - pump.lastConnection; Long agoMsec = System.currentTimeMillis() - pump.lastConnection;
int agoMin = (int) (agoMsec / 60d / 1000d); int agoMin = (int) (agoMsec / 60d / 1000d);
lastConnectionView.setText(DateUtil.timeString(pump.lastConnection) + " (" + String.format(MainApp.sResources.getString(R.string.minago), agoMin) + ")"); lastConnectionView.setText(DateUtil.timeString(pump.lastConnection) + " (" + String.format(MainApp.gs(R.string.minago), agoMin) + ")");
SetWarnColor.setColor(lastConnectionView, agoMin, 16d, 31d); SetWarnColor.setColor(lastConnectionView, agoMin, 16d, 31d);
} }
if (pump.lastBolusTime.getTime() != 0) { if (pump.lastBolusTime.getTime() != 0) {
@ -247,7 +247,7 @@ public class DanaRFragment extends SubscriberFragment {
SetWarnColor.setColorInverse(batteryView, pump.batteryRemaining, 51d, 26d); SetWarnColor.setColorInverse(batteryView, pump.batteryRemaining, 51d, 26d);
iobView.setText(pump.iob + " U"); iobView.setText(pump.iob + " U");
if (pump.model != 0 || pump.protocol != 0 || pump.productCode != 0) { if (pump.model != 0 || pump.protocol != 0 || pump.productCode != 0) {
firmwareView.setText(String.format(MainApp.sResources.getString(R.string.danar_model), pump.model, pump.protocol, pump.productCode)); firmwareView.setText(String.format(MainApp.gs(R.string.danar_model), pump.model, pump.protocol, pump.productCode));
} else { } else {
firmwareView.setText("OLD"); firmwareView.setText("OLD");
} }

View file

@ -18,6 +18,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStartWithSpeed;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
@ -71,7 +72,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
pumpDescription.isRefillingCapable = true; pumpDescription.isRefillingCapable = true;
pumpDescription.storesCarbInfo = true; pumpDescription.storesCarbInfo = false;
pumpDescription.supportsTDDs = true; pumpDescription.supportsTDDs = true;
pumpDescription.needsManualTDDLoad = true; pumpDescription.needsManualTDDLoad = true;
@ -129,7 +130,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
// Plugin base interface // Plugin base interface
@Override @Override
public String getName() { public String getName() {
return MainApp.instance().getString(R.string.danarpump); return MainApp.gs(R.string.danarpump);
} }
@Override @Override
@ -158,10 +159,13 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0)
connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t); connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t);
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = connectionOK; result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep;
result.bolusDelivered = t.insulin; result.bolusDelivered = t.insulin;
result.carbsDelivered = detailedBolusInfo.carbs; result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); if (!result.success)
result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStartWithSpeed.errorCode);
else
result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.insulin = t.insulin; detailedBolusInfo.insulin = t.insulin;
@ -173,7 +177,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
result.success = false; result.success = false;
result.bolusDelivered = 0d; result.bolusDelivered = 0d;
result.carbsDelivered = 0d; result.carbsDelivered = 0d;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput); result.comment = MainApp.gs(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input"); log.error("deliverTreatment: Invalid input");
return result; return result;
} }
@ -342,7 +346,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = true; result.success = true;
result.enacted = false; result.enacted = false;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = true; result.isTempCancel = true;
return result; return result;
} }
@ -358,13 +362,13 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
if (!pump.isTempBasalInProgress) { if (!pump.isTempBasalInProgress) {
result.success = true; result.success = true;
result.isTempCancel = true; result.isTempCancel = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("cancelRealTempBasal: OK"); log.debug("cancelRealTempBasal: OK");
return result; return result;
} else { } else {
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
result.isTempCancel = true; result.isTempCancel = true;
log.error("cancelRealTempBasal: Failed to cancel temp basal"); log.error("cancelRealTempBasal: Failed to cancel temp basal");
return result; return result;

View file

@ -122,20 +122,20 @@ public class DanaRHistoryActivity extends Activity {
// Types // Types
ArrayList<TypeList> typeList = new ArrayList<>(); ArrayList<TypeList> typeList = new ArrayList<>();
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_ALARM, getString(R.string.danar_history_alarm))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_ALARM, MainApp.gs(R.string.danar_history_alarm)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, getString(R.string.danar_history_basalhours))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_BASALHOUR, MainApp.gs(R.string.danar_history_basalhours)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_BOLUS, getString(R.string.danar_history_bolus))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_BOLUS, MainApp.gs(R.string.danar_history_bolus)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_CARBO, getString(R.string.danar_history_carbohydrates))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_CARBO, MainApp.gs(R.string.danar_history_carbohydrates)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_DAILY, getString(R.string.danar_history_dailyinsulin))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_DAILY, MainApp.gs(R.string.danar_history_dailyinsulin)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_GLUCOSE, getString(R.string.danar_history_glucose))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_GLUCOSE, MainApp.gs(R.string.danar_history_glucose)));
if (!isKorean && !isRS) { if (!isKorean && !isRS) {
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_ERROR, getString(R.string.danar_history_errors))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_ERROR, MainApp.gs(R.string.danar_history_errors)));
} }
if (isRS) if (isRS)
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_PRIME, getString(R.string.danar_history_prime))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_PRIME, MainApp.gs(R.string.danar_history_prime)));
if (!isKorean) { if (!isKorean) {
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_REFILL, getString(R.string.danar_history_refill))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_REFILL, MainApp.gs(R.string.danar_history_refill)));
typeList.add(new TypeList(RecordTypes.RECORD_TYPE_SUSPEND, getString(R.string.danar_history_syspend))); typeList.add(new TypeList(RecordTypes.RECORD_TYPE_SUSPEND, MainApp.gs(R.string.danar_history_syspend)));
} }
ArrayAdapter<TypeList> spinnerAdapter = new ArrayAdapter<>(this, ArrayAdapter<TypeList> spinnerAdapter = new ArrayAdapter<>(this,
R.layout.spinner_centered, typeList); R.layout.spinner_centered, typeList);
@ -215,7 +215,7 @@ public class DanaRHistoryActivity extends Activity {
}); });
profile = MainApp.getConfigBuilder().getProfile(); profile = MainApp.getConfigBuilder().getProfile();
if (profile == null) { if (profile == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.noprofile)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.noprofile));
finish(); finish();
} }
} }

View file

@ -57,7 +57,7 @@ public class DanaRNSHistorySync {
if (record._id != null) continue; if (record._id != null) continue;
//log.debug(record.bytes); //log.debug(record.bytes);
JSONObject nsrec = new JSONObject(); JSONObject nsrec = new JSONObject();
ev.message = MainApp.sResources.getString(R.string.uploading) + " " + processing + "/" + records + " "; // TODO: translations ev.message = MainApp.gs(R.string.uploading) + " " + processing + "/" + records + " "; // TODO: translations
switch (record.recordCode) { switch (record.recordCode) {
case RecordTypes.RECORD_TYPE_BOLUS: case RecordTypes.RECORD_TYPE_BOLUS:
if ((what & SYNC_BOLUS) == 0) break; if ((what & SYNC_BOLUS) == 0) break;
@ -68,10 +68,10 @@ public class DanaRNSHistorySync {
nsrec.put("eventType", "Meal Bolus"); nsrec.put("eventType", "Meal Bolus");
nsrec.put("insulin", record.recordValue); nsrec.put("insulin", record.recordValue);
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_sbolus); ev.message += MainApp.gs(R.string.danar_sbolus);
break; break;
case "E": case "E":
if (record.recordDuration > 0) { if (record.recordDuration > 0) {
@ -86,10 +86,10 @@ public class DanaRNSHistorySync {
cal.setTimeInMillis(record.recordDate); cal.setTimeInMillis(record.recordDate);
cal.add(Calendar.MINUTE, -1 * record.recordDuration); cal.add(Calendar.MINUTE, -1 * record.recordDuration);
nsrec.put("created_at", DateUtil.toISOString(cal.getTime())); nsrec.put("created_at", DateUtil.toISOString(cal.getTime()));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_ebolus); ev.message += MainApp.gs(R.string.danar_ebolus);
} else { } else {
log.debug("NOT Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate) + " zero duration"); log.debug("NOT Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate) + " zero duration");
} }
@ -102,10 +102,10 @@ public class DanaRNSHistorySync {
nsrec.put("splitNow", 100); nsrec.put("splitNow", 100);
nsrec.put("splitExt", 0); nsrec.put("splitExt", 0);
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_dsbolus); ev.message += MainApp.gs(R.string.danar_dsbolus);
break; break;
case "DE": case "DE":
log.debug("Syncing dual(E) bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate)); log.debug("Syncing dual(E) bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate));
@ -118,10 +118,10 @@ public class DanaRNSHistorySync {
cal.setTimeInMillis(record.recordDate); cal.setTimeInMillis(record.recordDate);
cal.add(Calendar.MINUTE, -1 * record.recordDuration); cal.add(Calendar.MINUTE, -1 * record.recordDuration);
nsrec.put("created_at", DateUtil.toISOString(cal.getTime())); nsrec.put("created_at", DateUtil.toISOString(cal.getTime()));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_debolus); ev.message += MainApp.gs(R.string.danar_debolus);
break; break;
default: default:
log.debug("Unknown bolus record"); log.debug("Unknown bolus record");
@ -135,10 +135,10 @@ public class DanaRNSHistorySync {
nsrec.put("eventType", "Note"); nsrec.put("eventType", "Note");
nsrec.put("notes", "Error"); nsrec.put("notes", "Error");
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_error); ev.message += MainApp.gs(R.string.danar_error);
break; break;
case RecordTypes.RECORD_TYPE_REFILL: case RecordTypes.RECORD_TYPE_REFILL:
if ((what & SYNC_REFILL) == 0) break; if ((what & SYNC_REFILL) == 0) break;
@ -147,10 +147,10 @@ public class DanaRNSHistorySync {
nsrec.put("eventType", "Insulin Change"); nsrec.put("eventType", "Insulin Change");
nsrec.put("notes", "Refill " + record.recordValue + "U"); nsrec.put("notes", "Refill " + record.recordValue + "U");
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_refill); ev.message += MainApp.gs(R.string.danar_refill);
break; break;
case RecordTypes.RECORD_TYPE_BASALHOUR: case RecordTypes.RECORD_TYPE_BASALHOUR:
if ((what & SYNC_BASALHOURS) == 0) break; if ((what & SYNC_BASALHOURS) == 0) break;
@ -160,10 +160,10 @@ public class DanaRNSHistorySync {
nsrec.put("absolute", record.recordValue); nsrec.put("absolute", record.recordValue);
nsrec.put("duration", 60); nsrec.put("duration", 60);
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_basalhour); ev.message += MainApp.gs(R.string.danar_basalhour);
break; break;
case RecordTypes.RECORD_TYPE_TB: case RecordTypes.RECORD_TYPE_TB:
//log.debug("Ignoring TB record " + record.bytes + " " + DateUtil.toISOString(record.recordDate)); //log.debug("Ignoring TB record " + record.bytes + " " + DateUtil.toISOString(record.recordDate));
@ -176,10 +176,10 @@ public class DanaRNSHistorySync {
nsrec.put("glucose", Profile.fromMgdlToUnits(record.recordValue, MainApp.getConfigBuilder().getProfileUnits())); nsrec.put("glucose", Profile.fromMgdlToUnits(record.recordValue, MainApp.getConfigBuilder().getProfileUnits()));
nsrec.put("glucoseType", "Finger"); nsrec.put("glucoseType", "Finger");
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_glucose); ev.message += MainApp.gs(R.string.danar_glucose);
break; break;
case RecordTypes.RECORD_TYPE_CARBO: case RecordTypes.RECORD_TYPE_CARBO:
if ((what & SYNC_CARBO) == 0) break; if ((what & SYNC_CARBO) == 0) break;
@ -188,10 +188,10 @@ public class DanaRNSHistorySync {
nsrec.put("eventType", "Meal Bolus"); nsrec.put("eventType", "Meal Bolus");
nsrec.put("carbs", record.recordValue); nsrec.put("carbs", record.recordValue);
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_carbohydrate); ev.message += MainApp.gs(R.string.danar_carbohydrate);
break; break;
case RecordTypes.RECORD_TYPE_ALARM: case RecordTypes.RECORD_TYPE_ALARM:
if ((what & SYNC_ALARM) == 0) break; if ((what & SYNC_ALARM) == 0) break;
@ -200,10 +200,10 @@ public class DanaRNSHistorySync {
nsrec.put("eventType", "Note"); nsrec.put("eventType", "Note");
nsrec.put("notes", "Alarm: " + record.recordAlarm); nsrec.put("notes", "Alarm: " + record.recordAlarm);
nsrec.put("created_at", DateUtil.toISOString(record.recordDate)); nsrec.put("created_at", DateUtil.toISOString(record.recordDate));
nsrec.put("enteredBy", "openaps://" + MainApp.sResources.getString(R.string.app_name)); nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec); NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++; uploaded++;
ev.message += MainApp.sResources.getString(R.string.danar_alarm); ev.message += MainApp.gs(R.string.danar_alarm);
break; break;
case RecordTypes.RECORD_TYPE_SUSPEND: // TODO: this too case RecordTypes.RECORD_TYPE_SUSPEND: // TODO: this too
case RecordTypes.RECORD_TYPE_DAILY: case RecordTypes.RECORD_TYPE_DAILY:
@ -216,7 +216,7 @@ public class DanaRNSHistorySync {
} }
MainApp.bus().post(ev); MainApp.bus().post(ev);
} }
ev.message = String.format(MainApp.sResources.getString(R.string.danar_totaluploaded), uploaded); ev.message = String.format(MainApp.gs(R.string.danar_totaluploaded), uploaded);
MainApp.bus().post(ev); MainApp.bus().post(ev);
} catch (JSONException e) { } catch (JSONException e) {

View file

@ -36,7 +36,7 @@ public class MsgBolusProgress extends MessageBase {
Double done = (amount * 100 - progress) / 100d; Double done = (amount * 100 - progress) / 100d;
t.insulin = done; t.insulin = done;
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.status = String.format(MainApp.sResources.getString(R.string.bolusdelivering), done); bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), done);
bolusingEvent.t = t; bolusingEvent.t = t;
bolusingEvent.percent = Math.min((int) (done / amount * 100), 100); bolusingEvent.percent = Math.min((int) (done / amount * 100), 100);

View file

@ -11,6 +11,8 @@ import info.nightscout.utils.HardLimits;
public class MsgBolusStart extends MessageBase { public class MsgBolusStart extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgBolusStart.class); private static Logger log = LoggerFactory.getLogger(MsgBolusStart.class);
public static int errorCode;
public MsgBolusStart() { public MsgBolusStart() {
SetCommand(0x0102); SetCommand(0x0102);
} }
@ -29,13 +31,13 @@ public class MsgBolusStart extends MessageBase {
@Override @Override
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
int result = intFromBuff(bytes, 0, 1); errorCode = intFromBuff(bytes, 0, 1);
if (result != 2) { if (errorCode != 2) {
failed = true; failed = true;
log.debug("Messsage response: " + result + " FAILED!!"); log.debug("Messsage response: " + errorCode + " FAILED!!");
} else { } else {
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
log.debug("Messsage response: " + result); log.debug("Messsage response: " + errorCode + " OK");
} }
} }
} }

View file

@ -11,6 +11,8 @@ import info.nightscout.utils.HardLimits;
public class MsgBolusStartWithSpeed extends MessageBase { public class MsgBolusStartWithSpeed extends MessageBase {
private static Logger log = LoggerFactory.getLogger(MsgBolusStartWithSpeed.class); private static Logger log = LoggerFactory.getLogger(MsgBolusStartWithSpeed.class);
public static int errorCode;
public MsgBolusStartWithSpeed() { public MsgBolusStartWithSpeed() {
SetCommand(0x0104); SetCommand(0x0104);
} }
@ -30,13 +32,13 @@ public class MsgBolusStartWithSpeed extends MessageBase {
@Override @Override
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
int result = intFromBuff(bytes, 0, 1); errorCode = intFromBuff(bytes, 0, 1);
if (result != 2) { if (errorCode != 2) {
failed = true; failed = true;
log.debug("Messsage response: " + result + " FAILED!!"); log.debug("Messsage response: " + errorCode + " FAILED!!");
} else { } else {
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
log.debug("Messsage response: " + result); log.debug("Messsage response: " + errorCode + " OK");
} }
} }
} }

View file

@ -34,10 +34,10 @@ public class MsgBolusStop extends MessageBase {
stopped = true; stopped = true;
if (!forced) { if (!forced) {
t.insulin = amount; t.insulin = amount;
bolusingEvent.status = MainApp.sResources.getString(R.string.overview_bolusprogress_delivered); bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_delivered);
bolusingEvent.percent = 100; bolusingEvent.percent = 100;
} else { } else {
bolusingEvent.status = MainApp.sResources.getString(R.string.overview_bolusprogress_stoped); bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_stoped);
} }
MainApp.bus().post(bolusingEvent); MainApp.bus().post(bolusingEvent);
} }

View file

@ -25,19 +25,19 @@ public class MsgError extends MessageBase {
case 1: case 1:
case 2: case 2:
case 3: // Pump error case 3: // Pump error
errorString = MainApp.sResources.getString(R.string.pumperror) + " " + errorCode; errorString = MainApp.gs(R.string.pumperror) + " " + errorCode;
break; break;
case 4: // Shutdown case 4: // Shutdown
errorString = MainApp.sResources.getString(R.string.pumpshutdown); errorString = MainApp.gs(R.string.pumpshutdown);
break; break;
case 5: // Occlusion case 5: // Occlusion
errorString = MainApp.sResources.getString(R.string.occlusion); errorString = MainApp.gs(R.string.occlusion);
break; break;
case 7: // Low Battery case 7: // Low Battery
errorString = MainApp.sResources.getString(R.string.lowbattery); errorString = MainApp.gs(R.string.lowbattery);
break; break;
case 8: // Battery 0% case 8: // Battery 0%
errorString = MainApp.sResources.getString(R.string.batterydischarged); errorString = MainApp.gs(R.string.batterydischarged);
break; break;
} }

View file

@ -41,7 +41,7 @@ public class MsgInitConnStatusBolus extends MessageBase {
} }
if (!pump.isExtendedBolusEnabled) { if (!pump.isExtendedBolusEnabled) {
Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.sResources.getString(R.string.danar_enableextendedbolus), Notification.URGENT); Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.gs(R.string.danar_enableextendedbolus), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)); MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));

View file

@ -27,7 +27,7 @@ public class MsgInitConnStatusTime extends MessageBase {
@Override @Override
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
if (bytes.length - 10 > 7) { if (bytes.length - 10 > 7) {
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.sResources.getString(R.string.pumpdrivercorrected), Notification.NORMAL); Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model"); MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model");
log.debug("Wrong model selected. Switching to Korean DanaR"); log.debug("Wrong model selected. Switching to Korean DanaR");

View file

@ -33,12 +33,12 @@ public class MsgSetBasalProfile extends MessageBase {
if (result != 1) { if (result != 1) {
failed = true; failed = true;
log.debug("Set basal profile result: " + result + " FAILED!!!"); log.debug("Set basal profile result: " + result + " FAILED!!!");
Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.sResources.getString(R.string.profile_set_failed), Notification.URGENT); Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.gs(R.string.profile_set_failed), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail)); MainApp.bus().post(new EventNewNotification(reportFail));
} else { } else {
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
log.debug("Set basal profile result: " + result); log.debug("Set basal profile result: " + result);
Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.sResources.getString(R.string.profile_set_ok), Notification.INFO, 60); Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(reportOK)); MainApp.bus().post(new EventNewNotification(reportOK));
} }
} }

View file

@ -32,12 +32,12 @@ public class MsgSetSingleBasalProfile extends MessageBase {
if (result != 1) { if (result != 1) {
failed = true; failed = true;
log.debug("Set basal profile result: " + result + " FAILED!!!"); log.debug("Set basal profile result: " + result + " FAILED!!!");
Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.sResources.getString(R.string.profile_set_failed), Notification.URGENT); Notification reportFail = new Notification(Notification.PROFILE_SET_FAILED, MainApp.gs(R.string.profile_set_failed), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail)); MainApp.bus().post(new EventNewNotification(reportFail));
} else { } else {
if (Config.logDanaMessageDetail) if (Config.logDanaMessageDetail)
log.debug("Set basal profile result: " + result); log.debug("Set basal profile result: " + result);
Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.sResources.getString(R.string.profile_set_ok), Notification.INFO, 60); Notification reportOK = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(reportOK)); MainApp.bus().post(new EventNewNotification(reportOK));
} }
} }

View file

@ -48,14 +48,14 @@ public class MsgSettingMeal extends MessageBase {
} }
if (pump.basalStep != 0.01d) { if (pump.basalStep != 0.01d) {
Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.sResources.getString(R.string.danar_setbasalstep001), Notification.URGENT); Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.gs(R.string.danar_setbasalstep001), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP)); MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP));
} }
if (pump.isConfigUD) { if (pump.isConfigUD) {
Notification notification = new Notification(Notification.UD_MODE_ENABLED, MainApp.sResources.getString(R.string.danar_switchtouhmode), Notification.URGENT); Notification notification = new Notification(Notification.UD_MODE_ENABLED, MainApp.gs(R.string.danar_switchtouhmode), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.UD_MODE_ENABLED)); MainApp.bus().post(new EventDismissNotification(Notification.UD_MODE_ENABLED));

View file

@ -134,7 +134,7 @@ public abstract class AbstractDanaRExecutionService extends Service {
} }
protected void getBTSocketForSelectedPump() { protected void getBTSocketForSelectedPump() {
mDevName = SP.getString(MainApp.sResources.getString(R.string.key_danar_bt_name), ""); mDevName = SP.getString(MainApp.gs(R.string.key_danar_bt_name), "");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) { if (bluetoothAdapter != null) {
@ -152,10 +152,10 @@ public abstract class AbstractDanaRExecutionService extends Service {
} }
} }
} else { } else {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.nobtadapter)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.nobtadapter));
} }
if (mBTDevice == null) { if (mBTDevice == null) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.devicenotfound)); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.devicenotfound));
} }
} }

View file

@ -97,7 +97,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public void connect() { public void connect() {
if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) { if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.wrongpumppassword), R.raw.error);
return; return;
} }
@ -138,7 +138,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public void getPumpStatus() { public void getPumpStatus() {
try { try {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
MsgStatus statusMsg = new MsgStatus(); MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
@ -154,15 +154,15 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg); mSerialIOThread.sendMessage(statusBasicMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingtempbasalstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg); mSerialIOThread.sendMessage(tempStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingextendedbolusstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg); mSerialIOThread.sendMessage(exStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (mDanaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !MainApp.getSpecificPlugin(DanaRPlugin.class).isInitialized()) { if (mDanaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !MainApp.getSpecificPlugin(DanaRPlugin.class).isInitialized()) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpsettings))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo()); mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile()); mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingMeal()); mSerialIOThread.sendMessage(new MsgSettingMeal());
@ -173,7 +173,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
mSerialIOThread.sendMessage(new MsgSettingActiveProfile()); mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios()); mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll()); mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumptime))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
@ -192,9 +192,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits);
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail)); MainApp.bus().post(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U"); NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U");
} }
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -204,11 +204,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public boolean tempBasal(int percent, int durationInHours) { public boolean tempBasal(int percent, int durationInHours) {
if (!isConnected()) return false; if (!isConnected()) return false;
if (mDanaRPump.isTempBasalInProgress) { if (mDanaRPump.isTempBasalInProgress) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500); SystemClock.sleep(500);
} }
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -217,7 +217,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public boolean tempBasalStop() { public boolean tempBasalStop() {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -226,7 +226,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public boolean extendedBolus(double insulin, int durationInHalfHours) { public boolean extendedBolus(double insulin, int durationInHalfHours) {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -235,7 +235,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public boolean extendedBolusStop() { public boolean extendedBolusStop() {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -264,82 +264,84 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
mSerialIOThread.sendMessage(new MsgSetCarbsEntry(carbtime, carbs)); mSerialIOThread.sendMessage(new MsgSetCarbsEntry(carbtime, carbs));
} }
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables if (amount > 0) {
long bolusStart = System.currentTimeMillis(); MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
long bolusStart = System.currentTimeMillis();
if (!stop.stopped) { if (!stop.stopped) {
mSerialIOThread.sendMessage(start); mSerialIOThread.sendMessage(start);
} else { } else {
t.insulin = 0d; t.insulin = 0d;
return false; return false;
}
while (!stop.stopped && !start.failed) {
SystemClock.sleep(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm
stop.stopped = true;
stop.forced = true;
log.debug("Communication stopped");
} }
} while (!stop.stopped && !start.failed) {
SystemClock.sleep(300); SystemClock.sleep(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); stop.stopped = true;
bolusingEvent.t = t; stop.forced = true;
bolusingEvent.percent = 99; log.debug("Communication stopped");
mBolusingTreatment = null;
int speed = 12;
switch (preferencesSpeed) {
case 0:
speed = 12;
break;
case 1:
speed = 30;
break;
case 2:
speed = 60;
break;
}
// try to find real amount if bolusing was interrupted or comm failed
if (t.insulin != amount) {
disconnect("bolusingInterrupted");
long bolusDurationInMSec = (long) (amount * speed * 1000);
long expectedEnd = bolusStart + bolusDurationInMSec + 3000;
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
bolusingEvent.status = String.format(MainApp.sResources.getString(R.string.waitingforestimatedbolusend), waitTime / 1000);
MainApp.bus().post(bolusingEvent);
SystemClock.sleep(1000);
}
final Object o = new Object();
synchronized(o) {
ConfigBuilderPlugin.getCommandQueue().independentConnect("bolusingInterrupted", new Callback() {
@Override
public void run() {
if (mDanaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old
t.insulin = mDanaRPump.lastBolusAmount;
log.debug("Used bolus amount from history: " + mDanaRPump.lastBolusAmount);
} else {
log.debug("Bolus amount in history too old: " + mDanaRPump.lastBolusTime.toLocaleString());
}
synchronized (o) {
o.notify();
}
}
});
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
} }
} }
} else { SystemClock.sleep(300);
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusOK", null);
EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.t = t;
bolusingEvent.percent = 99;
mBolusingTreatment = null;
int speed = 12;
switch (preferencesSpeed) {
case 0:
speed = 12;
break;
case 1:
speed = 30;
break;
case 2:
speed = 60;
break;
}
// try to find real amount if bolusing was interrupted or comm failed
if (t.insulin != amount) {
disconnect("bolusingInterrupted");
long bolusDurationInMSec = (long) (amount * speed * 1000);
long expectedEnd = bolusStart + bolusDurationInMSec + 3000;
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000);
MainApp.bus().post(bolusingEvent);
SystemClock.sleep(1000);
}
final Object o = new Object();
synchronized (o) {
ConfigBuilderPlugin.getCommandQueue().independentConnect("bolusingInterrupted", new Callback() {
@Override
public void run() {
if (mDanaRPump.lastBolusTime.getTime() > System.currentTimeMillis() - 60 * 1000L) { // last bolus max 1 min old
t.insulin = mDanaRPump.lastBolusAmount;
log.debug("Used bolus amount from history: " + mDanaRPump.lastBolusAmount);
} else {
log.debug("Bolus amount in history too old: " + mDanaRPump.lastBolusTime.toLocaleString());
}
synchronized (o) {
o.notify();
}
}
});
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusOK", null);
}
} }
return true; return !start.failed;
} }
public boolean carbsEntry(int amount) { public boolean carbsEntry(int amount) {
@ -361,7 +363,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService{
public boolean updateBasalsInPump(final Profile profile) { public boolean updateBasalsInPump(final Profile profile) {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
double[] basal = DanaRPump.buildDanaRProfileRecord(profile); double[] basal = DanaRPump.buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet); mSerialIOThread.sendMessage(msgSet);

View file

@ -18,14 +18,15 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.plugins.PumpDanaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.PumpDanaR.AbstractDanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.MsgBolusStart;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService; import info.nightscout.androidaps.plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.Round; import info.nightscout.utils.Round;
import info.nightscout.utils.SP; import info.nightscout.utils.SP;
@ -72,7 +73,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
pumpDescription.isRefillingCapable = true; pumpDescription.isRefillingCapable = true;
pumpDescription.storesCarbInfo = true; pumpDescription.storesCarbInfo = false;
pumpDescription.supportsTDDs = true; pumpDescription.supportsTDDs = true;
pumpDescription.needsManualTDDLoad = true; pumpDescription.needsManualTDDLoad = true;
@ -130,7 +131,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
// Plugin base interface // Plugin base interface
@Override @Override
public String getName() { public String getName() {
return MainApp.instance().getString(R.string.danarkoreanpump); return MainApp.gs(R.string.danarkoreanpump);
} }
@Override @Override
@ -159,10 +160,13 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0)
connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t); connectionOK = sExecutionService.bolus(detailedBolusInfo.insulin, (int) detailedBolusInfo.carbs, detailedBolusInfo.carbTime, t);
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = connectionOK; result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep;
result.bolusDelivered = t.insulin; result.bolusDelivered = t.insulin;
result.carbsDelivered = detailedBolusInfo.carbs; result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); if (!result.success)
result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, MsgBolusStart.errorCode);
else
result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
detailedBolusInfo.insulin = t.insulin; detailedBolusInfo.insulin = t.insulin;
@ -174,7 +178,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
result.success = false; result.success = false;
result.bolusDelivered = 0d; result.bolusDelivered = 0d;
result.carbsDelivered = 0d; result.carbsDelivered = 0d;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput); result.comment = MainApp.gs(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input"); log.error("deliverTreatment: Invalid input");
return result; return result;
} }
@ -343,7 +347,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = true; result.success = true;
result.enacted = false; result.enacted = false;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = true; result.isTempCancel = true;
return result; return result;
} }
@ -359,13 +363,13 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
if (!pump.isTempBasalInProgress) { if (!pump.isTempBasalInProgress) {
result.success = true; result.success = true;
result.isTempCancel = true; result.isTempCancel = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("cancelRealTempBasal: OK"); log.debug("cancelRealTempBasal: OK");
return result; return result;
} else { } else {
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
result.isTempCancel = true; result.isTempCancel = true;
log.error("cancelRealTempBasal: Failed to cancel temp basal"); log.error("cancelRealTempBasal: Failed to cancel temp basal");
return result; return result;

View file

@ -39,7 +39,7 @@ public class MsgInitConnStatusBasic_k extends MessageBase {
} }
if (pump.isEasyModeEnabled) { if (pump.isEasyModeEnabled) {
Notification notification = new Notification(Notification.EASYMODE_ENABLED, MainApp.sResources.getString(R.string.danar_disableeasymode), Notification.URGENT); Notification notification = new Notification(Notification.EASYMODE_ENABLED, MainApp.gs(R.string.danar_disableeasymode), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.EASYMODE_ENABLED)); MainApp.bus().post(new EventDismissNotification(Notification.EASYMODE_ENABLED));

View file

@ -44,7 +44,7 @@ public class MsgInitConnStatusBolus_k extends MessageBase {
} }
if (!pump.isExtendedBolusEnabled) { if (!pump.isExtendedBolusEnabled) {
Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.sResources.getString(R.string.danar_enableextendedbolus), Notification.URGENT); Notification notification = new Notification(Notification.EXTENDED_BOLUS_DISABLED, MainApp.gs(R.string.danar_enableextendedbolus), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED)); MainApp.bus().post(new EventDismissNotification(Notification.EXTENDED_BOLUS_DISABLED));

View file

@ -29,7 +29,7 @@ public class MsgInitConnStatusTime_k extends MessageBase {
public void handleMessage(byte[] bytes) { public void handleMessage(byte[] bytes) {
if (bytes.length - 10 < 10) { if (bytes.length - 10 < 10) {
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.sResources.getString(R.string.pumpdrivercorrected), Notification.NORMAL); Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model"); DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model");
log.debug("Wrong model selected. Switching to export DanaR"); log.debug("Wrong model selected. Switching to export DanaR");

View file

@ -105,7 +105,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public void connect() { public void connect() {
if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) { if (mDanaRPump.password != -1 && mDanaRPump.password != SP.getInt(R.string.key_danar_password, -1)) {
ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.sResources.getString(R.string.wrongpumppassword), R.raw.error); ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.wrongpumppassword), R.raw.error);
return; return;
} }
@ -146,7 +146,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public void getPumpStatus() { public void getPumpStatus() {
try { try {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
//MsgStatus_k statusMsg = new MsgStatus_k(); //MsgStatus_k statusMsg = new MsgStatus_k();
MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(); MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
@ -162,15 +162,15 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
//mSerialIOThread.sendMessage(statusMsg); //mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg); mSerialIOThread.sendMessage(statusBasicMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingtempbasalstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg); mSerialIOThread.sendMessage(tempStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingextendedbolusstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg); mSerialIOThread.sendMessage(exStatusMsg);
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingbolusstatus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
if (mDanaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isInitialized()) { if (mDanaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isInitialized()) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumpsettings))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo()); mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingMeal()); mSerialIOThread.sendMessage(new MsgSettingMeal());
mSerialIOThread.sendMessage(new MsgSettingBasal_k()); mSerialIOThread.sendMessage(new MsgSettingBasal_k());
@ -178,7 +178,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(new MsgSettingMaxValues()); mSerialIOThread.sendMessage(new MsgSettingMaxValues());
mSerialIOThread.sendMessage(new MsgSettingGlucose()); mSerialIOThread.sendMessage(new MsgSettingGlucose());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios()); mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.gettingpumptime))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime()); mSerialIOThread.sendMessage(new MsgSettingPumpTime());
long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L; long timeDiff = (mDanaRPump.pumpTime.getTime() - System.currentTimeMillis()) / 1000L;
log.debug("Pump time difference: " + timeDiff + " seconds"); log.debug("Pump time difference: " + timeDiff + " seconds");
@ -197,9 +197,9 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
NSUpload.uploadDeviceStatus(); NSUpload.uploadDeviceStatus();
if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { if (mDanaRPump.dailyTotalUnits > mDanaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits); log.debug("Approaching daily limit: " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits);
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.sResources.getString(R.string.approachingdailylimit), Notification.URGENT); Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, MainApp.gs(R.string.approachingdailylimit), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(reportFail)); MainApp.bus().post(new EventNewNotification(reportFail));
NSUpload.uploadError(MainApp.sResources.getString(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U"); NSUpload.uploadError(MainApp.gs(R.string.approachingdailylimit) + ": " + mDanaRPump.dailyTotalUnits + "/" + mDanaRPump.maxDailyTotalUnits + "U");
} }
} catch (Exception e) { } catch (Exception e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
@ -209,11 +209,11 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public boolean tempBasal(int percent, int durationInHours) { public boolean tempBasal(int percent, int durationInHours) {
if (!isConnected()) return false; if (!isConnected()) return false;
if (mDanaRPump.isTempBasalInProgress) { if (mDanaRPump.isTempBasalInProgress) {
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500); SystemClock.sleep(500);
} }
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -222,7 +222,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public boolean tempBasalStop() { public boolean tempBasalStop() {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingtempbasal))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal()); mSerialIOThread.sendMessage(new MsgStatusTempBasal());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -231,7 +231,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public boolean extendedBolus(double insulin, int durationInHalfHours) { public boolean extendedBolus(double insulin, int durationInHalfHours) {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.settingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -240,7 +240,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public boolean extendedBolusStop() { public boolean extendedBolusStop() {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.stoppingextendedbolus))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
@ -264,29 +264,31 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(new MsgSetCarbsEntry(carbtime, carbs)); mSerialIOThread.sendMessage(new MsgSetCarbsEntry(carbtime, carbs));
} }
MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables if (amount > 0) {
long bolusStart = System.currentTimeMillis(); MsgBolusProgress progress = new MsgBolusProgress(amount, t); // initialize static variables
long bolusStart = System.currentTimeMillis();
if (!stop.stopped) { if (!stop.stopped) {
mSerialIOThread.sendMessage(start); mSerialIOThread.sendMessage(start);
} else { } else {
t.insulin = 0d; t.insulin = 0d;
return false; return false;
}
while (!stop.stopped && !start.failed) {
SystemClock.sleep(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm
stop.stopped = true;
stop.forced = true;
log.debug("Communication stopped");
} }
while (!stop.stopped && !start.failed) {
SystemClock.sleep(100);
if ((System.currentTimeMillis() - progress.lastReceive) > 15 * 1000L) { // if i didn't receive status for more than 15 sec expecting broken comm
stop.stopped = true;
stop.forced = true;
log.debug("Communication stopped");
}
}
SystemClock.sleep(300);
mBolusingTreatment = null;
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusOK", null);
} }
SystemClock.sleep(300);
mBolusingTreatment = null; return !start.failed;
ConfigBuilderPlugin.getCommandQueue().readStatus("bolusOK", null);
return true;
} }
public boolean carbsEntry(int amount) { public boolean carbsEntry(int amount) {
@ -308,7 +310,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public boolean updateBasalsInPump(final Profile profile) { public boolean updateBasalsInPump(final Profile profile) {
if (!isConnected()) return false; if (!isConnected()) return false;
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.updatingbasalrates))); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
double[] basal = DanaRPump.buildDanaRProfileRecord(profile); double[] basal = DanaRPump.buildDanaRProfileRecord(profile);
MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal); MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal);
mSerialIOThread.sendMessage(msgSet); mSerialIOThread.sendMessage(msgSet);

View file

@ -26,6 +26,7 @@ import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Start;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
@ -178,8 +179,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
final Object o = new Object(); final Object o = new Object();
danaRSService.connect(from, mDeviceAddress, o); danaRSService.connect(from, mDeviceAddress, o);
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
} }
} }
@ -205,8 +204,11 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
@Override @Override
public void getPumpStatus() { public void getPumpStatus() {
if (danaRSService != null) if (danaRSService != null) {
danaRSService.getPumpStatus(); danaRSService.getPumpStatus();
pumpDescription.basalStep = pump.basalStep;
pumpDescription.bolusStep = pump.bolusStep;
}
} }
// DanaR interface // DanaR interface
@ -295,22 +297,22 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
if (!isInitialized()) { if (!isInitialized()) {
log.error("setNewBasalProfile not initialized"); log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.sResources.getString(R.string.pumpNotInitializedProfileNotSet); result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
return result; return result;
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
} }
if (!danaRSService.updateBasalsInPump(profile)) { if (!danaRSService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.sResources.getString(R.string.failedupdatebasalprofile), Notification.URGENT); Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.sResources.getString(R.string.failedupdatebasalprofile); result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
return result; return result;
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.sResources.getString(R.string.profile_set_ok), Notification.INFO, 60); Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
result.success = true; result.success = true;
result.enacted = true; result.enacted = true;
@ -368,7 +370,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
// RS stores end time for bolus, we need to adjust time // RS stores end time for bolus, we need to adjust time
// default delivery speed is 12 sec/U // default delivery speed is 12 sec/U
detailedBolusInfo.date = DateUtil.now() + (long)(speed * detailedBolusInfo.insulin * 1000); detailedBolusInfo.date = DateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000);
// clean carbs to prevent counting them as twice because they will picked up as another record // clean carbs to prevent counting them as twice because they will picked up as another record
// I don't think it's necessary to copy DetailedBolusInfo right now for carbs records // I don't think it's necessary to copy DetailedBolusInfo right now for carbs records
double carbs = detailedBolusInfo.carbs; double carbs = detailedBolusInfo.carbs;
@ -384,10 +386,13 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (detailedBolusInfo.insulin > 0 || carbs > 0) if (detailedBolusInfo.insulin > 0 || carbs > 0)
connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + carbTime * 60 * 1000, t); connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + carbTime * 60 * 1000, t);
PumpEnactResult result = new PumpEnactResult(); PumpEnactResult result = new PumpEnactResult();
result.success = connectionOK; result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep;
result.bolusDelivered = t.insulin; result.bolusDelivered = t.insulin;
result.carbsDelivered = detailedBolusInfo.carbs; result.carbsDelivered = detailedBolusInfo.carbs;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); if (!result.success)
result.comment = String.format(MainApp.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, DanaRS_Packet_Bolus_Set_Step_Bolus_Start.errorCode);
else
result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); log.debug("deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
return result; return result;
@ -396,7 +401,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
result.success = false; result.success = false;
result.bolusDelivered = 0d; result.bolusDelivered = 0d;
result.carbsDelivered = 0d; result.carbsDelivered = 0d;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput); result.comment = MainApp.gs(R.string.danar_invalidinput);
log.error("deliverTreatment: Invalid input"); log.error("deliverTreatment: Invalid input");
return result; return result;
} }
@ -500,7 +505,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
result.isTempCancel = false; result.isTempCancel = false;
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_invalidinput); result.comment = MainApp.gs(R.string.danar_invalidinput);
log.error("setTempBasalPercent: Invalid input"); log.error("setTempBasalPercent: Invalid input");
return result; return result;
} }
@ -512,7 +517,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
result.enacted = false; result.enacted = false;
result.success = true; result.success = true;
result.isTempCancel = false; result.isTempCancel = false;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
result.isPercent = true; result.isPercent = true;
@ -530,7 +535,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) { if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
@ -541,7 +546,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.tempbasaldeliveryerror); result.comment = MainApp.gs(R.string.tempbasaldeliveryerror);
log.error("setTempBasalPercent: Failed to set temp basal"); log.error("setTempBasalPercent: Failed to set temp basal");
return result; return result;
} }
@ -552,7 +557,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) { if (connectionOK && pump.isTempBasalInProgress && pump.tempBasalPercent == percent) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.tempBasalRemainingMin; result.duration = pump.tempBasalRemainingMin;
result.percent = pump.tempBasalPercent; result.percent = pump.tempBasalPercent;
@ -563,7 +568,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
log.error("setHighTempBasalPercent: Failed to set temp basal"); log.error("setHighTempBasalPercent: Failed to set temp basal");
return result; return result;
} }
@ -579,7 +584,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = false; result.enacted = false;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.duration = pump.extendedBolusRemainingMinutes; result.duration = pump.extendedBolusRemainingMinutes;
result.absolute = pump.extendedBolusAbsoluteRate; result.absolute = pump.extendedBolusAbsoluteRate;
result.isPercent = false; result.isPercent = false;
@ -592,7 +597,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAbsoluteRate - insulin) < getPumpDescription().extendedBolusStep) { if (connectionOK && pump.isExtendedInProgress && Math.abs(pump.extendedBolusAbsoluteRate - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = true; result.enacted = true;
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.isTempCancel = false; result.isTempCancel = false;
result.duration = pump.extendedBolusRemainingMinutes; result.duration = pump.extendedBolusRemainingMinutes;
result.absolute = pump.extendedBolusAbsoluteRate; result.absolute = pump.extendedBolusAbsoluteRate;
@ -604,7 +609,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
result.enacted = false; result.enacted = false;
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
log.error("setExtendedBolus: Failed to extended bolus"); log.error("setExtendedBolus: Failed to extended bolus");
return result; return result;
} }
@ -621,13 +626,13 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
if (!pump.isTempBasalInProgress) { if (!pump.isTempBasalInProgress) {
result.success = true; result.success = true;
result.isTempCancel = true; result.isTempCancel = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("cancelRealTempBasal: OK"); log.debug("cancelRealTempBasal: OK");
return result; return result;
} else { } else {
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
result.isTempCancel = true; result.isTempCancel = true;
log.error("cancelRealTempBasal: Failed to cancel temp basal"); log.error("cancelRealTempBasal: Failed to cancel temp basal");
return result; return result;
@ -645,13 +650,13 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
} }
if (!pump.isExtendedInProgress) { if (!pump.isExtendedInProgress) {
result.success = true; result.success = true;
result.comment = MainApp.instance().getString(R.string.virtualpump_resultok); result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (Config.logPumpActions) if (Config.logPumpActions)
log.debug("cancelExtendedBolus: OK"); log.debug("cancelExtendedBolus: OK");
return result; return result;
} else { } else {
result.success = false; result.success = false;
result.comment = MainApp.instance().getString(R.string.danar_valuenotsetproperly); result.comment = MainApp.gs(R.string.danar_valuenotsetproperly);
log.error("cancelExtendedBolus: Failed to cancel extended bolus"); log.error("cancelExtendedBolus: Failed to cancel extended bolus");
return result; return result;
} }

View file

@ -51,14 +51,14 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic
public View onCreateView(LayoutInflater inflater, ViewGroup container, public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.danars_pairingprogressdialog, container, false); View view = inflater.inflate(R.layout.danars_pairingprogressdialog, container, false);
getDialog().setTitle(MainApp.sResources.getString(R.string.pairing)); getDialog().setTitle(MainApp.gs(R.string.pairing));
statusView = (TextView) view.findViewById(R.id.danars_paringprogress_status); statusView = (TextView) view.findViewById(R.id.danars_paringprogress_status);
progressBar = (ProgressBar) view.findViewById(R.id.danars_paringprogress_progressbar); progressBar = (ProgressBar) view.findViewById(R.id.danars_paringprogress_progressbar);
button = (Button) view.findViewById(R.id.ok); button = (Button) view.findViewById(R.id.ok);
progressBar.setMax(100); progressBar.setMax(100);
progressBar.setProgress(0); progressBar.setProgress(0);
statusView.setText(MainApp.sResources.getString(R.string.waitingforpairing)); statusView.setText(MainApp.gs(R.string.waitingforpairing));
button.setVisibility(View.GONE); button.setVisibility(View.GONE);
button.setOnClickListener(this); button.setOnClickListener(this);
setCancelable(false); setCancelable(false);

View file

@ -200,7 +200,7 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
if (datetime.getTime() > lastEventTimeLoaded) if (datetime.getTime() > lastEventTimeLoaded)
lastEventTimeLoaded = datetime.getTime(); lastEventTimeLoaded = datetime.getTime();
MainApp.bus().post(new EventPumpStatusChanged(MainApp.sResources.getString(R.string.processinghistory) + ": " + status)); MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
} }
@Override @Override

View file

@ -53,7 +53,7 @@ public class DanaRS_Packet_Basal_Get_Basal_Rate extends DanaRS_Packet {
} }
if (pump.basalStep != 0.01d) { if (pump.basalStep != 0.01d) {
Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.sResources.getString(R.string.danar_setbasalstep001), Notification.URGENT); Notification notification = new Notification(Notification.WRONGBASALSTEP, MainApp.gs(R.string.danar_setbasalstep001), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification)); MainApp.bus().post(new EventNewNotification(notification));
} else { } else {
MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP)); MainApp.bus().post(new EventDismissNotification(Notification.WRONGBASALSTEP));

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