daggerize

This commit is contained in:
Milos Kozak 2019-12-30 00:53:44 +01:00
parent 1ac0094f48
commit fef74726b2
232 changed files with 4133 additions and 3845 deletions

View file

@ -10,6 +10,10 @@
<option name="NAME_COUNT_TO_USE_STAR_IMPORT_FOR_MEMBERS" value="6" />
<option name="BLANK_LINES_AROUND_BLOCK_WHEN_BRANCHES" value="1" />
</JetCodeStyleSettings>
<codeStyleSettings language="JAVA">
<option name="METHOD_ANNOTATION_WRAP" value="0" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
</codeStyleSettings>
<codeStyleSettings language="XML">
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
@ -129,6 +133,8 @@
<option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
<option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="1" />
<option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1" />
<option name="METHOD_ANNOTATION_WRAP" value="5" />
<option name="FIELD_ANNOTATION_WRAP" value="0" />
<indentOptions>
<option name="CONTINUATION_INDENT_SIZE" value="4" />
</indentOptions>

View file

@ -126,7 +126,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
setupTabs();
setupViews();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventRebuildTabs.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {
@ -140,7 +140,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
setWakeLock();
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventPreferenceChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::processPreferenceChange, FabricPrivacy::logException)
@ -322,7 +322,7 @@ public class MainActivity extends NoSplashAppCompatActivity {
return true;
case R.id.nav_exit:
aapsLogger.debug(LTag.CORE, "Exiting");
RxBus.INSTANCE.send(new EventAppExit());
RxBus.Companion.getINSTANCE().send(new EventAppExit());
finish();
System.runFinalization();
System.exit(0);

View file

@ -59,6 +59,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin;
import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
@ -126,17 +127,30 @@ public class MainApp extends DaggerApplication {
@Inject
AAPSLogger aapsLogger;
@Inject ActionsPlugin actionsPlugin;
@Inject AutomationPlugin automationPlugin;
@Inject CareportalPlugin careportalPlugin;
@Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject DanaRPlugin danaRPlugin;
@Inject DanaRSPlugin danaRSPlugin;
@Inject DanaRv2Plugin danaRv2Plugin;
@Inject DanaRKoreanPlugin danaRKoreanPlugin;
@Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin;
@Inject InsulinOrefRapidActingPlugin insulinOrefRapidActingPlugin;
@Inject InsulinOrefUltraRapidActingPlugin insulinOrefUltraRapidActingPlugin;
@Inject LocalProfilePlugin localProfilePlugin;
@Inject ObjectivesPlugin objectivesPlugin;
@Inject SafetyPlugin safetyPlugin;
@Inject SmsCommunicatorPlugin smsCommunicatorPlugin;
@Inject OpenAPSMAPlugin openAPSMAPlugin;
@Inject OpenAPSAMAPlugin openAPSAMAPlugin;
@Inject OpenAPSSMBPlugin openAPSSMBPlugin;
@Inject OverviewPlugin overviewPlugin;
@Inject StatusLinePlugin statusLinePlugin;
@Inject TidepoolPlugin tidepoolPlugin;
@Inject TreatmentsPlugin treatmentsPlugin;
@Inject VirtualPumpPlugin virtualPumpPlugin;
@Inject VersionCheckerPlugin versionCheckerPlugin;
@Override
public void onCreate() {
@ -190,9 +204,9 @@ public class MainApp extends DaggerApplication {
if (pluginsList == null) {
pluginsList = new ArrayList<>();
// Register all tabs in app here
pluginsList.add(OverviewPlugin.INSTANCE);
pluginsList.add(overviewPlugin);
pluginsList.add(IobCobCalculatorPlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(ActionsPlugin.INSTANCE);
if (!Config.NSCLIENT) pluginsList.add(actionsPlugin);
pluginsList.add(insulinOrefRapidActingPlugin);
pluginsList.add(insulinOrefUltraRapidActingPlugin);
pluginsList.add(insulinOrefFreePeakPlugin);
@ -200,28 +214,28 @@ public class MainApp extends DaggerApplication {
pluginsList.add(SensitivityAAPSPlugin.getPlugin());
pluginsList.add(SensitivityWeightedAveragePlugin.getPlugin());
pluginsList.add(SensitivityOref1Plugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(danaRPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRKoreanPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRv2Plugin);
if (Config.PUMPDRIVERS) pluginsList.add(danaRSPlugin);
if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(MedtronicPumpPlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin());
pluginsList.add(CareportalPlugin.getPlugin());
pluginsList.add(virtualPumpPlugin);
pluginsList.add(careportalPlugin);
if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
if (Config.APS) pluginsList.add(openAPSMAPlugin);
if (Config.APS) pluginsList.add(openAPSAMAPlugin);
if (Config.APS) pluginsList.add(openAPSSMBPlugin);
pluginsList.add(NSProfilePlugin.getPlugin());
if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.INSTANCE);
if (!Config.NSCLIENT) pluginsList.add(localProfilePlugin);
pluginsList.add(treatmentsPlugin);
if (!Config.NSCLIENT) pluginsList.add(safetyPlugin);
if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE);
if (!Config.NSCLIENT) pluginsList.add(versionCheckerPlugin);
if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin());
if (Config.APS) pluginsList.add(SignatureVerifierPlugin.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesPlugin.INSTANCE);
if (Config.APS) pluginsList.add(objectivesPlugin);
pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin());
pluginsList.add(SourceMM640gPlugin.getPlugin());
@ -238,9 +252,9 @@ public class MainApp extends DaggerApplication {
pluginsList.add(statusLinePlugin);
pluginsList.add(PersistentNotificationPlugin.getPlugin());
pluginsList.add(NSClientPlugin.getPlugin());
// if (engineeringMode) pluginsList.add(TidepoolPlugin.INSTANCE);
// if (engineeringMode) pluginsList.add(tidepoolPlugin);
pluginsList.add(MaintenancePlugin.initPlugin(this));
pluginsList.add(AutomationPlugin.INSTANCE);
pluginsList.add(automationPlugin);
pluginsList.add(configBuilderPlugin);
@ -323,22 +337,27 @@ public class MainApp extends DaggerApplication {
}
@Deprecated
public static String gs(@StringRes int id) {
return sResources.getString(id);
}
@Deprecated
public static String gs(@StringRes int id, Object... args) {
return sResources.getString(id, args);
}
@Deprecated
public static String gq(@PluralsRes int id, int quantity, Object... args) {
return sResources.getQuantityString(id, quantity, args);
}
@Deprecated
public static int gc(@ColorRes int id) {
return ContextCompat.getColor(instance(), id);
}
@Deprecated
public static MainApp instance() {
return sInstance;
}

View file

@ -4,9 +4,11 @@ import android.os.Bundle
import info.nightscout.androidaps.R
import info.nightscout.androidaps.dialogs.ErrorDialog
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
class ErrorHelperActivity : NoSplashAppCompatActivity() {
@Inject lateinit var sp : SP
@Override
override fun onCreate(savedInstanceState: Bundle?) {
@ -18,7 +20,7 @@ class ErrorHelperActivity : NoSplashAppCompatActivity() {
errorDialog.title = intent.getStringExtra("title")
errorDialog.show(supportFragmentManager, "Error")
if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) {
if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) {
NSUpload.uploadError(intent.getStringExtra("status"))
}
}

View file

@ -175,7 +175,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
@Override
public void onResume() {
super.onResume();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventAutosensCalculationFinished.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {
@ -187,7 +187,7 @@ public class HistoryBrowseActivity extends NoSplashAppCompatActivity {
}
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventIobCalculationProgress.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {

View file

@ -47,23 +47,23 @@ import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin;
public class MyPreferenceFragment extends PreferenceFragment implements HasAndroidInjector {
private Integer id;
@Inject
DispatchingAndroidInjector<Object> androidInjector;
@Inject DispatchingAndroidInjector<Object> androidInjector;
@Inject
OpenAPSAMAPlugin openAPSAMAPlugin;
@Inject
OpenAPSMAPlugin openAPSMAPlugin;
@Inject
OpenAPSSMBPlugin openAPSSMBPlugin;
@Inject
InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin;
@Inject
SafetyPlugin safetyPlugin;
@Inject
SmsCommunicatorPlugin smsCommunicatorPlugin;
@Inject
StatusLinePlugin statusLinePlugin;
@Inject AutomationPlugin automationPlugin;
@Inject DanaRPlugin danaRPlugin;
@Inject DanaRKoreanPlugin danaRKoreanPlugin;
@Inject DanaRv2Plugin danaRv2Plugin;
@Inject DanaRSPlugin danaRSPlugin;
@Inject CareportalPlugin careportalPlugin;
@Inject InsulinOrefFreePeakPlugin insulinOrefFreePeakPlugin;
@Inject OpenAPSAMAPlugin openAPSAMAPlugin;
@Inject OpenAPSMAPlugin openAPSMAPlugin;
@Inject OpenAPSSMBPlugin openAPSSMBPlugin;
@Inject SafetyPlugin safetyPlugin;
@Inject SmsCommunicatorPlugin smsCommunicatorPlugin;
@Inject StatusLinePlugin statusLinePlugin;
@Inject TidepoolPlugin tidepoolPlugin;
@Inject VirtualPumpPlugin virtualPumpPlugin;
@Override
public void setArguments(Bundle args) {
@ -105,7 +105,7 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro
addPreferencesFromResource(R.xml.pref_overview);
addPreferencesFromResourceIfEnabled(SourceDexcomPlugin.INSTANCE, PluginType.BGSOURCE);
addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(careportalPlugin, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(safetyPlugin, PluginType.CONSTRAINTS);
if (Config.APS) {
addPreferencesFromResourceIfEnabled(LoopPlugin.getPlugin(), PluginType.LOOP);
@ -120,25 +120,25 @@ public class MyPreferenceFragment extends PreferenceFragment implements HasAndro
addPreferencesFromResourceIfEnabled(SensitivityOref1Plugin.getPlugin(), PluginType.SENSITIVITY);
if (Config.PUMPDRIVERS) {
addPreferencesFromResourceIfEnabled(DanaRPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(danaRPlugin, PluginType.PUMP);
addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, PluginType.PUMP);
addPreferencesFromResourceIfEnabled(danaRv2Plugin, PluginType.PUMP);
addPreferencesFromResourceIfEnabled(danaRSPlugin, PluginType.PUMP);
addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP);
}
if (!Config.NSCLIENT) {
addPreferencesFromResourceIfEnabled(VirtualPumpPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(virtualPumpPlugin, PluginType.PUMP);
}
addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, PluginType.INSULIN);
addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(TidepoolPlugin.INSTANCE, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(tidepoolPlugin, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(smsCommunicatorPlugin, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(AutomationPlugin.INSTANCE, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(automationPlugin, PluginType.GENERAL);
addPreferencesFromResource(R.xml.pref_others);
addPreferencesFromResource(R.xml.pref_datachoices);

View file

@ -61,14 +61,14 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
RxBus.INSTANCE.send(new EventPreferenceChange(key));
RxBus.Companion.getINSTANCE().send(new EventPreferenceChange(key));
if (key.equals(MainApp.gs(R.string.key_language))) {
RxBus.INSTANCE.send(new EventRebuildTabs(true));
RxBus.Companion.getINSTANCE().send(new EventRebuildTabs(true));
//recreate() does not update language so better close settings
finish();
}
if (key.equals(MainApp.gs(R.string.key_short_tabtitles))) {
RxBus.INSTANCE.send(new EventRebuildTabs());
RxBus.Companion.getINSTANCE().send(new EventRebuildTabs());
}
if (key.equals(MainApp.gs(R.string.key_units))) {
recreate();

View file

@ -1,19 +1,18 @@
package info.nightscout.androidaps.activities
import android.os.Bundle
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.ActivityMonitor
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.TddCalculator
import info.nightscout.androidaps.utils.TirCalculator
import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.stats_activity.*
import javax.inject.Inject
class StatsActivity : NoSplashAppCompatActivity() {
@Inject
lateinit var tddCalculator: TddCalculator
@Inject lateinit var tddCalculator: TddCalculator
@Inject lateinit var resourceHelper: ResourceHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@ -25,7 +24,7 @@ class StatsActivity : NoSplashAppCompatActivity() {
ok.setOnClickListener { finish() }
stats_reset.setOnClickListener {
OKDialog.showConfirmation(this, MainApp.gs(R.string.doyouwantresetstats), Runnable {
OKDialog.showConfirmation(this, resourceHelper.gs(R.string.doyouwantresetstats), Runnable {
ActivityMonitor.reset()
recreate()
})

View file

@ -6,19 +6,21 @@ import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.defaultProfile.DefaultProfile
import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.dialogs.ProfileViewerDialog
import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.survey_activity.*
import org.slf4j.LoggerFactory
import javax.inject.Inject
class SurveyActivity : NoSplashAppCompatActivity() {
private val log = LoggerFactory.getLogger(SurveyActivity::class.java)
@Inject
lateinit var tddCalculator: TddCalculator
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var tddCalculator: TddCalculator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@ -26,7 +28,7 @@ class SurveyActivity : NoSplashAppCompatActivity() {
survey_id.text = InstanceId.instanceId()
val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile
val profileStore = configBuilderPlugin.activeProfileInterface.profile
val profileList = profileStore?.getProfileList() ?: return
survey_spinner.adapter = ArrayAdapter(this, R.layout.spinner_centered, profileList)
@ -87,13 +89,13 @@ class SurveyActivity : NoSplashAppCompatActivity() {
auth.signInAnonymously()
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
log.debug("signInAnonymously:success")
aapsLogger.debug(LTag.CORE, "signInAnonymously:success")
val user = auth.currentUser // TODO: do we need this, seems unused?
val database = FirebaseDatabase.getInstance().reference
database.child("survey").child(r.id).setValue(r)
} else {
log.error("signInAnonymously:failure", task.exception)
aapsLogger.error("signInAnonymously:failure", task.exception!!)
ToastUtils.showToastInUiThread(this, "Authentication failed.")
//updateUI(null)
}

View file

@ -77,12 +77,12 @@ public class TDDStatsActivity extends NoSplashAppCompatActivity {
@Override
protected void onResume() {
super.onResume();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventPumpStatusChanged.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventDanaRSyncStatus.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {

View file

@ -235,7 +235,7 @@ public class Profile {
if (notify && secondsFromMidnight % 3600 != 0) {
if (Config.APS) {
Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, String.format(MainApp.gs(R.string.basalprofilenotaligned), from), Notification.NORMAL);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
}
}
}
@ -267,11 +267,11 @@ public class Profile {
}
protected void sendBelowMinimumNotification(String from) {
RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
}
protected void sendAboveMaximumNotification(String from) {
RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
}
private void validate(LongSparseArray array) {

View file

@ -224,7 +224,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true);
scheduleBgChange(null); // trigger refresh
scheduleTemporaryBasalChange();
scheduleExtendedBolusChange();
@ -235,7 +235,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
new java.util.TimerTask() {
@Override
public void run() {
RxBus.INSTANCE.send(new EventRefreshOverview("resetDatabases"));
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("resetDatabases"));
}
},
3000
@ -260,7 +260,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
VirtualPumpPlugin.getPlugin().setFakingStatus(false);
VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(false);
scheduleTemporaryBasalChange();
}
@ -404,7 +404,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
RxBus.INSTANCE.send(new EventNewBG(bgReading));
RxBus.Companion.getINSTANCE().send(new EventNewBG(bgReading));
scheduledBgPost = null;
}
}
@ -729,7 +729,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange");
RxBus.INSTANCE.send(new EventTempTargetChange());
RxBus.Companion.getINSTANCE().send(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
}
@ -1026,10 +1026,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempBasalChange");
RxBus.INSTANCE.send(new EventReloadTempBasalData());
RxBus.INSTANCE.send(new EventTempBasalChange());
RxBus.Companion.getINSTANCE().send(new EventReloadTempBasalData());
RxBus.Companion.getINSTANCE().send(new EventTempBasalChange());
if (earliestDataChange != null)
RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange));
RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
@ -1071,8 +1071,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
.insulin(trJson.getDouble("originalExtendedAmount"))
._id(trJson.getString("_id"));
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
if (!VirtualPumpPlugin.Companion.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
@ -1086,8 +1086,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
extendedBolus.insulin = 0;
extendedBolus._id = trJson.getString("_id");
// if faking found in NS, adapt AAPS to use it too
if (!VirtualPumpPlugin.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.getPlugin().setFakingStatus(true);
if (!VirtualPumpPlugin.Companion.getPlugin().getFakingStatus()) {
VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true);
updateEarliestDataChange(0);
scheduleTemporaryBasalChange();
}
@ -1362,9 +1362,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange");
RxBus.INSTANCE.send(new EventReloadTreatmentData(new EventExtendedBolusChange()));
RxBus.Companion.getINSTANCE().send(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange));
RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
@ -1568,7 +1568,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange");
RxBus.INSTANCE.send(new EventCareportalEventChange());
RxBus.Companion.getINSTANCE().send(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
}
@ -1741,8 +1741,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventProfileNeedsUpdate");
RxBus.INSTANCE.send(new EventReloadProfileSwitchData());
RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
RxBus.Companion.getINSTANCE().send(new EventReloadProfileSwitchData());
RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate());
scheduledProfileSwitchEventPost = null;
}
}

View file

@ -111,7 +111,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
*/
public String getCustomizedName() {
String name = profileName;
if (LocalProfilePlugin.LOCAL_PROFILE.equals(name)) {
if (LocalProfilePlugin.Companion.getLOCAL_PROFILE().equals(name)) {
name = DecimalFormatter.to2Decimal(getProfileObject().percentageBasalSum()) + "U ";
}
if (isCPP) {
@ -226,7 +226,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
private void createNotificationInvalidProfile(String detail) {
Notification notification = new Notification(Notification.ZERO_VALUE_IN_PROFILE, String.format(MainApp.gs(R.string.zerovalueinprofile), detail), Notification.LOW, 5);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
}
public static boolean isEvent5minBack(List<ProfileSwitch> list, long time, boolean zeroDurationOnly) {

View file

@ -19,6 +19,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.dialog.MedtronicHistory
import info.nightscout.androidaps.setupwizard.SetupWizardActivity
@Module
@Suppress("unused")
abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity

View file

@ -6,10 +6,9 @@ import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS
import info.nightscout.androidaps.queue.commands.CommandSetProfile
import info.nightscout.androidaps.services.DataService
import javax.inject.Singleton
@Singleton
@ -18,18 +17,23 @@ import javax.inject.Singleton
AndroidInjectionModule::class,
ActivitiesModule::class,
FragmentsModule::class,
AppModule::class
AppModule::class,
ReceiversModule::class,
ServicesModule::class
]
)
interface AppComponent : AndroidInjector<MainApp> {
fun injectDataService(service: DataService)
fun injectCommandSetProfile(commandSetProfile: CommandSetProfile)
fun injectActionSendSMS(actionSendSMS: ActionSendSMS)
fun injectObjective0(objective0: Objective0)
fun injectObjective1(objective1: Objective1)
fun injectObjective2(objective2: Objective2)
fun injectObjective3(objective3: Objective3)
fun injectObjective5(objective5: Objective5)
fun injectObjective6(objective6: Objective6)
fun injectLoggerCallback(loggerCallback: LoggerCallback)

View file

@ -12,14 +12,12 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.AAPSLoggerDebug
import info.nightscout.androidaps.logging.AAPSLoggerProduction
import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
import info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.commands.CommandSetProfile
import info.nightscout.androidaps.services.DataService
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation
import info.nightscout.androidaps.utils.sharedPreferences.SP
@ -37,14 +35,8 @@ class AppModule {
@Provides
@Singleton
fun provideProfileFunction(sp: SP): ProfileFunction {
return ProfileFunctionImplementation(sp)
}
@Provides
@Singleton
fun provideConstraintChecker(mainApp: MainApp): ConstraintChecker {
return ConstraintChecker(mainApp)
fun provideProfileFunction(sp: SP, configBuilderPlugin: ConfigBuilderPlugin): ProfileFunction {
return ProfileFunctionImplementation(sp, configBuilderPlugin)
}
@Provides
@ -66,22 +58,16 @@ class AppModule {
@Module
interface AppBindings {
@ContributesAndroidInjector
fun dataServiceInjector(): DataService
@ContributesAndroidInjector fun commandSetProfileInjector(): CommandSetProfile
@ContributesAndroidInjector fun actionSendSMSInjector(): ActionSendSMS
@ContributesAndroidInjector fun objective0Injector(): Objective0
@ContributesAndroidInjector fun objective1Injector(): Objective1
@ContributesAndroidInjector fun objective2Injector(): Objective2
@ContributesAndroidInjector fun objective3Injector(): Objective3
@ContributesAndroidInjector fun objective5Injector(): Objective5
@ContributesAndroidInjector fun objective6Injector(): Objective6
@ContributesAndroidInjector fun loggerCallbackInjector(): LoggerCallback
@ContributesAndroidInjector
fun commandSetProfileInjector(): CommandSetProfile
@ContributesAndroidInjector
fun actionSendSMSInjector(): ActionSendSMS
@ContributesAndroidInjector
fun objective5Injector(): Objective5
@ContributesAndroidInjector
fun loggerCallbackInjector(): LoggerCallback
@Binds
fun bindContext(mainApp: MainApp): Context
@Binds fun bindContext(mainApp: MainApp): Context
}
}

View file

@ -7,32 +7,75 @@ import info.nightscout.androidaps.dialogs.*
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAFragment
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAFragment
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog
import info.nightscout.androidaps.plugins.general.actions.ActionsFragment
import info.nightscout.androidaps.plugins.general.automation.AutomationFragment
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseActionDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditActionDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditTriggerDialog
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment
import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorFragment
import info.nightscout.androidaps.plugins.general.tidepool.TidepoolFragment
import info.nightscout.androidaps.plugins.profile.local.LocalProfileFragment
import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpFragment
import info.nightscout.androidaps.plugins.source.BGSourceFragment
import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment
@Module
@Suppress("unused")
abstract class FragmentsModule {
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment
@ContributesAndroidInjector abstract fun contributesPreferencesFragment(): MyPreferenceFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment
@ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment
@ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment
@ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment
@ContributesAndroidInjector abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment
@ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment
@ContributesAndroidInjector abstract fun contributesEditActionDialog(): EditActionDialog
@ContributesAndroidInjector abstract fun contributesEditEventDialog(): EditEventDialog
@ContributesAndroidInjector abstract fun contributesEditTriggerDialog(): EditTriggerDialog
@ContributesAndroidInjector abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog
@ContributesAndroidInjector abstract fun contributesChooseActionDialog(): ChooseActionDialog
@ContributesAndroidInjector abstract fun contributesChooseTriggerDialog(): ChooseTriggerDialog
@ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment
@ContributesAndroidInjector abstract fun contributesObjectivesFragment(): ObjectivesFragment
@ContributesAndroidInjector abstract fun contributesOpenAPSAMAFragment(): OpenAPSAMAFragment
@ContributesAndroidInjector abstract fun contributesOpenAPSMAFragment(): OpenAPSMAFragment
@ContributesAndroidInjector abstract fun contributesOpenAPSSMBFragment(): OpenAPSSMBFragment
@ContributesAndroidInjector abstract fun contributesOverviewFragment(): OverviewFragment
@ContributesAndroidInjector abstract fun contributesMedtronicFragment(): MedtronicFragment
@ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment
@ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment
@ContributesAndroidInjector abstract fun contributesTidepoolFragment(): TidepoolFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsFragment(): TreatmentsFragment
@ContributesAndroidInjector abstract fun contributesTreatmentsProfileSwitchFragment(): TreatmentsProfileSwitchFragment
@ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog
@Suppress("unused") @ContributesAndroidInjector abstract fun contributesWizardDialog(): WizardDialog
@ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog
@ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog
@ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog
@ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog
@ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog
@ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog
@ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog
@ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog
@ContributesAndroidInjector abstract fun contributesNtpProgressDialog(): NtpProgressDialog
@ContributesAndroidInjector abstract fun contributesObjectivesExamDialog(): ObjectivesExamDialog
@ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog
@ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog
@ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog
@ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog
@ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog
@ContributesAndroidInjector abstract fun contributesWizardDialog(): WizardDialog
}

View file

@ -0,0 +1,12 @@
package info.nightscout.androidaps.dependencyInjection
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.receivers.KeepAliveReceiver
@Module
@Suppress("unused")
abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver
}

View file

@ -0,0 +1,12 @@
package info.nightscout.androidaps.dependencyInjection
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.services.DataService
@Module
@Suppress("unused")
abstract class ServicesModule {
@ContributesAndroidInjector abstract fun contributesDataService(): DataService
}

View file

@ -8,28 +8,32 @@ import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import info.nightscout.androidaps.MainApp
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.BolusProgressHelperActivity
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus.toObservable
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.dialog_bolusprogress.*
import org.slf4j.LoggerFactory
import javax.inject.Inject
class BolusProgressDialog : DaggerDialogFragment() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
class BolusProgressDialog : DialogFragment() {
private val log = LoggerFactory.getLogger(L.UI)
private val disposable = CompositeDisposable()
companion object {
private val DEFAULT_STATE = MainApp.gs(R.string.waitingforpump)
@JvmField
var bolusEnded = false
@JvmField
@ -62,16 +66,17 @@ class BolusProgressDialog : DialogFragment() {
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
overview_bolusprogress_title.text = String.format(MainApp.gs(R.string.overview_bolusprogress_goingtodeliver), amount)
overview_bolusprogress_title.text = resourceHelper.gs(R.string.overview_bolusprogress_goingtodeliver, amount)
overview_bolusprogress_stop.setOnClickListener {
if (L.isEnabled(L.UI)) log.debug("Stop bolus delivery button pressed")
aapsLogger.debug(LTag.UI, "Stop bolus delivery button pressed")
stopPressed = true
overview_bolusprogress_stoppressed.visibility = View.VISIBLE
overview_bolusprogress_stop.visibility = View.INVISIBLE
ConfigBuilderPlugin.getPlugin().commandQueue.cancelAllBoluses()
configBuilderPlugin.commandQueue.cancelAllBoluses()
}
val defaultState = resourceHelper.gs(R.string.waitingforpump)
overview_bolusprogress_progressbar.max = 100
state = savedInstanceState?.getString("state", DEFAULT_STATE) ?: DEFAULT_STATE
state = savedInstanceState?.getString("state", defaultState) ?: defaultState
overview_bolusprogress_status.text = state
stopPressed = false
}
@ -83,25 +88,28 @@ class BolusProgressDialog : DialogFragment() {
override fun onResume() {
super.onResume()
if (L.isEnabled(L.UI)) log.debug("onResume")
if (!ConfigBuilderPlugin.getPlugin().commandQueue.bolusInQueue())
aapsLogger.debug(LTag.UI, "onResume")
if (!configBuilderPlugin.commandQueue.bolusInQueue())
bolusEnded = true
if (bolusEnded) dismiss()
else running = true
disposable.add(toObservable(EventPumpStatusChanged::class.java)
disposable.add(rxBus
.toObservable(EventPumpStatusChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ overview_bolusprogress_status.text = it.getStatus() }) { FabricPrivacy.logException(it) }
)
disposable.add(toObservable(EventDismissBolusProgressIfRunning::class.java)
disposable.add(rxBus
.toObservable(EventDismissBolusProgressIfRunning::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ if (running) dismiss() }) { FabricPrivacy.logException(it) }
)
disposable.add(toObservable(EventOverviewBolusProgress::class.java)
disposable.add(rxBus
.toObservable(EventOverviewBolusProgress::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (L.isEnabled(L.UI)) log.debug("Status: " + it.status + " Percent: " + it.percent)
aapsLogger.debug(LTag.UI, "Status: ${it.status} Percent: ${it.percent}")
overview_bolusprogress_status.text = it.status
overview_bolusprogress_progressbar.progress = it.percent
if (it.percent == 100) {
@ -114,21 +122,21 @@ class BolusProgressDialog : DialogFragment() {
}
override fun dismiss() {
if (L.isEnabled(L.UI)) log.debug("dismiss")
aapsLogger.debug(LTag.UI, "dismiss")
try {
super.dismiss()
} catch (e: IllegalStateException) {
// dialog not running yet. onResume will try again. Set bolusEnded to make extra
// sure onResume will catch this
bolusEnded = true
log.error("Unhandled exception", e)
aapsLogger.error("Unhandled exception", e)
}
helpActivity?.finish()
}
override fun onPause() {
super.onPause()
if (L.isEnabled(L.UI)) log.debug("onPause")
aapsLogger.debug(LTag.UI, "onPause")
running = false
disposable.clear()
}
@ -139,18 +147,18 @@ class BolusProgressDialog : DialogFragment() {
}
private fun scheduleDismiss() {
if (L.isEnabled(L.UI)) log.debug("scheduleDismiss")
aapsLogger.debug(LTag.UI, "scheduleDismiss")
Thread(Runnable {
SystemClock.sleep(5000)
bolusEnded = true
val activity: Activity? = activity
activity?.runOnUiThread {
if (running) {
if (L.isEnabled(L.UI)) log.debug("executing")
aapsLogger.debug(LTag.UI, "executing")
try {
dismiss()
} catch (e: Exception) {
log.error("Unhandled exception", e)
aapsLogger.error("Unhandled exception", e)
}
}
}

View file

@ -32,15 +32,10 @@ import javax.inject.Inject
import kotlin.math.max
class CarbsDialog : DialogFragmentWithDate() {
@Inject
lateinit var mainApp: MainApp
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject
lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
companion object {
private const val FAV1_DEFAULT = 5
@ -100,30 +95,30 @@ class CarbsDialog : DialogFragmentWithDate() {
overview_carbs_carbs.setParams(savedInstanceState?.getDouble("overview_carbs_carbs")
?: 0.0, 0.0, maxCarbs, 1.0, DecimalFormat("0"), false, ok, textWatcher)
overview_carbs_plus1.text = toSignedString(SP.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
overview_carbs_plus1.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
overview_carbs_plus1.setOnClickListener {
overview_carbs_carbs.value = max(0.0, overview_carbs_carbs.value
+ SP.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
+ sp.getInt(R.string.key_carbs_button_increment_1, FAV1_DEFAULT))
validateInputs()
}
overview_carbs_plus2.text = toSignedString(SP.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
overview_carbs_plus2.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
overview_carbs_plus2.setOnClickListener {
overview_carbs_carbs.value = max(0.0, overview_carbs_carbs.value
+ SP.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
+ sp.getInt(R.string.key_carbs_button_increment_2, FAV2_DEFAULT))
validateInputs()
}
overview_carbs_plus3.text = toSignedString(SP.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
overview_carbs_plus3.text = toSignedString(sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
overview_carbs_plus3.setOnClickListener {
overview_carbs_carbs.value = max(0.0, overview_carbs_carbs.value
+ SP.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
+ sp.getInt(R.string.key_carbs_button_increment_3, FAV3_DEFAULT))
validateInputs()
}
DatabaseHelper.actualBg()?.let { bgReading ->
if (bgReading.value < 72)
overview_carbs_hypo_tt.setChecked(true)
overview_carbs_hypo_tt.isChecked = true
}
overview_carbs_hypo_tt.setOnClickListener {
overview_carbs_activity_tt.isChecked = false
@ -185,33 +180,39 @@ class CarbsDialog : DialogFragmentWithDate() {
if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.carbs), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
if (activitySelected) {
val tempTarget = TempTarget()
.date(System.currentTimeMillis())
.duration(activityTTDuration)
.reason(resourceHelper.gs(R.string.activity))
.source(Source.USER)
.low(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits()))
.high(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits()))
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
} else if (eatingSoonSelected) {
val tempTarget = TempTarget()
.date(System.currentTimeMillis())
.duration(eatingSoonTTDuration)
.reason(resourceHelper.gs(R.string.eatingsoon))
.source(Source.USER)
.low(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits()))
.high(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits()))
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
} else if (hypoSelected) {
val tempTarget = TempTarget()
.date(System.currentTimeMillis())
.duration(hypoTTDuration)
.reason(resourceHelper.gs(R.string.hypo))
.source(Source.USER)
.low(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits()))
.high(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits()))
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
when {
activitySelected -> {
val tempTarget = TempTarget()
.date(System.currentTimeMillis())
.duration(activityTTDuration)
.reason(resourceHelper.gs(R.string.activity))
.source(Source.USER)
.low(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits()))
.high(Profile.toMgdl(activityTT, ProfileFunctions.getSystemUnits()))
treatmentsPlugin.addToHistoryTempTarget(tempTarget)
}
eatingSoonSelected -> {
val tempTarget = TempTarget()
.date(System.currentTimeMillis())
.duration(eatingSoonTTDuration)
.reason(resourceHelper.gs(R.string.eatingsoon))
.source(Source.USER)
.low(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits()))
.high(Profile.toMgdl(eatingSoonTT, ProfileFunctions.getSystemUnits()))
treatmentsPlugin.addToHistoryTempTarget(tempTarget)
}
hypoSelected -> {
val tempTarget = TempTarget()
.date(System.currentTimeMillis())
.duration(hypoTTDuration)
.reason(resourceHelper.gs(R.string.hypo))
.source(Source.USER)
.low(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits()))
.high(Profile.toMgdl(hypoTT, ProfileFunctions.getSystemUnits()))
treatmentsPlugin.addToHistoryTempTarget(tempTarget)
}
}
if (carbsAfterConstraints > 0) {
if (duration == 0) {

View file

@ -19,7 +19,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.Translator
import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.dialog_care.*
@ -31,12 +30,8 @@ import java.util.*
import javax.inject.Inject
class CareDialog : DialogFragmentWithDate() {
@Inject
lateinit var mainApp: MainApp
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
enum class EventType {
BGCHECK,
@ -112,7 +107,7 @@ class CareDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val enteredBy = SP.getString("careportal_enteredby", "")
val enteredBy = sp.getString("careportal_enteredby", "")
val unitResId = if (ProfileFunctions.getSystemUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol
val json = JSONObject()

View file

@ -10,17 +10,20 @@ import android.view.Window
import android.view.WindowManager
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.toVisibility
import kotlinx.android.synthetic.main.datetime.*
import kotlinx.android.synthetic.main.notes.*
import kotlinx.android.synthetic.main.okcancel.*
import org.slf4j.LoggerFactory
import java.util.*
import javax.inject.Inject
abstract class DialogFragmentWithDate : DaggerDialogFragment() {
private val log = LoggerFactory.getLogger(DialogFragmentWithDate::class.java)
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
var eventTime = DateUtil.now()
var eventTimeChanged = false
@ -104,12 +107,12 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() {
}
}
notes_layout?.visibility = SP.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility()
notes_layout?.visibility = sp.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility()
ok.setOnClickListener {
synchronized(okClicked) {
if (okClicked) {
log.debug("guarding: ok already clicked")
aapsLogger.warn(LTag.UI, "guarding: ok already clicked")
} else {
okClicked = true
if (submit()) dismiss()

View file

@ -8,16 +8,19 @@ import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.services.AlarmSoundService
import kotlinx.android.synthetic.main.dialog_error.*
import org.slf4j.LoggerFactory
import javax.inject.Inject
class ErrorDialog : DialogFragment() {
private val log = LoggerFactory.getLogger(ErrorDialog::class.java)
class ErrorDialog : DaggerDialogFragment() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var mainApp: MainApp
var helperActivity: ErrorHelperActivity? = null
var status: String = ""
@ -44,11 +47,11 @@ class ErrorDialog : DialogFragment() {
error_title.text = title
overview_error_ok.setOnClickListener {
log.debug("Error dialog ok button pressed")
aapsLogger.debug(LTag.UI, "Error dialog ok button pressed")
dismiss()
}
overview_error_mute.setOnClickListener {
log.debug("Error dialog mute button pressed")
aapsLogger.debug(LTag.UI, "Error dialog mute button pressed")
stopAlarm()
}
startAlarm()
@ -79,16 +82,16 @@ class ErrorDialog : DialogFragment() {
private fun startAlarm() {
if (sound != 0) {
val alarm = Intent(MainApp.instance().applicationContext, AlarmSoundService::class.java)
val alarm = Intent(mainApp, AlarmSoundService::class.java)
alarm.putExtra("soundid", sound)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MainApp.instance().startForegroundService(alarm)
mainApp.startForegroundService(alarm)
} else {
MainApp.instance().startService(alarm)
mainApp.startService(alarm)
}
}
}
private fun stopAlarm() =
MainApp.instance().stopService(Intent(MainApp.instance().applicationContext, AlarmSoundService::class.java))
mainApp.stopService(Intent(mainApp, AlarmSoundService::class.java))
}

View file

@ -25,15 +25,10 @@ import javax.inject.Inject
import kotlin.math.abs
class ExtendedBolusDialog : DialogFragmentWithDate() {
@Inject
lateinit var mainApp: MainApp
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject
lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
@ -50,7 +45,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return
val pumpDescription = configBuilderPlugin.activePump?.pumpDescription ?: return
val maxInsulin = constraintChecker.getMaxExtendedBolusAllowed().value()
val extendedStep = pumpDescription.extendedBolusStep
@ -75,7 +70,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() {
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
ConfigBuilderPlugin.getPlugin().commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() {
configBuilderPlugin.commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(mainApp, ErrorHelperActivity::class.java)

View file

@ -23,7 +23,6 @@ import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import kotlinx.android.synthetic.main.dialog_fill.*
import kotlinx.android.synthetic.main.notes.*
import kotlinx.android.synthetic.main.okcancel.*
@ -32,22 +31,14 @@ import javax.inject.Inject
import kotlin.math.abs
class FillDialog : DialogFragmentWithDate() {
@Inject
lateinit var constraintChecker: ConstraintChecker
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject
lateinit var sp: SP
@Inject
lateinit var mainApp: MainApp
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var mainApp: MainApp
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("fill_insulinamount", fill_insulinamount.value)
savedInstanceState.putDouble("fill_insulin_amount", fill_insulinamount.value)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
@ -60,8 +51,8 @@ class FillDialog : DialogFragmentWithDate() {
super.onViewCreated(view, savedInstanceState)
val maxInsulin = constraintChecker.getMaxBolusAllowed().value()
val bolusStep = ConfigBuilderPlugin.getPlugin().activePump!!.pumpDescription.bolusStep
fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulinamount")
val bolusStep = configBuilderPlugin.activePump!!.pumpDescription.bolusStep
fill_insulinamount.setParams(savedInstanceState?.getDouble("fill_insulin_amount")
?: 0.0, 0.0, maxInsulin, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), true, ok)
val amount1 = sp.getDouble("fill_button1", 0.3)
if (amount1 > 0) {
@ -98,7 +89,7 @@ class FillDialog : DialogFragmentWithDate() {
if (insulinAfterConstraints > 0) {
actions.add(resourceHelper.gs(R.string.fillwarning))
actions.add("")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.colorInsulinButton) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + MainApp.gs(R.string.insulin_unit_shortname) + "</font>")
actions.add(resourceHelper.gs(R.string.bolus) + ": " + "<font color='" + resourceHelper.gc(R.color.colorInsulinButton) + "'>" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + resourceHelper.gs(R.string.insulin_unit_shortname) + "</font>")
if (abs(insulinAfterConstraints - insulin) > 0.01)
actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), insulin, insulinAfterConstraints))
}
@ -124,7 +115,7 @@ class FillDialog : DialogFragmentWithDate() {
detailedBolusInfo.source = Source.USER
detailedBolusInfo.isValid = false // do not count it in IOB (for pump history)
detailedBolusInfo.notes = notes
ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() {
configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(mainApp, ErrorHelperActivity::class.java)

View file

@ -35,18 +35,12 @@ import kotlin.math.abs
import kotlin.math.max
class InsulinDialog : DialogFragmentWithDate() {
@Inject
lateinit var constraintChecker: ConstraintChecker
@Inject
lateinit var mainApp: MainApp
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject
lateinit var profileFunction: ProfileFunction
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
companion object {
private const val PLUS1_DEFAULT = 0.5
@ -95,24 +89,24 @@ class InsulinDialog : DialogFragmentWithDate() {
overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time")
?: 0.0, -12 * 60.0, 12 * 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher)
overview_insulin_amount.setParams(savedInstanceState?.getDouble("overview_insulin_amount")
?: 0.0, 0.0, maxInsulin, ConfigBuilderPlugin.getPlugin().activePump!!.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
?: 0.0, 0.0, maxInsulin, configBuilderPlugin.activePump!!.pumpDescription.bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
overview_insulin_plus05.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT))
overview_insulin_plus05.text = toSignedString(sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT))
overview_insulin_plus05.setOnClickListener {
overview_insulin_amount.value = max(0.0, overview_insulin_amount.value
+ SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT))
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_1), PLUS1_DEFAULT))
validateInputs()
}
overview_insulin_plus10.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT))
overview_insulin_plus10.text = toSignedString(sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT))
overview_insulin_plus10.setOnClickListener {
overview_insulin_amount.value = max(0.0, overview_insulin_amount.value
+ SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT))
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_2), PLUS2_DEFAULT))
validateInputs()
}
overview_insulin_plus20.text = toSignedString(SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT))
overview_insulin_plus20.text = toSignedString(sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT))
overview_insulin_plus20.setOnClickListener {
overview_insulin_amount.value = Math.max(0.0, overview_insulin_amount.value
+ SP.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT))
+ sp.getDouble(resourceHelper.gs(R.string.key_insulin_button_increment_3), PLUS3_DEFAULT))
validateInputs()
}
@ -128,7 +122,7 @@ class InsulinDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription
val pumpDescription = configBuilderPlugin.activePump?.pumpDescription
?: return false
val insulin = SafeParse.stringToDouble(overview_insulin_amount.text)
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
@ -170,7 +164,7 @@ class InsulinDialog : DialogFragmentWithDate() {
.source(Source.USER)
.low(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()))
.high(Profile.toMgdl(eatingSoonTT, profileFunction.getUnits()))
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
treatmentsPlugin.addToHistoryTempTarget(tempTarget)
}
if (insulinAfterConstraints > 0) {
val detailedBolusInfo = DetailedBolusInfo()
@ -181,10 +175,10 @@ class InsulinDialog : DialogFragmentWithDate() {
detailedBolusInfo.notes = notes
if (recordOnlyChecked) {
detailedBolusInfo.date = time
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false)
treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false)
} else {
detailedBolusInfo.date = DateUtil.now()
ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() {
configBuilderPlugin.commandQueue.bolus(detailedBolusInfo, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(mainApp, ErrorHelperActivity::class.java)

View file

@ -21,7 +21,6 @@ import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import kotlinx.android.synthetic.main.dialog_temptarget.*
import kotlinx.android.synthetic.main.okcancel.*
import java.text.DecimalFormat
@ -29,18 +28,10 @@ import java.util.*
import javax.inject.Inject
class TempTargetDialog : DialogFragmentWithDate() {
@Inject
lateinit var constraintChecker: ConstraintChecker
@Inject
lateinit var sp: SP
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject
lateinit var profileFunction: ProfileFunction
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
@ -147,7 +138,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
.duration(0)
.low(0.0).high(0.0)
.source(Source.USER)
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
treatmentsPlugin.addToHistoryTempTarget(tempTarget)
} else {
val tempTarget = TempTarget()
.date(eventTime)
@ -156,7 +147,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
.source(Source.USER)
.low(Profile.toMgdl(target, profileFunction.getUnits()))
.high(Profile.toMgdl(target, profileFunction.getUnits()))
TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
treatmentsPlugin.addToHistoryTempTarget(tempTarget)
}
if (duration == 10.0) sp.putBoolean(R.string.key_objectiveusetemptarget, true)
})

View file

@ -20,7 +20,7 @@ import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.DatabaseHelper
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction
@ -42,20 +42,14 @@ import kotlin.math.abs
class WizardDialog : DaggerDialogFragment() {
private val log = LoggerFactory.getLogger(WizardDialog::class.java)
@Inject
lateinit var constraintChecker: ConstraintChecker
@Inject
lateinit var mainApp: MainApp
@Inject
lateinit var resourceHelper: ResourceHelper
@Inject
lateinit var profileFunction: ProfileFunction
@Inject
lateinit var sp: SP
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var sp: SP
@Inject lateinit var rxBus: RxBusWrapper
private var wizard: BolusWizard? = null
@ -108,7 +102,7 @@ class WizardDialog : DaggerDialogFragment() {
?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher)
treatments_wizard_carbs_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carbs_input")
?: 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false, ok, textWatcher)
val bolusStep = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription?.bolusStep
val bolusStep = configBuilderPlugin.activePump?.pumpDescription?.bolusStep
?: 0.1
treatments_wizard_correction_input.setParams(savedInstanceState?.getDouble("treatments_wizard_correction_input")
?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
@ -165,7 +159,7 @@ class WizardDialog : DaggerDialogFragment() {
}
}
// bus
disposable.add(RxBus
disposable.add(rxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -184,7 +178,7 @@ class WizardDialog : DaggerDialogFragment() {
private fun onCheckedChanged(buttonView: CompoundButton, @Suppress("UNUSED_PARAMETER") state: Boolean) {
saveCheckedStates()
treatments_wizard_ttcheckbox.isEnabled = treatments_wizard_bgcheckbox.isChecked && TreatmentsPlugin.getPlugin().tempTargetFromHistory != null
treatments_wizard_ttcheckbox.isEnabled = treatments_wizard_bgcheckbox.isChecked && treatmentsPlugin.tempTargetFromHistory != null
if (buttonView.id == treatments_wizard_cobcheckbox.id)
processCobCheckBox()
calculateInsulin()
@ -214,7 +208,7 @@ class WizardDialog : DaggerDialogFragment() {
private fun initDialog() {
val profile = profileFunction.getProfile()
val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface.profile
val profileStore = configBuilderPlugin.activeProfileInterface.profile
if (profile == null || profileStore == null) {
ToastUtils.showToastInUiThread(mainApp, resourceHelper.gs(R.string.noprofile))
@ -245,13 +239,13 @@ class WizardDialog : DaggerDialogFragment() {
} else {
treatments_wizard_bg_input.value = 0.0
}
treatments_wizard_ttcheckbox.isEnabled = TreatmentsPlugin.getPlugin().tempTargetFromHistory != null
treatments_wizard_ttcheckbox.isEnabled = treatmentsPlugin.tempTargetFromHistory != null
// IOB calculation
TreatmentsPlugin.getPlugin().updateTotalIOBTreatments()
val bolusIob = TreatmentsPlugin.getPlugin().lastCalculationTreatments.round()
TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals()
val basalIob = TreatmentsPlugin.getPlugin().lastCalculationTempBasals.round()
treatmentsPlugin.updateTotalIOBTreatments()
val bolusIob = treatmentsPlugin.lastCalculationTreatments.round()
treatmentsPlugin.updateTotalIOBTempBasals()
val basalIob = treatmentsPlugin.lastCalculationTempBasals.round()
treatments_wizard_bolusiobinsulin.text = StringUtils.formatInsulin(-bolusIob.iob)
treatments_wizard_basaliobinsulin.text = StringUtils.formatInsulin(-basalIob.basaliob)
@ -262,7 +256,7 @@ class WizardDialog : DaggerDialogFragment() {
}
private fun calculateInsulin() {
val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface.profile
val profileStore = configBuilderPlugin.activeProfileInterface.profile
if (treatments_wizard_profile.selectedItem == null || profileStore == null)
return // not initialized yet
var profileName = treatments_wizard_profile.selectedItem.toString()
@ -287,7 +281,7 @@ class WizardDialog : DaggerDialogFragment() {
}
bg = if (treatments_wizard_bgcheckbox.isChecked) bg else 0.0
val tempTarget = if (treatments_wizard_ttcheckbox.isChecked) TreatmentsPlugin.getPlugin().tempTargetFromHistory else null
val tempTarget = if (treatments_wizard_ttcheckbox.isChecked) treatmentsPlugin.tempTargetFromHistory else null
// COB
var cob = 0.0

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.events.EventRebuildTabs
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.logging.L.isEnabled
import info.nightscout.androidaps.plugins.bus.RxBus.send
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui
import info.nightscout.androidaps.utils.OKDialog.showConfirmation
@ -57,7 +57,7 @@ abstract class PluginBase(pluginDesc: PluginDescription) {
SP.putBoolean("allow_hardware_pump", true)
if (isEnabled(L.PUMP)) log.debug("First time HW pump allowed!")
}, Runnable {
send(EventConfigBuilderUpdateGui())
RxBus.INSTANCE.send(EventConfigBuilderUpdateGui())
if (isEnabled(L.PUMP)) log.debug("User does not allow switching to HW pump!")
})
}
@ -71,9 +71,9 @@ abstract class PluginBase(pluginDesc: PluginDescription) {
setFragmentVisible(type, enabled)
ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, type)
ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled")
send(EventRebuildTabs())
send(EventConfigBuilderChange())
send(EventConfigBuilderUpdateGui())
RxBus.INSTANCE.send(EventRebuildTabs())
RxBus.INSTANCE.send(EventConfigBuilderChange())
RxBus.INSTANCE.send(EventConfigBuilderUpdateGui())
ConfigBuilderPlugin.getPlugin().logPluginStatus()
}
@ -93,8 +93,7 @@ abstract class PluginBase(pluginDesc: PluginDescription) {
val description: String?
get() = if (pluginDescription.description == -1) null else MainApp.gs(pluginDescription.description)
val type: PluginType
get() = pluginDescription.mainType
fun getType(): PluginType = pluginDescription.mainType
open val preferencesId: Int
get() = pluginDescription.preferencesId
@ -164,7 +163,7 @@ abstract class PluginBase(pluginDesc: PluginDescription) {
}
protected open fun onStart() {
if (type == PluginType.PUMP) {
if (getType() == PluginType.PUMP) {
Thread(Runnable {
SystemClock.sleep(3000)
val commandQueue = ConfigBuilderPlugin.getPlugin().commandQueue

View file

@ -4,6 +4,8 @@ import org.json.JSONObject;
import java.util.List;
import javax.annotation.Nullable;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
@ -89,6 +91,7 @@ public interface PumpInterface {
boolean canHandleDST();
@Nullable
List<CustomAction> getCustomActions();
void executeCustomAction(CustomActionType customActionType);

View file

@ -9,6 +9,7 @@ interface AAPSLogger {
fun debug(message: String)
fun debug(enable: Boolean, tag: LTag, message: String)
fun debug(tag: LTag, message: String)
fun warn(tag: LTag, message: String)
fun info(tag: LTag, message: String)
fun error(tag: LTag, message: String)
fun error(message: String)

View file

@ -20,6 +20,10 @@ class AAPSLoggerDebug : AAPSLogger {
Log.d(tag.tag, message)
}
override fun warn(tag: LTag, message: String) {
Log.w(tag.tag, message)
}
override fun info(tag: LTag, message: String) {
Log.i(tag.tag, message)
}

View file

@ -24,6 +24,12 @@ class AAPSLoggerProduction : AAPSLogger {
}
}
override fun warn(tag: LTag, message: String) {
if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).warn(message)
}
}
override fun info(tag: LTag, message: String) {
if (L.isEnabled(tag.tag)) {
LoggerFactory.getLogger(tag.tag).info(message)

View file

@ -38,7 +38,7 @@ class LoopFragment : Fragment() {
@Synchronized
override fun onResume() {
super.onResume()
disposable += RxBus
disposable += RxBus.INSTANCE
.toObservable(EventLoopUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -47,7 +47,7 @@ class LoopFragment : Fragment() {
FabricPrivacy.logException(it)
})
disposable += RxBus
disposable += RxBus.INSTANCE
.toObservable(EventLoopSetLastRunGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({

View file

@ -80,6 +80,7 @@ public class LoopPlugin extends PluginBase {
private static LoopPlugin loopPlugin;
@NonNull
@Deprecated
public static LoopPlugin getPlugin() {
if (loopPlugin == null) {
loopPlugin = new LoopPlugin();
@ -122,7 +123,7 @@ public class LoopPlugin extends PluginBase {
protected void onStart() {
createNotificationChannel();
super.onStart();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventTempTargetChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -136,7 +137,7 @@ public class LoopPlugin extends PluginBase {
* the event causing the calculation is not EventNewBg.
* <p>
*/
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventAutosensCalculationFinished.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -280,7 +281,7 @@ public class LoopPlugin extends PluginBase {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
if (L.isEnabled(L.APS))
log.debug(message);
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(message));
RxBus.Companion.getINSTANCE().send(new EventLoopSetLastRunGui(message));
return;
}
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
@ -294,7 +295,7 @@ public class LoopPlugin extends PluginBase {
if (profile == null || !ProfileFunctions.getInstance().isProfileValid("Loop")) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
RxBus.Companion.getINSTANCE().send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return;
}
@ -309,7 +310,7 @@ public class LoopPlugin extends PluginBase {
// Check if we have any result
if (result == null) {
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
RxBus.Companion.getINSTANCE().send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
return;
}
@ -351,14 +352,14 @@ public class LoopPlugin extends PluginBase {
if (isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.loopsuspended));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
RxBus.Companion.getINSTANCE().send(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.pumpsuspended));
RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
RxBus.Companion.getINSTANCE().send(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return;
}
@ -374,7 +375,7 @@ public class LoopPlugin extends PluginBase {
lastRun.tbrSetByPump = waiting;
if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting;
RxBus.INSTANCE.send(new EventLoopUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventLoopUpdateGui());
FabricPrivacy.getInstance().logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
@ -395,11 +396,11 @@ public class LoopPlugin extends PluginBase {
LoopPlugin.getPlugin().invoke("tempBasalFallback", allowNotification, true);
}).start();
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventLoopUpdateGui());
}
});
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventLoopUpdateGui());
}
});
} else {
@ -440,7 +441,7 @@ public class LoopPlugin extends PluginBase {
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
RxBus.INSTANCE.send(new EventNewOpenLoopNotification());
RxBus.Companion.getINSTANCE().send(new EventNewOpenLoopNotification());
// Send to Wear
ActionStringHandler.handleInitiate("changeRequest");
@ -453,7 +454,7 @@ public class LoopPlugin extends PluginBase {
}
}
RxBus.INSTANCE.send(new EventLoopUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventLoopUpdateGui());
} finally {
if (L.isEnabled(L.APS))
log.debug("invoke end");
@ -473,7 +474,7 @@ public class LoopPlugin extends PluginBase {
NSUpload.uploadDeviceStatus();
SP.incInt(R.string.key_ObjectivesmanualEnacts);
}
RxBus.INSTANCE.send(new EventAcceptOpenLoopChange());
RxBus.Companion.getINSTANCE().send(new EventAcceptOpenLoopChange());
}
});
FabricPrivacy.getInstance().logCustom("AcceptTemp");
@ -485,7 +486,7 @@ public class LoopPlugin extends PluginBase {
*/
public void applyTBRRequest(APSResult request, Profile profile, Callback callback) {
boolean allowPercentage = VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
boolean allowPercentage = VirtualPumpPlugin.Companion.getPlugin().isEnabled(PluginType.PUMP);
if (!request.tempBasalRequested) {
if (callback != null) {

View file

@ -12,7 +12,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
@ -27,11 +27,9 @@ import javax.inject.Inject
class OpenAPSAMAFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable()
@Inject
lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject
lateinit var aapsLogger: AAPSLogger
@Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
@ -50,7 +48,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
override fun onResume() {
super.onResume()
disposable += RxBus
disposable += rxBus
.toObservable(EventOpenAPSUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -58,7 +56,7 @@ class OpenAPSAMAFragment : DaggerFragment() {
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
disposable += rxBus
.toObservable(EventOpenAPSUpdateResultGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -90,7 +88,8 @@ class OpenAPSAMAFragment : DaggerFragment() {
val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam)
openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
aapsLogger.error(LTag.APS,"Unhandled exception", e)
aapsLogger.error(LTag.APS, "Unhandled exception", e)
@Suppress("SetTextI18n")
openapsma_iobdata.text = "JSONException see log for details"
}

View file

@ -94,25 +94,25 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.noprofileselected));
return;
}
if (pump == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.nopumpselected));
return;
}
if (!isEnabled(PluginType.APS)) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_noglucosedata));
return;
}
@ -165,7 +165,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
return;
}
lastAutosensResult = autosensData.autosensResult;
@ -215,7 +215,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
lastAPSResult = determineBasalResultAMA;
lastAPSRun = now;
}
RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}

View file

@ -6,10 +6,9 @@ import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
@ -17,14 +16,13 @@ import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.openapsama_fragment.*
import org.slf4j.LoggerFactory
import javax.inject.Inject
class OpenAPSMAFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable()
@Inject
lateinit var openAPSMAPlugin: OpenAPSMAPlugin
@Inject lateinit var openAPSMAPlugin: OpenAPSMAPlugin
@Inject lateinit var rxBus: RxBusWrapper
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
@ -44,7 +42,7 @@ class OpenAPSMAFragment : DaggerFragment() {
override fun onResume() {
super.onResume()
disposable += RxBus
disposable += rxBus
.toObservable(EventOpenAPSUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -52,7 +50,7 @@ class OpenAPSMAFragment : DaggerFragment() {
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
disposable += rxBus
.toObservable(EventOpenAPSUpdateResultGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({

View file

@ -93,25 +93,25 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.noprofileselected));
return;
}
if (pump == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.nopumpselected));
return;
}
if (!isEnabled(PluginType.APS)) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_noglucosedata));
return;
}
@ -195,7 +195,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
lastAPSResult = determineBasalResultMA;
lastAPSRun = now;
}
RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateGui());
}

View file

@ -13,7 +13,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
@ -28,11 +28,9 @@ import javax.inject.Inject
class OpenAPSSMBFragment : DaggerFragment() {
private var disposable: CompositeDisposable = CompositeDisposable()
@Inject
lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@Inject
lateinit var aapsLogger: AAPSLogger
@Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rxBus: RxBusWrapper
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
@ -50,7 +48,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
@Synchronized
override fun onResume() {
super.onResume()
disposable += RxBus
disposable += rxBus
.toObservable(EventOpenAPSUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -58,7 +56,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
disposable += rxBus
.toObservable(EventOpenAPSUpdateResultGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
@ -91,7 +89,7 @@ class OpenAPSSMBFragment : DaggerFragment() {
openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
aapsLogger.error(LTag.APS, "Unhandled exception", e)
@SuppressLint("SetTextl18n")
@SuppressLint("SetTextI18n")
openapsma_iobdata.text = "JSONException see log for details"
}

View file

@ -112,25 +112,25 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.noprofileselected));
return;
}
if (pump == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.nopumpselected)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.nopumpselected));
return;
}
if (!isEnabled(PluginType.APS)) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
aapsLogger.debug(LTag.APS, MainApp.gs(R.string.openapsma_noglucosedata));
return;
}
@ -186,7 +186,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
if (ConstraintChecker.getInstance().isAutosensModeEnabled().value()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) {
RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
return;
}
lastAutosensResult = autosensData.autosensResult;
@ -257,7 +257,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
lastAPSResult = determineBasalResultSMB;
lastAPSRun = now;
}
RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}

View file

@ -5,8 +5,13 @@ import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
// Use object so we have a singleton instance
object RxBus {
class RxBus {
companion object {
@JvmStatic
@Deprecated("Get via Dagger. Will be removed once fully transitioned to Dagger")
var INSTANCE: RxBus = RxBus()//TODO: remove as soon as Dagger is fully set up
}
private val publisher = PublishSubject.create<Event>()

View file

@ -0,0 +1,21 @@
package info.nightscout.androidaps.plugins.bus
import info.nightscout.androidaps.events.Event
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class RxBusWrapper @Inject constructor() {
private val bus: RxBus = RxBus.INSTANCE
fun send(event: Event) {
bus.send(event)
}
// Listen should return an Observable and not the publisher
// Using ofType we filter only events that match that class type
fun <T> toObservable(eventType: Class<T>): Observable<T> =
bus.toObservable(eventType)
}

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.configBuilder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
@ -8,19 +7,22 @@ import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.PasswordProtection
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.configbuilder_fragment.*
import java.util.*
import javax.inject.Inject
class ConfigBuilderFragment : Fragment() {
class ConfigBuilderFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBusWrapper
private var disposable: CompositeDisposable = CompositeDisposable()
private val pluginViewHolders = ArrayList<PluginViewHolder>()
@ -49,14 +51,14 @@ class ConfigBuilderFragment : Fragment() {
@Synchronized
override fun onResume() {
super.onResume()
disposable.add(RxBus
.toObservable(EventConfigBuilderUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
for (pluginViewHolder in pluginViewHolders) pluginViewHolder.update()
}, {
FabricPrivacy.logException(it)
}))
disposable += rxBus
.toObservable(EventConfigBuilderUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
for (pluginViewHolder in pluginViewHolders) pluginViewHolder.update()
}, {
FabricPrivacy.logException(it)
})
updateGUI()
}

View file

@ -25,13 +25,14 @@ import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
* Created by mike on 05.08.2016.
@ -40,6 +41,8 @@ import info.nightscout.androidaps.utils.SP;
public class ConfigBuilderPlugin extends PluginBase {
private static ConfigBuilderPlugin configBuilderPlugin;
private final AAPSLogger aapsLogger; // TODO move to plugin base
private final SP sp;
private final RxBusWrapper rxBus;
/**
@ -63,10 +66,10 @@ public class ConfigBuilderPlugin extends PluginBase {
private CommandQueue commandQueue = new CommandQueue();
private Lazy<InsulinOrefRapidActingPlugin> insulinOrefRapidActingPlugin;
//TODO: inject
LocalProfilePlugin localProfilePlugin = LocalProfilePlugin.INSTANCE;
private final Lazy<MainApp> mainApp;
private final Lazy<InsulinOrefRapidActingPlugin> insulinOrefRapidActingPlugin;
private final Lazy<LocalProfilePlugin> localProfilePlugin;
private final Lazy<VirtualPumpPlugin> virtualPumpPlugin;
/*
* Written by Adrian:
@ -77,8 +80,13 @@ public class ConfigBuilderPlugin extends PluginBase {
* */
@Inject
public ConfigBuilderPlugin(
Lazy<MainApp> mainApp,
Lazy<InsulinOrefRapidActingPlugin> insulinOrefRapidActingPlugin,
AAPSLogger aapsLogger
Lazy<LocalProfilePlugin> localProfilePlugin,
Lazy<VirtualPumpPlugin> virtualPumpPlugin,
AAPSLogger aapsLogger,
SP sp,
RxBusWrapper rxBus
) {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
@ -90,28 +98,22 @@ public class ConfigBuilderPlugin extends PluginBase {
.shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder)
);
this.mainApp = mainApp;
this.insulinOrefRapidActingPlugin = insulinOrefRapidActingPlugin;
this.localProfilePlugin = localProfilePlugin;
this.virtualPumpPlugin = virtualPumpPlugin;
this.aapsLogger = aapsLogger;
this.sp = sp;
this.rxBus =rxBus;
configBuilderPlugin = this; // TODO: only while transitioning to Dagger
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onStop() {
super.onStop();
}
public void initialize() {
pluginList = MainApp.getPluginsList();
upgradeSettings();
loadSettings();
setAlwaysEnabledPluginsEnabled();
RxBus.INSTANCE.send(new EventAppInitialized());
RxBus.Companion.getINSTANCE().send(new EventAppInitialized());
}
private void setAlwaysEnabledPluginsEnabled() {
@ -146,11 +148,11 @@ public class ConfigBuilderPlugin extends PluginBase {
private void savePref(PluginBase p, PluginType type, boolean storeVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
SP.putBoolean(settingEnabled, p.isEnabled(type));
sp.putBoolean(settingEnabled, p.isEnabled(type));
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingEnabled + ":" + p.isEnabled(type));
if (storeVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
SP.putBoolean(settingVisible, p.isFragmentVisible());
sp.putBoolean(settingVisible, p.isFragmentVisible());
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing: " + settingVisible + ":" + p.isFragmentVisible());
}
}
@ -171,16 +173,16 @@ public class ConfigBuilderPlugin extends PluginBase {
private void loadPref(PluginBase p, PluginType type, boolean loadVisible) {
String settingEnabled = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Enabled";
if (SP.contains(settingEnabled))
p.setPluginEnabled(type, SP.getBoolean(settingEnabled, false));
if (sp.contains(settingEnabled))
p.setPluginEnabled(type, sp.getBoolean(settingEnabled, false));
else if (p.getType() == type && (p.pluginDescription.enableByDefault || p.pluginDescription.alwaysEnabled)) {
p.setPluginEnabled(type, true);
}
aapsLogger.debug(LTag.CONFIGBUILDER, "Loaded: " + settingEnabled + ":" + p.isEnabled(type));
if (loadVisible) {
String settingVisible = "ConfigBuilder_" + type.name() + "_" + p.getClass().getSimpleName() + "_Visible";
if (SP.contains(settingVisible))
p.setFragmentVisible(type, SP.getBoolean(settingVisible, false) && SP.getBoolean(settingEnabled, false));
if (sp.contains(settingVisible))
p.setFragmentVisible(type, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
else if (p.getType() == type && p.pluginDescription.visibleByDefault) {
p.setFragmentVisible(type, true);
}
@ -190,7 +192,7 @@ public class ConfigBuilderPlugin extends PluginBase {
// Detect settings prior 1.60
private void upgradeSettings() {
if (!SP.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
if (!sp.contains("ConfigBuilder_1_NSProfilePlugin_Enabled"))
return;
aapsLogger.debug(LTag.CONFIGBUILDER, "Upgrading stored settings");
for (PluginBase p : pluginList) {
@ -234,12 +236,12 @@ public class ConfigBuilderPlugin extends PluginBase {
}
String settingEnabled = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Enabled";
String settingVisible = "ConfigBuilder_" + type + "_" + p.getClass().getSimpleName() + "_Visible";
if (SP.contains(settingEnabled))
p.setPluginEnabled(newType, SP.getBoolean(settingEnabled, false));
if (SP.contains(settingVisible))
p.setFragmentVisible(newType, SP.getBoolean(settingVisible, false) && SP.getBoolean(settingEnabled, false));
SP.remove(settingEnabled);
SP.remove(settingVisible);
if (sp.contains(settingEnabled))
p.setPluginEnabled(newType, sp.getBoolean(settingEnabled, false));
if (sp.contains(settingVisible))
p.setFragmentVisible(newType, sp.getBoolean(settingVisible, false) && sp.getBoolean(settingEnabled, false));
sp.remove(settingEnabled);
sp.remove(settingVisible);
if (newType == p.getType()) {
savePref(p, newType, true);
} else if (p.getType() == PluginType.PUMP && p instanceof ProfileInterface) {
@ -261,7 +263,7 @@ public class ConfigBuilderPlugin extends PluginBase {
@NotNull
public ProfileInterface getActiveProfileInterface() {
if (activeProfile != null) return activeProfile;
else return localProfilePlugin;
else return localProfilePlugin.get();
}
@Nullable
@ -337,8 +339,8 @@ public class ConfigBuilderPlugin extends PluginBase {
pluginsInCategory = MainApp.getSpecificPluginsList(PluginType.PUMP);
activePump = (PumpInterface) getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP);
if (activePump == null) {
activePump = VirtualPumpPlugin.getPlugin();
VirtualPumpPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
activePump = virtualPumpPlugin.get();
virtualPumpPlugin.get().setPluginEnabled(PluginType.PUMP, true);
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting VirtualPumpPlugin");
}
this.setFragmentVisiblities(((PluginBase) activePump).getName(), pluginsInCategory, PluginType.PUMP);
@ -464,7 +466,7 @@ public class ConfigBuilderPlugin extends PluginBase {
}
} else { // enable first plugin in list
if (type == PluginType.PUMP)
VirtualPumpPlugin.getPlugin().setPluginEnabled(type, true);
VirtualPumpPlugin.Companion.getPlugin().setPluginEnabled(type, true);
else if (type == PluginType.INSULIN)
insulinOrefRapidActingPlugin.get().setPluginEnabled(type, true);
else if (type == PluginType.SENSITIVITY)

View file

@ -39,7 +39,7 @@ class PluginViewHolder internal constructor(private val fragment: ConfigBuilderF
pluginVisibility.setOnClickListener {
plugin.setFragmentVisible(pluginType, pluginVisibility.isChecked)
ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxVisible")
RxBus.send(EventRebuildTabs())
RxBus.INSTANCE.send(EventRebuildTabs())
ConfigBuilderPlugin.getPlugin().logPluginStatus()
}

View file

@ -8,10 +8,14 @@ import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.security.spec.InvalidParameterSpecException
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFunction {
class ProfileFunctionImplementation @Inject constructor(
private val sp: SP,
private val configBuilderPlugin: ConfigBuilderPlugin
) : ProfileFunction {
override fun getProfileName(): String =
getProfileName(System.currentTimeMillis(), customized = true, showRemainingTime = false)
@ -46,7 +50,7 @@ class ProfileFunctionImplementation constructor(private val sp: SP) : ProfileFun
profileSwitch.source = Source.USER
profileSwitch.profileName = profileName
profileSwitch.profileJson = profile.data.toString()
profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().activeProfileInterface::class.java.name
profileSwitch.profilePlugin = configBuilderPlugin.activeProfileInterface::class.java.name
profileSwitch.durationInMinutes = duration
profileSwitch.isCPP = percentage != 100 || timeShift != 0
profileSwitch.timeshift = timeShift

View file

@ -40,6 +40,7 @@ public class ProfileFunctions implements ProfileFunction {
private static ProfileFunctions profileFunctions = null;
@Deprecated
public static ProfileFunctions getInstance() {
if (profileFunctions == null)
profileFunctions = new ProfileFunctions();
@ -51,7 +52,7 @@ public class ProfileFunctions implements ProfileFunction {
}
private ProfileFunctions() {
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventProfileNeedsUpdate.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -69,7 +70,7 @@ public class ProfileFunctions implements ProfileFunction {
MainApp.instance().startActivity(i);
}
if (result.enacted)
RxBus.INSTANCE.send(new EventNewBasalProfile());
RxBus.Companion.getINSTANCE().send(new EventNewBasalProfile());
}
});
}, FabricPrivacy::logException)

View file

@ -27,6 +27,7 @@ public class DstHelperPlugin extends PluginBase implements ConstraintsInterface
static DstHelperPlugin plugin = null;
@Deprecated
public static DstHelperPlugin getPlugin() {
if (plugin == null)
plugin = new DstHelperPlugin();
@ -90,6 +91,6 @@ public class DstHelperPlugin extends PluginBase implements ConstraintsInterface
private void warnUser(int id, String warningText) {
Notification notification = new Notification(id, warningText, Notification.LOW);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
}
}

View file

@ -14,14 +14,13 @@ import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.MainApp
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus
@ -30,13 +29,20 @@ import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Obje
import info.nightscout.androidaps.receivers.NetworkChangeReceiver
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate
import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.objectives_fragment.*
import org.slf4j.LoggerFactory
import javax.inject.Inject
class ObjectivesFragment : DaggerFragment() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var sp: SP
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var objectivesPlugin: ObjectivesPlugin
class ObjectivesFragment : Fragment() {
private val log = LoggerFactory.getLogger(L.CONSTRAINTS)
private val objectivesAdapter = ObjectivesAdapter()
private val handler = Handler(Looper.getMainLooper())
@ -60,7 +66,7 @@ class ObjectivesFragment : Fragment() {
objectives_recyclerview.adapter = objectivesAdapter
objectives_fake.setOnClickListener { updateGUI() }
objectives_reset.setOnClickListener {
ObjectivesPlugin.reset()
objectivesPlugin.reset()
objectives_recyclerview.adapter?.notifyDataSetChanged()
scrollToCurrentObjective()
}
@ -71,15 +77,15 @@ class ObjectivesFragment : Fragment() {
@Synchronized
override fun onResume() {
super.onResume()
disposable.add(RxBus
disposable += rxBus
.toObservable(EventObjectivesUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
objectives_recyclerview.adapter?.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
})
)
}
)
}
@Synchronized
@ -96,7 +102,7 @@ class ObjectivesFragment : Fragment() {
private fun startUpdateTimer() {
handler.removeCallbacks(objectiveUpdater)
for (objective in ObjectivesPlugin.objectives) {
for (objective in objectivesPlugin.objectives) {
if (objective.isStarted && !objective.isAccomplished) {
val timeTillNextMinute = (System.currentTimeMillis() - objective.startedOn) % (60 * 1000)
handler.postDelayed(objectiveUpdater, timeTillNextMinute)
@ -107,8 +113,8 @@ class ObjectivesFragment : Fragment() {
private fun scrollToCurrentObjective() {
activity?.runOnUiThread {
for (i in 0 until ObjectivesPlugin.objectives.size) {
val objective = ObjectivesPlugin.objectives[i]
for (i in 0 until objectivesPlugin.objectives.size) {
val objective = objectivesPlugin.objectives[i]
if (!objective.isStarted || !objective.isAccomplished) {
context?.let {
val smoothScroller = object : LinearSmoothScroller(it) {
@ -131,16 +137,16 @@ class ObjectivesFragment : Fragment() {
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val objective = ObjectivesPlugin.objectives[position]
holder.title.text = MainApp.gs(R.string.nth_objective, position + 1)
val objective = objectivesPlugin.objectives[position]
holder.title.text = resourceHelper.gs(R.string.nth_objective, position + 1)
if (objective.objective != 0) {
holder.objective.visibility = View.VISIBLE
holder.objective.text = MainApp.gs(objective.objective)
holder.objective.text = resourceHelper.gs(objective.objective)
} else
holder.objective.visibility = View.GONE
if (objective.gate != 0) {
holder.gate.visibility = View.VISIBLE
holder.gate.text = MainApp.gs(objective.gate)
holder.gate.text = resourceHelper.gs(objective.gate)
} else
holder.gate.visibility = View.GONE
if (!objective.isStarted) {
@ -150,7 +156,7 @@ class ObjectivesFragment : Fragment() {
holder.accomplished.visibility = View.GONE
holder.unFinish.visibility = View.GONE
holder.unStart.visibility = View.GONE
if (position == 0 || ObjectivesPlugin.objectives[position - 1].isAccomplished)
if (position == 0 || objectivesPlugin.objectives[position - 1].isAccomplished)
holder.start.visibility = View.VISIBLE
else
holder.start.visibility = View.GONE
@ -176,7 +182,8 @@ class ObjectivesFragment : Fragment() {
if (task.shouldBeIgnored()) continue
// name
val name = TextView(holder.progress.context)
name.text = MainApp.gs(task.task) + ":"
@Suppress("SetTextlI8n")
name.text = resourceHelper.gs(task.task) + ":"
name.setTextColor(-0x1)
holder.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
// hint
@ -209,7 +216,7 @@ class ObjectivesFragment : Fragment() {
holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2)
}
}
holder.accomplished.text = MainApp.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn))
holder.accomplished.text = resourceHelper.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn))
holder.accomplished.setTextColor(-0x3e3e3f)
holder.verify.setOnClickListener {
NetworkChangeReceiver.grabNetworkStatus(context)
@ -217,33 +224,33 @@ class ObjectivesFragment : Fragment() {
objective.accomplishedOn = DateUtil.now()
scrollToCurrentObjective()
startUpdateTimer()
RxBus.send(EventObjectivesUpdateGui())
RxBus.send(EventSWUpdate(false))
rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false))
} else {
// move out of UI thread
Thread {
NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck")
RxBus.send(EventNtpStatus(MainApp.gs(R.string.timedetection), 0))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0))
SntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() {
log.debug("NTP time: $time System time: ${DateUtil.now()}")
aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}")
SystemClock.sleep(300)
if (!networkConnected) {
RxBus.send(EventNtpStatus(MainApp.gs(R.string.notconnected), 99))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99))
} else if (success) {
if (objective.isCompleted(time)) {
objective.accomplishedOn = time
RxBus.send(EventNtpStatus(MainApp.gs(R.string.success), 100))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.success), 100))
SystemClock.sleep(1000)
RxBus.send(EventObjectivesUpdateGui())
RxBus.send(EventSWUpdate(false))
rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false))
SystemClock.sleep(100)
scrollToCurrentObjective()
} else {
RxBus.send(EventNtpStatus(MainApp.gs(R.string.requirementnotmet), 99))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.requirementnotmet), 99))
}
} else {
RxBus.send(EventNtpStatus(MainApp.gs(R.string.failedretrievetime), 99))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99))
}
}
}, NetworkChangeReceiver.isConnected())
@ -256,29 +263,29 @@ class ObjectivesFragment : Fragment() {
objective.startedOn = DateUtil.now()
scrollToCurrentObjective()
startUpdateTimer()
RxBus.send(EventObjectivesUpdateGui())
RxBus.send(EventSWUpdate(false))
rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false))
} else
// move out of UI thread
Thread {
NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck")
RxBus.send(EventNtpStatus(MainApp.gs(R.string.timedetection), 0))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0))
SntpClient.ntpTime(object : SntpClient.Callback() {
override fun run() {
log.debug("NTP time: $time System time: ${DateUtil.now()}")
aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}")
SystemClock.sleep(300)
if (!networkConnected) {
RxBus.send(EventNtpStatus(MainApp.gs(R.string.notconnected), 99))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.notconnected), 99))
} else if (success) {
objective.startedOn = time
RxBus.send(EventNtpStatus(MainApp.gs(R.string.success), 100))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.success), 100))
SystemClock.sleep(1000)
RxBus.send(EventObjectivesUpdateGui())
RxBus.send(EventSWUpdate(false))
rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false))
SystemClock.sleep(100)
scrollToCurrentObjective()
} else {
RxBus.send(EventNtpStatus(MainApp.gs(R.string.failedretrievetime), 99))
rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.failedretrievetime), 99))
}
}
}, NetworkChangeReceiver.isConnected())
@ -286,25 +293,25 @@ class ObjectivesFragment : Fragment() {
}
holder.unStart.setOnClickListener {
activity?.let { activity ->
OKDialog.showConfirmation(activity, MainApp.gs(R.string.objectives), MainApp.gs(R.string.doyouwantresetstart), Runnable {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.doyouwantresetstart), Runnable {
objective.startedOn = 0
scrollToCurrentObjective()
RxBus.send(EventObjectivesUpdateGui())
RxBus.send(EventSWUpdate(false))
rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false))
})
}
}
holder.unFinish.setOnClickListener {
objective.accomplishedOn = 0
scrollToCurrentObjective()
RxBus.send(EventObjectivesUpdateGui())
RxBus.send(EventSWUpdate(false))
rxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventSWUpdate(false))
}
if (objective.hasSpecialInput && !objective.isAccomplished && objective.isStarted && objective.specialActionEnabled()) {
// generate random request code if none exists
val request = SP.getString(R.string.key_objectives_request_code, String.format("%1$05d", (Math.random() * 99999).toInt()))
SP.putString(R.string.key_objectives_request_code, request)
holder.requestCode.text = MainApp.gs(R.string.requestcode, request)
val request = sp.getString(R.string.key_objectives_request_code, String.format("%1$05d", (Math.random() * 99999).toInt()))
sp.putString(R.string.key_objectives_request_code, request)
holder.requestCode.text = resourceHelper.gs(R.string.requestcode, request)
holder.requestCode.visibility = View.VISIBLE
holder.enterButton.visibility = View.VISIBLE
holder.input.visibility = View.VISIBLE
@ -312,7 +319,7 @@ class ObjectivesFragment : Fragment() {
holder.enterButton.setOnClickListener {
val input = holder.input.text.toString()
objective.specialAction(activity, input)
RxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventObjectivesUpdateGui())
}
} else {
holder.enterButton.visibility = View.GONE
@ -323,7 +330,7 @@ class ObjectivesFragment : Fragment() {
}
override fun getItemCount(): Int {
return ObjectivesPlugin.objectives.size
return objectivesPlugin.objectives.size
}
inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {

View file

@ -5,27 +5,35 @@ import com.google.common.base.Charsets
import com.google.common.hash.Hashing
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.*
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by mike on 05.08.2016.
*/
object ObjectivesPlugin : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.fragmentClass(ObjectivesFragment::class.qualifiedName)
.alwaysEnabled(Config.APS)
.showInList(Config.APS)
.pluginName(R.string.objectives)
.shortName(R.string.objectives_shortname)
.description(R.string.description_objectives)), ConstraintsInterface {
@Singleton
class ObjectivesPlugin @Inject constructor(
private val sp: SP,
private val resourceHelper: ResourceHelper,
private val configBuilderPlugin: ConfigBuilderPlugin
) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.fragmentClass(ObjectivesFragment::class.qualifiedName)
.alwaysEnabled(Config.APS)
.showInList(Config.APS)
.pluginName(R.string.objectives)
.shortName(R.string.objectives_shortname)
.description(R.string.description_objectives)), ConstraintsInterface {
var objectives: MutableList<Objective> = ArrayList()
@ -40,13 +48,14 @@ object ObjectivesPlugin : PluginBase(PluginDescription()
val AMA_OBJECTIVE = 8
val SMB_OBJECTIVE = 9
init {
override fun onStart() {
super.onStart()
convertSP()
setupObjectives()
}
override fun specialEnableCondition(): Boolean {
val pump = ConfigBuilderPlugin.getPlugin().activePump
val pump = configBuilderPlugin.activePump
return pump == null || pump.pumpDescription.isTempBasalCapable
}
@ -63,9 +72,9 @@ object ObjectivesPlugin : PluginBase(PluginDescription()
}
private fun doConvertSP(number: Int, name: String) {
if (!SP.contains("Objectives_" + name + "_started")) {
SP.putLong("Objectives_" + name + "_started", SP.getLong("Objectives" + number + "started", 0L))
SP.putLong("Objectives_" + name + "_accomplished", SP.getLong("Objectives" + number + "accomplished", 0L))
if (!sp.contains("Objectives_" + name + "_started")) {
sp.putLong("Objectives_" + name + "_started", sp.getLong("Objectives" + number + "started", 0L))
sp.putLong("Objectives_" + name + "_accomplished", sp.getLong("Objectives" + number + "accomplished", 0L))
}
// TODO: we can remove Objectives1accomplished sometimes later
}
@ -89,42 +98,42 @@ object ObjectivesPlugin : PluginBase(PluginDescription()
objective.startedOn = 0
objective.accomplishedOn = 0
}
SP.putBoolean(R.string.key_ObjectivesbgIsAvailableInNS, false)
SP.putBoolean(R.string.key_ObjectivespumpStatusIsAvailableInNS, false)
SP.putInt(R.string.key_ObjectivesmanualEnacts, 0)
SP.putBoolean(R.string.key_objectiveuseprofileswitch, false)
SP.putBoolean(R.string.key_objectiveusedisconnect, false)
SP.putBoolean(R.string.key_objectiveusereconnect, false)
SP.putBoolean(R.string.key_objectiveusetemptarget, false)
SP.putBoolean(R.string.key_objectiveuseactions, false)
SP.putBoolean(R.string.key_objectiveuseloop, false)
SP.putBoolean(R.string.key_objectiveusescale, false)
sp.putBoolean(R.string.key_ObjectivesbgIsAvailableInNS, false)
sp.putBoolean(R.string.key_ObjectivespumpStatusIsAvailableInNS, false)
sp.putInt(R.string.key_ObjectivesmanualEnacts, 0)
sp.putBoolean(R.string.key_objectiveuseprofileswitch, false)
sp.putBoolean(R.string.key_objectiveusedisconnect, false)
sp.putBoolean(R.string.key_objectiveusereconnect, false)
sp.putBoolean(R.string.key_objectiveusetemptarget, false)
sp.putBoolean(R.string.key_objectiveuseactions, false)
sp.putBoolean(R.string.key_objectiveuseloop, false)
sp.putBoolean(R.string.key_objectiveusescale, false)
}
fun completeObjectives(activity: Activity, request: String) {
val requestCode = SP.getString(R.string.key_objectives_request_code, "")
var url = SP.getString(R.string.key_nsclientinternal_url, "").toLowerCase()
val requestCode = sp.getString(R.string.key_objectives_request_code, "")
var url = sp.getString(R.string.key_nsclientinternal_url, "").toLowerCase()
if (!url.endsWith("/")) url = "$url/"
@Suppress("DEPRECATION") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString()
if (request.equals(hashNS.substring(0, 10), ignoreCase = true)) {
SP.putLong("Objectives_" + "openloop" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "openloop" + "_accomplished", DateUtil.now())
SP.putLong("Objectives_" + "maxbasal" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "maxbasal" + "_accomplished", DateUtil.now())
SP.putLong("Objectives_" + "maxiobzero" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "maxiobzero" + "_accomplished", DateUtil.now())
SP.putLong("Objectives_" + "maxiob" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "maxiob" + "_accomplished", DateUtil.now())
SP.putLong("Objectives_" + "autosens" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "autosens" + "_accomplished", DateUtil.now())
SP.putLong("Objectives_" + "ama" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "ama" + "_accomplished", DateUtil.now())
SP.putLong("Objectives_" + "smb" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "smb" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "openloop" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "openloop" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "maxbasal" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "maxbasal" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "maxiobzero" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "maxiobzero" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "maxiob" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "maxiob" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "autosens" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "autosens" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "ama" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "ama" + "_accomplished", DateUtil.now())
sp.putLong("Objectives_" + "smb" + "_started", DateUtil.now())
sp.putLong("Objectives_" + "smb" + "_accomplished", DateUtil.now())
setupObjectives()
OKDialog.show(activity, MainApp.gs(R.string.objectives), MainApp.gs(R.string.codeaccepted))
OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeaccepted))
} else {
OKDialog.show(activity, MainApp.gs(R.string.objectives), MainApp.gs(R.string.codeinvalid))
OKDialog.show(activity, resourceHelper.gs(R.string.objectives), resourceHelper.gs(R.string.codeinvalid))
}
}
@ -133,37 +142,37 @@ object ObjectivesPlugin : PluginBase(PluginDescription()
*/
override fun isLoopInvocationAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[FIRST_OBJECTIVE].isStarted)
value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), FIRST_OBJECTIVE + 1), this)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, FIRST_OBJECTIVE + 1), this)
return value
}
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted)
value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
return value
}
override fun isAutosensModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[AUTOSENS_OBJECTIVE].isStarted)
value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), AUTOSENS_OBJECTIVE + 1), this)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, AUTOSENS_OBJECTIVE + 1), this)
return value
}
override fun isAMAModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[AMA_OBJECTIVE].isStarted)
value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), AMA_OBJECTIVE + 1), this)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, AMA_OBJECTIVE + 1), this)
return value
}
override fun isSMBModeEnabled(value: Constraint<Boolean>): Constraint<Boolean> {
if (!objectives[SMB_OBJECTIVE].isStarted)
value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), SMB_OBJECTIVE + 1), this)
value.set(false, resourceHelper.gs(R.string.objectivenotstarted, SMB_OBJECTIVE + 1), this)
return value
}
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> {
if (objectives[MAXIOB_ZERO_CL_OBJECTIVE].isStarted && !objectives[MAXIOB_ZERO_CL_OBJECTIVE].isAccomplished)
maxIob.set(0.0, String.format(MainApp.gs(R.string.objectivenotfinished), MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
maxIob.set(0.0, resourceHelper.gs(R.string.objectivenotfinished, MAXIOB_ZERO_CL_OBJECTIVE + 1), this)
return maxIob
}

View file

@ -4,25 +4,28 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.*
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.Option
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import kotlinx.android.synthetic.main.objectives_exam_fragment.*
import javax.inject.Inject
class ObjectivesExamDialog : DaggerDialogFragment() {
@Inject lateinit var rxBus: RxBusWrapper
class ObjectivesExamDialog : DialogFragment() {
companion object {
var objective: Objective? = null
}
var currentTask = 0
private var currentTask = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
@ -37,7 +40,7 @@ class ObjectivesExamDialog : DialogFragment() {
override fun onStart() {
super.onStart()
dialog?.setCanceledOnTouchOutside(false)
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onResume() {
@ -79,23 +82,23 @@ class ObjectivesExamDialog : DialogFragment() {
objectives_exam_verify.setOnClickListener {
var result = true
for (o in task.options) {
val option: Option = o as Option;
val option: Option = o as Option
result = result && option.evaluate()
}
task.setAnswered(result);
task.answered = result
if (!result) {
task.disabledTo = DateUtil.now() + T.hours(1).msecs()
ToastUtils.showToastInUiThread(context, R.string.wronganswer)
} else task.disabledTo = 0
updateGui()
RxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventObjectivesUpdateGui())
}
close.setOnClickListener { dismiss() }
objectives_exam_reset.setOnClickListener {
task.answered = false
//task.disabledTo = 0
updateGui()
RxBus.send(EventObjectivesUpdateGui())
rxBus.send(EventObjectivesUpdateGui())
}
objectives_back_button.isEnabled = currentTask != 0
objectives_back_button.setOnClickListener {
@ -110,7 +113,7 @@ class ObjectivesExamDialog : DialogFragment() {
objectives_next_unanswered_button.isEnabled = !objective.isCompleted
objectives_next_unanswered_button.setOnClickListener {
for (i in (currentTask + 1)..(objective.tasks.size - 1)) {
for (i in (currentTask + 1) until objective.tasks.size) {
if (!objective.tasks[i].isCompleted) {
currentTask = i
updateGui()

View file

@ -5,32 +5,35 @@ import android.os.SystemClock
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import info.nightscout.androidaps.MainApp
import dagger.android.support.DaggerDialogFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus.toObservable
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.dialog_bolusprogress.*
import org.slf4j.LoggerFactory
import javax.inject.Inject
class NtpProgressDialog : DaggerDialogFragment() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var resourceHelper: ResourceHelper
class NtpProgressDialog : DialogFragment() {
private val log = LoggerFactory.getLogger(L.UI)
private val disposable = CompositeDisposable()
private val DEFAULT_STATE = MainApp.gs(R.string.timedetection)
private var state: String = DEFAULT_STATE
private var state: String? = null
private var percent = 0
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
dialog?.setTitle(String.format(MainApp.gs(R.string.objectives)))
isCancelable = false
state = savedInstanceState?.getString("state", DEFAULT_STATE) ?: DEFAULT_STATE
state = savedInstanceState?.getString("state", null)
percent = savedInstanceState?.getInt("percent", 0) ?: 0
return inflater.inflate(R.layout.dialog_bolusprogress, container, false)
@ -38,41 +41,43 @@ class NtpProgressDialog : DialogFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val defaultMessage = resourceHelper.gs(R.string.timedetection)
dialog?.setTitle(resourceHelper.gs(R.string.objectives))
overview_bolusprogress_stop.setOnClickListener { dismiss() }
overview_bolusprogress_status.text = state
overview_bolusprogress_status.text = state ?: defaultMessage
overview_bolusprogress_progressbar.max = 100
overview_bolusprogress_progressbar.progress = percent
overview_bolusprogress_stop.text = MainApp.gs(R.string.close)
overview_bolusprogress_title.text = MainApp.gs(R.string.please_wait)
overview_bolusprogress_stop.text = resourceHelper.gs(R.string.close)
overview_bolusprogress_title.text = resourceHelper.gs(R.string.please_wait)
}
override fun onResume() {
super.onResume()
if (L.isEnabled(L.UI)) log.debug("onResume")
aapsLogger.debug(LTag.UI, "onResume")
if (percent == 100) {
dismiss()
return
} else
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
disposable.add(toObservable(EventNtpStatus::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ event: EventNtpStatus ->
if (L.isEnabled(L.UI)) log.debug("Status: " + event.status + " Percent: " + event.percent)
overview_bolusprogress_status?.text = event.status
overview_bolusprogress_progressbar?.progress = event.percent
if (event.percent == 100) {
SystemClock.sleep(100)
dismiss()
}
state = event.status
percent = event.percent
}) { FabricPrivacy.logException(it) }
)
disposable += rxBus
.toObservable(EventNtpStatus::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ event: EventNtpStatus ->
aapsLogger.debug(LTag.UI, "Status: " + event.status + " Percent: " + event.percent)
overview_bolusprogress_status?.text = event.status
overview_bolusprogress_progressbar?.progress = event.percent
if (event.percent == 100) {
SystemClock.sleep(100)
dismiss()
}
state = event.status
percent = event.percent
}) { FabricPrivacy.logException(it) }
}
override fun onPause() {
if (L.isEnabled(L.UI)) log.debug("onPause")
aapsLogger.debug(LTag.UI, "onPause")
super.onPause()
disposable.clear()
}

View file

@ -2,24 +2,31 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class Objective0 extends Objective {
@Inject SP sp;
@Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject VirtualPumpPlugin virtualPumpPlugin;
@Inject TreatmentsPlugin treatmentsPlugin;
public Objective0() {
super("config", R.string.objectives_0_objective, R.string.objectives_0_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
}
@Override
@ -27,7 +34,7 @@ public class Objective0 extends Objective {
tasks.add(new Task(R.string.objectives_bgavailableinns) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_ObjectivesbgIsAvailableInNS, false);
return sp.getBoolean(R.string.key_ObjectivesbgIsAvailableInNS, false);
}
});
tasks.add(new Task(R.string.nsclienthaswritepermission) {
@ -39,18 +46,18 @@ public class Objective0 extends Objective {
tasks.add(new Task(R.string.virtualpump_uploadstatus_title) {
@Override
public boolean isCompleted() {
return SP.getBoolean("virtualpump_uploadstatus", false);
return sp.getBoolean("virtualpump_uploadstatus", false);
}
@Override
public boolean shouldBeIgnored() {
return !VirtualPumpPlugin.getPlugin().isEnabled(PluginType.PUMP);
return !virtualPumpPlugin.isEnabled(PluginType.PUMP);
}
});
tasks.add(new Task(R.string.objectives_pumpstatusavailableinns) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_ObjectivespumpStatusIsAvailableInNS, false);
return sp.getBoolean(R.string.key_ObjectivespumpStatusIsAvailableInNS, false);
}
});
tasks.add(new Task(R.string.hasbgdata) {
@ -68,7 +75,7 @@ public class Objective0 extends Objective {
tasks.add(new Task(R.string.apsselected) {
@Override
public boolean isCompleted() {
APSInterface usedAPS = ConfigBuilderPlugin.getPlugin().getActiveAPS();
APSInterface usedAPS = configBuilderPlugin.getActiveAPS();
if (usedAPS != null && ((PluginBase) usedAPS).isEnabled(PluginType.APS))
return true;
return false;
@ -77,7 +84,7 @@ public class Objective0 extends Objective {
tasks.add(new Task(R.string.activate_profile) {
@Override
public boolean isCompleted() {
return TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now()) != null;
return treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now()) != null;
}
});
}

View file

@ -2,16 +2,22 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class Objective1 extends Objective {
@Inject SP sp;
@Inject ActionsPlugin actionsPlugin;
@Inject
public Objective1() {
super("usage", R.string.objectives_usage_objective, R.string.objectives_usage_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once ActionsPlugin is prepared for Dagger
}
@Override
@ -19,43 +25,43 @@ public class Objective1 extends Objective {
tasks.add(new Task(R.string.objectives_useprofileswitch) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveuseprofileswitch, false);
return sp.getBoolean(R.string.key_objectiveuseprofileswitch, false);
}
});
tasks.add(new Task(R.string.objectives_usedisconnectpump) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusedisconnect, false);
return sp.getBoolean(R.string.key_objectiveusedisconnect, false);
}
}.hint(new Hint(R.string.disconnectpump_hint)));
tasks.add(new Task(R.string.objectives_usereconnectpump) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusereconnect, false);
return sp.getBoolean(R.string.key_objectiveusereconnect, false);
}
}.hint(new Hint(R.string.disconnectpump_hint)));
tasks.add(new Task(R.string.objectives_usetemptarget) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusetemptarget, false);
return sp.getBoolean(R.string.key_objectiveusetemptarget, false);
}
}.hint(new Hint(R.string.usetemptarget_hint)));
tasks.add(new Task(R.string.objectives_useactions) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveuseactions, false) && ActionsPlugin.INSTANCE.isEnabled(PluginType.GENERAL) && ActionsPlugin.INSTANCE.isFragmentVisible();
return sp.getBoolean(R.string.key_objectiveuseactions, false) && actionsPlugin.isEnabled(PluginType.GENERAL) && actionsPlugin.isFragmentVisible();
}
}.hint(new Hint(R.string.useaction_hint)));
tasks.add(new Task(R.string.objectives_useloop) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveuseloop, false);
return sp.getBoolean(R.string.key_objectiveuseloop, false);
}
}.hint(new Hint(R.string.useaction_hint)));
tasks.add(new Task(R.string.objectives_usescale) {
@Override
public boolean isCompleted() {
return SP.getBoolean(R.string.key_objectiveusescale, false);
return sp.getBoolean(R.string.key_objectiveusescale, false);
}
}.hint(new Hint(R.string.usescale_hint)));
}

View file

@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.Collections;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
public class Objective2 extends Objective {
@ -10,6 +11,7 @@ public class Objective2 extends Objective {
public Objective2() {
super("exam", R.string.objectives_exam_objective, R.string.objectives_exam_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
for (Task task : tasks) {
if (!task.isCompleted()) setAccomplishedOn(0);
}

View file

@ -4,19 +4,27 @@ import android.app.Activity;
import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class Objective3 extends Objective {
@Inject SP sp;
@Inject ObjectivesPlugin objectivesPlugin;
@Inject ResourceHelper resourceHelper;
public final int MANUAL_ENACTS_NEEDED = 20;
private final int MANUAL_ENACTS_NEEDED = 20;
@Inject
public Objective3() {
super("openloop", R.string.objectives_openloop_objective, R.string.objectives_openloop_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
hasSpecialInput = true;
}
@ -26,15 +34,15 @@ public class Objective3 extends Objective {
tasks.add(new Task(R.string.objectives_manualenacts) {
@Override
public boolean isCompleted() {
return SP.getInt(R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED;
return sp.getInt(R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED;
}
@Override
public String getProgress() {
if (SP.getInt(R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED)
return MainApp.gs(R.string.completed_well_done);
if (sp.getInt(R.string.key_ObjectivesmanualEnacts, 0) >= MANUAL_ENACTS_NEEDED)
return resourceHelper.gs(R.string.completed_well_done);
else
return SP.getInt(R.string.key_ObjectivesmanualEnacts, 0) + " / " + MANUAL_ENACTS_NEEDED;
return sp.getInt(R.string.key_ObjectivesmanualEnacts, 0) + " / " + MANUAL_ENACTS_NEEDED;
}
});
}
@ -46,6 +54,6 @@ public class Objective3 extends Objective {
@Override
public void specialAction(Activity activity, String input) {
ObjectivesPlugin.INSTANCE.completeObjectives(activity, input);
objectivesPlugin.completeObjectives(activity, input);
}
}

View file

@ -11,9 +11,7 @@ import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.utils.T;
public class Objective5 extends Objective {
@Inject
SafetyPlugin safetyPlugin;
@Inject SafetyPlugin safetyPlugin;
public Objective5() {
super("maxiobzero", R.string.objectives_maxiobzero_objective, R.string.objectives_maxiobzero_gate);

View file

@ -2,14 +2,19 @@ package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.utils.T;
public class Objective6 extends Objective {
@Inject ConstraintChecker constraintChecker;
public Objective6() {
super("maxiob", R.string.objectives_maxiob_objective, R.string.objectives_maxiob_gate);
MainApp.instance().androidInjector().inject(this); // TODO inject or pass itno constructor once AutomationPlugin is prepared for Dagger
}
@Override
@ -18,7 +23,7 @@ public class Objective6 extends Objective {
tasks.add(new Task(R.string.maxiobset) {
@Override
public boolean isCompleted() {
double maxIOB = ConstraintChecker.getInstance().getMaxIOBAllowed().value();
double maxIOB = constraintChecker.getMaxIOBAllowed().value();
return maxIOB > 0;
}
});

View file

@ -72,7 +72,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface {
if (!MainApp.isEngineeringModeOrRelease()) {
if (value.value()) {
Notification n = new Notification(Notification.TOAST_ALARM, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), Notification.NORMAL);
RxBus.INSTANCE.send(new EventNewNotification(n));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
}
value.set(false, MainApp.gs(R.string.closed_loop_disabled_on_dev_branch), this);
}

View file

@ -54,6 +54,7 @@ public class SignatureVerifierPlugin extends PluginBase implements ConstraintsIn
private File revokedCertsFile;
private List<byte[]> revokedCerts;
@Deprecated
public static SignatureVerifierPlugin getPlugin() {
return plugin;
}
@ -104,7 +105,7 @@ public class SignatureVerifierPlugin extends PluginBase implements ConstraintsIn
private void showNotification() {
Notification notification = new Notification(Notification.INVALID_VERSION, MainApp.gs(R.string.running_invalid_version), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
}
private boolean hasIllegalSignature() {

View file

@ -29,6 +29,7 @@ public class StorageConstraintPlugin extends PluginBase implements ConstraintsIn
private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
static StorageConstraintPlugin plugin = null;
@Deprecated
public static StorageConstraintPlugin getPlugin() {
if (plugin == null)
plugin = new StorageConstraintPlugin();
@ -57,9 +58,9 @@ public class StorageConstraintPlugin extends PluginBase implements ConstraintsIn
if (diskfree < Constants.MINIMUM_FREE_SPACE) {
value.set(false, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), this);
Notification notification = new Notification(Notification.DISKFULL, MainApp.gs(R.string.diskfull, Constants.MINIMUM_FREE_SPACE), Notification.NORMAL);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} else {
RxBus.INSTANCE.send(new EventDismissNotification(Notification.DISKFULL));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.DISKFULL));
}
return value;

View file

@ -1,27 +1,27 @@
package info.nightscout.androidaps.plugins.constraints.versionChecker
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ConstraintsInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.math.roundToInt
/**
* Usually we would have a class here.
* Instead of having a class we can use an object directly inherited from PluginBase.
* This is a lazy loading singleton only loaded when actually used.
* */
object VersionCheckerPlugin : PluginBase(PluginDescription()
@Singleton
class VersionCheckerPlugin @Inject constructor(
private val rxBus: RxBusWrapper,
private val resourceHelper: ResourceHelper
) : PluginBase(PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.neverVisible(true)
.alwaysEnabled(true)
@ -35,11 +35,16 @@ object VersionCheckerPlugin : PluginBase(PluginDescription()
GracePeriod.RELEASE
}
companion object {
private val WARN_EVERY: Long
get() = TimeUnit.DAYS.toMillis(1)
}
override fun isClosedLoopAllowed(value: Constraint<Boolean>): Constraint<Boolean> {
checkWarning()
triggerCheckVersion()
return if (isOldVersion(gracePeriod.veryOld.daysToMillis()))
value.set(false, MainApp.gs(R.string.very_old_version), this)
value.set(false, resourceHelper.gs(R.string.very_old_version), this)
else
value
}
@ -58,13 +63,13 @@ object VersionCheckerPlugin : PluginBase(PluginDescription()
SP.putLong(R.string.key_last_versionchecker_plugin_warning, now)
//notify
val message = MainApp.gs(R.string.new_version_warning,
val message = resourceHelper.gs(R.string.new_version_warning,
((now - SP.getLong(R.string.key_last_time_this_version_detected, now)) / 1L.daysToMillis().toDouble()).roundToInt(),
gracePeriod.old,
gracePeriod.veryOld
)
val notification = Notification(Notification.OLDVERSION, message, Notification.NORMAL)
RxBus.send(EventNewNotification(notification))
rxBus.send(EventNewNotification(notification))
}
}
@ -73,7 +78,7 @@ object VersionCheckerPlugin : PluginBase(PluginDescription()
override fun applyMaxIOBConstraints(maxIob: Constraint<Double>): Constraint<Double> =
if (isOldVersion(gracePeriod.old.daysToMillis()))
maxIob.set(0.toDouble(), MainApp.gs(R.string.old_version), this)
maxIob.set(0.toDouble(), resourceHelper.gs(R.string.old_version), this)
else
maxIob
@ -81,9 +86,6 @@ object VersionCheckerPlugin : PluginBase(PluginDescription()
val now = System.currentTimeMillis()
return now > SP.getLong(R.string.key_last_time_this_version_detected, 0) + gracePeriod
}
private val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
}
enum class GracePeriod(val warning: Long, val old: Long, val veryOld: Long) {

View file

@ -97,7 +97,7 @@ fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
if (now > SP.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
log.debug("Version ${currentVersion} outdated. Found $newVersion")
val notification = Notification(Notification.NEWVERSIONDETECTED, String.format(MainApp.gs(R.string.versionavailable), newVersion.toString()), Notification.LOW)
RxBus.send(EventNewNotification(notification))
RxBus.INSTANCE.send(EventNewNotification(notification))
SP.putLong(R.string.key_last_versionchecker_warning, now)
}
}

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.general.actions
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
@ -8,39 +7,41 @@ import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.activities.HistoryBrowseActivity
import info.nightscout.androidaps.activities.TDDStatsActivity
import info.nightscout.androidaps.dialogs.*
import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction
import info.nightscout.androidaps.dialogs.CareDialog
import info.nightscout.androidaps.dialogs.ExtendedBolusDialog
import info.nightscout.androidaps.dialogs.FillDialog
import info.nightscout.androidaps.dialogs.TempBasalDialog
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.dialogs.ProfileSwitchDialog
import info.nightscout.androidaps.dialogs.TempTargetDialog
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.SingleClickButton
import info.nightscout.androidaps.utils.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.toVisibility
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.actions_fragment.*
import kotlinx.android.synthetic.main.careportal_stats_fragment.*
import java.util.*
import javax.inject.Inject
class ActionsFragment : Fragment() {
class ActionsFragment : DaggerFragment() {
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
private var disposable: CompositeDisposable = CompositeDisposable()
@ -65,16 +66,16 @@ class ActionsFragment : Fragment() {
fragmentManager?.let { ExtendedBolusDialog().show(it, "Actions") }
}
actions_extendedbolus_cancel.setOnClickListener {
if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress) {
ConfigBuilderPlugin.getPlugin().commandQueue.cancelExtended(object : Callback() {
if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress) {
configBuilderPlugin.commandQueue.cancelExtended(object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java)
val i = Intent(mainApp, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", MainApp.gs(R.string.extendedbolusdeliveryerror))
i.putExtra("title", resourceHelper.gs(R.string.extendedbolusdeliveryerror))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
MainApp.instance().startActivity(i)
mainApp.startActivity(i)
}
}
})
@ -84,16 +85,16 @@ class ActionsFragment : Fragment() {
fragmentManager?.let { TempBasalDialog().show(it, "Actions") }
}
actions_canceltempbasal.setOnClickListener {
if (TreatmentsPlugin.getPlugin().isTempBasalInProgress) {
ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() {
if (treatmentsPlugin.isTempBasalInProgress) {
configBuilderPlugin.commandQueue.cancelTempBasal(true, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java)
val i = Intent(mainApp, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror))
i.putExtra("title", resourceHelper.gs(R.string.tempbasaldeliveryerror))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
MainApp.instance().startActivity(i)
mainApp.startActivity(i)
}
}
})
@ -118,30 +119,30 @@ class ActionsFragment : Fragment() {
@Synchronized
override fun onResume() {
super.onResume()
disposable += RxBus
.toObservable(EventInitializationChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventRefreshOverview::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventExtendedBolusChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventTempBasalChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventCustomActionsChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventCareportalEventChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventInitializationChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventRefreshOverview::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventExtendedBolusChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventTempBasalChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventCustomActionsChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventCareportalEventChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
updateGui()
}
@ -154,8 +155,8 @@ class ActionsFragment : Fragment() {
@Synchronized
fun updateGui() {
actions_profileswitch?.visibility =
if (ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile != null) View.VISIBLE
else View.GONE
if (configBuilderPlugin.activeProfileInterface.profile != null) View.VISIBLE
else View.GONE
if (ProfileFunctions.getInstance().getProfile() == null) {
actions_temptarget?.visibility = View.GONE
@ -167,7 +168,7 @@ class ActionsFragment : Fragment() {
return
}
val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return
val pump = configBuilderPlugin.activePump ?: return
val basalProfileEnabled = MainApp.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE
@ -176,11 +177,12 @@ class ActionsFragment : Fragment() {
actions_extendedbolus?.visibility = View.GONE
actions_extendedbolus_cancel?.visibility = View.GONE
} else {
val activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis())
val activeExtendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis())
if (activeExtendedBolus != null) {
actions_extendedbolus?.visibility = View.GONE
actions_extendedbolus_cancel?.visibility = View.VISIBLE
actions_extendedbolus_cancel?.text = MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString()
@Suppress("SetTextI18n")
actions_extendedbolus_cancel?.text = resourceHelper.gs(R.string.cancel) + " " + activeExtendedBolus.toString()
} else {
actions_extendedbolus?.visibility = View.VISIBLE
actions_extendedbolus_cancel?.visibility = View.GONE
@ -191,11 +193,12 @@ class ActionsFragment : Fragment() {
actions_settempbasal?.visibility = View.GONE
actions_canceltempbasal?.visibility = View.GONE
} else {
val activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis())
val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis())
if (activeTemp != null) {
actions_settempbasal?.visibility = View.GONE
actions_canceltempbasal?.visibility = View.VISIBLE
actions_canceltempbasal?.text = MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort()
@Suppress("SetTextI18n")
actions_canceltempbasal?.text = resourceHelper.gs(R.string.cancel) + " " + activeTemp.toStringShort()
} else {
actions_settempbasal?.visibility = View.VISIBLE
actions_canceltempbasal?.visibility = View.GONE
@ -203,8 +206,8 @@ class ActionsFragment : Fragment() {
}
actions_fill?.visibility =
if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE
else View.VISIBLE
if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE
else View.VISIBLE
actions_temptarget?.visibility = Config.APS.toVisibility()
actions_tddstats?.visibility = pump.pumpDescription.supportsTDDs.toVisibility()
@ -215,7 +218,7 @@ class ActionsFragment : Fragment() {
}
private fun checkPumpCustomActions() {
val activePump = ConfigBuilderPlugin.getPlugin().activePump ?: return
val activePump = configBuilderPlugin.activePump ?: return
val customActions = activePump.customActions ?: return
removePumpCustomActions()
@ -223,24 +226,24 @@ class ActionsFragment : Fragment() {
if (!customAction.isEnabled) continue
val btn = SingleClickButton(context, null, android.R.attr.buttonStyle)
btn.text = MainApp.gs(customAction.name)
btn.text = resourceHelper.gs(customAction.name)
val layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f)
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f)
layoutParams.setMargins(20, 8, 20, 8) // 10,3,10,3
btn.layoutParams = layoutParams
btn.setOnClickListener { v ->
val b = v as SingleClickButton
val action = this.pumpCustomActions[b.text.toString()]
ConfigBuilderPlugin.getPlugin().activePump!!.executeCustomAction(action!!.customActionType)
configBuilderPlugin.activePump!!.executeCustomAction(action!!.customActionType)
}
val top = activity?.let { ContextCompat.getDrawable(it, customAction.iconResourceId) }
btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null)
action_buttons_layout?.addView(btn)
this.pumpCustomActions[MainApp.gs(customAction.name)] = customAction
this.pumpCustomActions[resourceHelper.gs(customAction.name)] = customAction
this.pumpCustomButtons.add(btn)
}
}

View file

@ -5,8 +5,11 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import javax.inject.Inject
import javax.inject.Singleton
object ActionsPlugin : PluginBase(PluginDescription()
@Singleton
class ActionsPlugin @Inject constructor(): PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(ActionsFragment::class.qualifiedName)
.enableByDefault(Config.APS || Config.PUMPCONTROL)

View file

@ -5,12 +5,12 @@ import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.OnStartDragListener
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.SimpleItemTouchHelperCallback
@ -22,11 +22,14 @@ import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_fragment.*
import javax.inject.Inject
class AutomationFragment : Fragment(), OnStartDragListener {
class AutomationFragment : DaggerFragment(), OnStartDragListener {
@Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var rxBus: RxBusWrapper
private var disposable: CompositeDisposable = CompositeDisposable()
private var eventListAdapter: EventListAdapter? = null
private lateinit var eventListAdapter: EventListAdapter
private var itemTouchHelper: ItemTouchHelper? = null
@ -37,11 +40,11 @@ class AutomationFragment : Fragment(), OnStartDragListener {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
eventListAdapter = EventListAdapter(AutomationPlugin.automationEvents, fragmentManager, activity, this)
eventListAdapter = EventListAdapter(automationPlugin.automationEvents, fragmentManager, activity, this)
automation_eventListView.layoutManager = LinearLayoutManager(context)
automation_eventListView.adapter = eventListAdapter
automation_logView.setMovementMethod(ScrollingMovementMethod())
automation_logView.movementMethod = ScrollingMovementMethod()
automation_fabAddEvent.setOnClickListener {
val dialog = EditEventDialog()
@ -52,7 +55,7 @@ class AutomationFragment : Fragment(), OnStartDragListener {
fragmentManager?.let { dialog.show(it, "EditEventDialog") }
}
val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter!!)
val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter)
itemTouchHelper = ItemTouchHelper(callback)
itemTouchHelper?.attachToRecyclerView(automation_eventListView)
@ -61,22 +64,22 @@ class AutomationFragment : Fragment(), OnStartDragListener {
@Synchronized
override fun onResume() {
super.onResume()
disposable += RxBus
.toObservable(EventAutomationUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateGui()
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventAutomationDataChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
eventListAdapter?.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventAutomationUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateGui()
}, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventAutomationDataChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
eventListAdapter.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
})
updateGui()
}
@ -88,15 +91,15 @@ class AutomationFragment : Fragment(), OnStartDragListener {
@Synchronized
private fun updateGui() {
eventListAdapter?.notifyDataSetChanged()
eventListAdapter.notifyDataSetChanged()
val sb = StringBuilder()
for (l in AutomationPlugin.executionLog.reversed())
for (l in automationPlugin.executionLog.reversed())
sb.append(l).append("<br>")
automation_logView?.text = HtmlHelper.fromHtml(sb.toString())
}
override fun onStartDrag(viewHolder: RecyclerView.ViewHolder) {
itemTouchHelper?.startDrag(viewHolder);
itemTouchHelper?.startDrag(viewHolder)
}
}

View file

@ -12,9 +12,10 @@ import info.nightscout.androidaps.events.EventPreferenceChange
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.actions.*
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
@ -22,27 +23,37 @@ import info.nightscout.androidaps.plugins.general.automation.triggers.*
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.services.LocationService
import info.nightscout.androidaps.utils.*
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
object AutomationPlugin : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(AutomationFragment::class.qualifiedName)
.pluginName(R.string.automation)
.shortName(R.string.automation_short)
.preferencesId(R.xml.pref_automation)
.description(R.string.automation_description)) {
@Singleton
class AutomationPlugin @Inject constructor(
private val rxBus: RxBusWrapper,
private val aapsLogger: AAPSLogger,
private val mainApp: MainApp,
private val sp :SP
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(AutomationFragment::class.qualifiedName)
.pluginName(R.string.automation)
.shortName(R.string.automation_short)
.preferencesId(R.xml.pref_automation)
.description(R.string.automation_description)) {
private val log = LoggerFactory.getLogger(L.AUTOMATION)
private var disposable: CompositeDisposable = CompositeDisposable()
private const val key_AUTOMATION_EVENTS = "AUTOMATION_EVENTS"
private val keyAutomationEvents = "AUTOMATION_EVENTS"
val automationEvents = ArrayList<AutomationEvent>()
var executionLog: MutableList<String> = ArrayList()
@ -58,72 +69,70 @@ object AutomationPlugin : PluginBase(PluginDescription()
}
override fun onStart() {
val context = MainApp.instance().applicationContext
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
context.startForegroundService(Intent(context, LocationService::class.java))
mainApp.startForegroundService(Intent(mainApp, LocationService::class.java))
else
context.startService(Intent(context, LocationService::class.java))
mainApp.startService(Intent(mainApp, LocationService::class.java))
super.onStart()
loadFromSP()
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += RxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ e ->
if (e.isChanged(R.string.key_location)) {
context.stopService(Intent(context, LocationService::class.java))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
context.startForegroundService(Intent(context, LocationService::class.java))
else
context.startService(Intent(context, LocationService::class.java))
}
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventAutomationDataChanged::class.java)
.observeOn(Schedulers.io())
.subscribe({ storeToSP() }, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventLocationChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ e ->
e?.let {
log.debug("Grabbed location: $it.location.latitude $it.location.longitude Provider: $it.location.provider")
processActions()
}
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventChargingState::class.java)
.observeOn(Schedulers.io())
.subscribe({ processActions() }, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventNetworkChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ processActions() }, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(Schedulers.io())
.subscribe({ processActions() }, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventPreferenceChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ e ->
if (e.isChanged(R.string.key_location)) {
mainApp.stopService(Intent(mainApp, LocationService::class.java))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
mainApp.startForegroundService(Intent(mainApp, LocationService::class.java))
else
mainApp.startService(Intent(mainApp, LocationService::class.java))
}
}, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventAutomationDataChanged::class.java)
.observeOn(Schedulers.io())
.subscribe({ storeToSP() }, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventLocationChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ e ->
e?.let {
aapsLogger.debug(LTag.AUTOMATION, "Grabbed location: $it.location.latitude $it.location.longitude Provider: $it.location.provider")
processActions()
}
}, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventChargingState::class.java)
.observeOn(Schedulers.io())
.subscribe({ processActions() }, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventNetworkChange::class.java)
.observeOn(Schedulers.io())
.subscribe({ processActions() }, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(Schedulers.io())
.subscribe({ processActions() }, {
FabricPrivacy.logException(it)
})
}
override fun onStop() {
disposable.clear()
loopHandler.removeCallbacks(refreshLoop)
val context = MainApp.instance().applicationContext
context.stopService(Intent(context, LocationService::class.java))
mainApp.stopService(Intent(mainApp, LocationService::class.java))
super.onStop()
}
@ -137,12 +146,12 @@ object AutomationPlugin : PluginBase(PluginDescription()
e.printStackTrace()
}
SP.putString(key_AUTOMATION_EVENTS, array.toString())
sp.putString(keyAutomationEvents, array.toString())
}
private fun loadFromSP() {
automationEvents.clear()
val data = SP.getString(key_AUTOMATION_EVENTS, "")
val data = sp.getString(keyAutomationEvents, "")
if (data != "") {
try {
val array = JSONArray(data)
@ -162,13 +171,11 @@ object AutomationPlugin : PluginBase(PluginDescription()
if (!isEnabled(PluginType.GENERAL))
return
if (LoopPlugin.getPlugin().isSuspended || !LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
if (L.isEnabled(L.AUTOMATION))
log.debug("Loop deactivated")
aapsLogger.debug(LTag.AUTOMATION, "Loop deactivated")
return
}
if (L.isEnabled(L.AUTOMATION))
log.debug("processActions")
aapsLogger.debug(LTag.AUTOMATION, "processActions")
for (event in automationEvents) {
if (event.isEnabled && event.trigger.shouldRun() && event.preconditions.shouldRun()) {
val actions = event.actions
@ -186,9 +193,8 @@ object AutomationPlugin : PluginBase(PluginDescription()
sb.append(": ")
sb.append(result.comment)
executionLog.add(sb.toString())
if (L.isEnabled(L.AUTOMATION))
log.debug("Executed: $sb")
RxBus.send(EventAutomationUpdateGui())
aapsLogger.debug(LTag.AUTOMATION, "Executed: $sb")
rxBus.send(EventAutomationUpdateGui())
}
})
}
@ -200,35 +206,35 @@ object AutomationPlugin : PluginBase(PluginDescription()
fun getActionDummyObjects(): List<Action> {
return listOf(
//ActionLoopDisable(),
//ActionLoopEnable(),
//ActionLoopResume(),
//ActionLoopSuspend(),
ActionStartTempTarget(),
ActionStopTempTarget(),
ActionNotification(),
ActionProfileSwitchPercent(),
ActionProfileSwitch(),
ActionSendSMS()
//ActionLoopDisable(),
//ActionLoopEnable(),
//ActionLoopResume(),
//ActionLoopSuspend(),
ActionStartTempTarget(),
ActionStopTempTarget(),
ActionNotification(),
ActionProfileSwitchPercent(),
ActionProfileSwitch(),
ActionSendSMS()
)
}
fun getTriggerDummyObjects(): List<Trigger> {
return listOf(
TriggerTime(),
TriggerRecurringTime(),
TriggerTimeRange(),
TriggerBg(),
TriggerDelta(),
TriggerIob(),
TriggerCOB(),
TriggerProfilePercent(),
TriggerTempTarget(),
TriggerWifiSsid(),
TriggerLocation(),
TriggerAutosensValue(),
TriggerBolusAgo(),
TriggerPumpLastConnection()
TriggerTime(),
TriggerRecurringTime(),
TriggerTimeRange(),
TriggerBg(),
TriggerDelta(),
TriggerIob(),
TriggerCOB(),
TriggerProfilePercent(),
TriggerTempTarget(),
TriggerWifiSsid(),
TriggerLocation(),
TriggerAutosensValue(),
TriggerBolusAgo(),
TriggerPumpLastConnection()
)
}

View file

@ -100,7 +100,7 @@ class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder>
// enabled event
holder.enabled.setOnClickListener(v -> {
event.setEnabled((holder.enabled.isChecked()));
RxBus.INSTANCE.send(new EventAutomationDataChanged());
RxBus.Companion.getINSTANCE().send(new EventAutomationDataChanged());
});
// edit event
@ -138,7 +138,7 @@ class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder>
public boolean onItemMove(int fromPosition, int toPosition) {
Collections.swap(eventList, fromPosition, toPosition);
notifyItemMoved(fromPosition, toPosition);
RxBus.INSTANCE.send(new EventAutomationDataChanged());
RxBus.Companion.getINSTANCE().send(new EventAutomationDataChanged());
return true;
}
@ -148,10 +148,10 @@ class EventListAdapter extends RecyclerView.Adapter<EventListAdapter.ViewHolder>
() -> {
eventList.remove(position);
notifyItemRemoved(position);
RxBus.INSTANCE.send(new EventAutomationDataChanged());
RxBus.INSTANCE.send(new EventAutomationUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventAutomationDataChanged());
RxBus.Companion.getINSTANCE().send(new EventAutomationUpdateGui());
}, () -> {
RxBus.INSTANCE.send(new EventAutomationUpdateGui());
RxBus.Companion.getINSTANCE().send(new EventAutomationUpdateGui());
});
}

View file

@ -31,7 +31,7 @@ public class ActionLoopDisable extends Action {
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
RxBus.INSTANCE.send(new EventRefreshOverview("ActionLoopDisable"));
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("ActionLoopDisable"));
if (callback != null)
callback.result(result).run();
}

View file

@ -28,7 +28,7 @@ public class ActionLoopEnable extends Action {
if (!LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) {
LoopPlugin.getPlugin().setPluginEnabled(PluginType.LOOP, true);
ConfigBuilderPlugin.getPlugin().storeSettings("ActionLoopEnable");
RxBus.INSTANCE.send(new EventRefreshOverview("ActionLoopEnable"));
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("ActionLoopEnable"));
if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();
} else {

View file

@ -29,7 +29,7 @@ public class ActionLoopResume extends Action {
LoopPlugin.getPlugin().suspendTo(0);
ConfigBuilderPlugin.getPlugin().storeSettings("ActionLoopResume");
NSUpload.uploadOpenAPSOffline(0);
RxBus.INSTANCE.send(new EventRefreshOverview("ActionLoopResume"));
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("ActionLoopResume"));
if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();
} else {

View file

@ -40,7 +40,7 @@ public class ActionLoopSuspend extends Action {
public void doAction(Callback callback) {
if (!LoopPlugin.getPlugin().isSuspended()) {
LoopPlugin.getPlugin().suspendLoop(minutes.getMinutes());
RxBus.INSTANCE.send(new EventRefreshOverview("ActionLoopSuspend"));
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("ActionLoopSuspend"));
if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();
} else {

View file

@ -41,9 +41,9 @@ public class ActionNotification extends Action {
@Override
public void doAction(Callback callback) {
Notification notification = new Notification(Notification.USERMESSAGE, text.getValue(), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
NSUpload.uploadError(text.getValue());
RxBus.INSTANCE.send(new EventRefreshOverview("ActionNotification"));
RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("ActionNotification"));
if (callback != null)
callback.result(new PumpEnactResult().success(true).comment(R.string.ok)).run();

View file

@ -14,7 +14,8 @@ import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
class ActionListAdapter(private val fragmentManager: FragmentManager, private val actionList: MutableList<Action>) : RecyclerView.Adapter<ActionListAdapter.ViewHolder>() {
class ActionListAdapter(private val fragmentManager: FragmentManager, private val actionList: MutableList<Action>)
: RecyclerView.Adapter<ActionListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.automation_action_item, parent, false)
@ -46,7 +47,7 @@ class ActionListAdapter(private val fragmentManager: FragmentManager, private va
view.findViewById<ImageView>(R.id.automation_iconTrash).setOnClickListener {
actionList.remove(action)
recyclerView.notifyDataSetChanged()
RxBus.send(EventAutomationUpdateGui())
RxBus.INSTANCE.send(EventAutomationUpdateGui())
}
if (action.icon().isPresent) view.findViewById<ImageView>(R.id.automation_action_image).setImageResource(action.icon().get())
view.findViewById<TextView>(R.id.automation_viewActionTitle).text = action.shortDescription()

View file

@ -7,14 +7,17 @@ import android.view.ViewGroup
import android.widget.RadioButton
import info.nightscout.androidaps.R
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationAddAction
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
import kotlinx.android.synthetic.main.automation_dialog_choose_action.*
import javax.inject.Inject
class ChooseActionDialog : DialogFragmentWithDate() {
@Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var rxBus: RxBusWrapper
private var checkedIndex = -1
@ -32,7 +35,7 @@ class ChooseActionDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
for (a in AutomationPlugin.getActionDummyObjects()) {
for (a in automationPlugin.getActionDummyObjects()) {
val radioButton = RadioButton(context)
radioButton.setText(a.friendlyName())
radioButton.tag = a.javaClass
@ -45,8 +48,8 @@ class ChooseActionDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
instantiateAction()?.let {
RxBus.send(EventAutomationAddAction(it))
RxBus.send(EventAutomationUpdateGui())
rxBus.send(EventAutomationAddAction(it))
rxBus.send(EventAutomationUpdateGui())
}
return true
}

View file

@ -10,8 +10,10 @@ import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import kotlinx.android.synthetic.main.automation_dialog_choose_trigger.*
import javax.inject.Inject
class ChooseTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var automationPlugin: AutomationPlugin
private var checkedIndex = -1
private var clickListener: OnClickListener? = null
@ -34,7 +36,7 @@ class ChooseTriggerDialog : DialogFragmentWithDate() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
for (t in AutomationPlugin.getTriggerDummyObjects()) {
for (t in automationPlugin.getTriggerDummyObjects()) {
val radioButton = RadioButton(context)
radioButton.setText(t.friendlyName())
radioButton.tag = t.javaClass

View file

@ -6,13 +6,16 @@ import android.view.View
import android.view.ViewGroup
import info.nightscout.androidaps.R
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateAction
import kotlinx.android.synthetic.main.automation_dialog_action.*
import org.json.JSONObject
import javax.inject.Inject
class EditActionDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
private var action: Action? = null
private var actionPosition: Int = -1
@ -39,7 +42,7 @@ class EditActionDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
action?.let {
RxBus.send(EventAutomationUpdateAction(it, actionPosition))
rxBus.send(EventAutomationUpdateAction(it, actionPosition))
}
return true
}

View file

@ -7,18 +7,26 @@ import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import info.nightscout.androidaps.R
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.AutomationEvent
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.events.*
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationAddAction
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateAction
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateTrigger
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_dialog_event.*
import javax.inject.Inject
class EditEventDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var automationPlugin: AutomationPlugin
private var actionListAdapter: ActionListAdapter? = null
private var event: AutomationEvent = AutomationEvent()
@ -61,49 +69,48 @@ class EditEventDialog : DialogFragmentWithDate() {
showPreconditions()
disposable.add(RxBus
.toObservable(EventAutomationUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
actionListAdapter?.notifyDataSetChanged()
showPreconditions()
}, {
FabricPrivacy.logException(it)
})
)
disposable.add(RxBus
.toObservable(EventAutomationAddAction::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.addAction(it.action)
actionListAdapter?.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
})
)
disposable.add(RxBus
.toObservable(EventAutomationUpdateTrigger::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.trigger = it.trigger
automation_triggerDescription.text = event.trigger.friendlyDescription()
}, {
FabricPrivacy.logException(it)
})
)
disposable.add(RxBus
.toObservable(EventAutomationUpdateAction::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.actions[it.position] = it.action
actionListAdapter?.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
})
)
disposable += rxBus
.toObservable(EventAutomationUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
actionListAdapter?.notifyDataSetChanged()
showPreconditions()
}, {
FabricPrivacy.logException(it)
}
)
disposable += rxBus
.toObservable(EventAutomationAddAction::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.addAction(it.action)
actionListAdapter?.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
}
)
disposable += rxBus
.toObservable(EventAutomationUpdateTrigger::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.trigger = it.trigger
automation_triggerDescription.text = event.trigger.friendlyDescription()
}, {
FabricPrivacy.logException(it)
}
)
disposable += rxBus
.toObservable(EventAutomationUpdateAction::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.actions[it.position] = it.action
actionListAdapter?.notifyDataSetChanged()
}, {
FabricPrivacy.logException(it)
})
}
override fun submit() : Boolean{
override fun submit(): Boolean {
// check for title
val title = automation_inputEventTitle.text.toString()
if (title.isEmpty()) {
@ -124,11 +131,11 @@ class EditEventDialog : DialogFragmentWithDate() {
}
// store
if (position == -1)
AutomationPlugin.automationEvents.add(event)
automationPlugin.automationEvents.add(event)
else
AutomationPlugin.automationEvents[position] = event
automationPlugin.automationEvents[position] = event
RxBus.send(EventAutomationDataChanged())
rxBus.send(EventAutomationDataChanged())
return true
}

View file

@ -6,12 +6,14 @@ import android.view.View
import android.view.ViewGroup
import info.nightscout.androidaps.R
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateTrigger
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import kotlinx.android.synthetic.main.automation_dialog_edit_trigger.*
import javax.inject.Inject
class EditTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
private var trigger: Trigger? = null
@ -33,8 +35,8 @@ class EditTriggerDialog : DialogFragmentWithDate() {
trigger?.generateDialog(automation_layoutTrigger, fragmentManager)
}
override fun submit():Boolean {
trigger?.let { trigger -> RxBus.send(EventAutomationUpdateTrigger(trigger)) }
override fun submit(): Boolean {
trigger?.let { trigger -> rxBus.send(EventAutomationUpdateTrigger(trigger)) }
return true
}

View file

@ -120,7 +120,7 @@ public class CareportalFragment extends Fragment implements View.OnClickListener
@Override
public synchronized void onResume() {
super.onResume();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventCareportalEventChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGUI(), FabricPrivacy::logException)

View file

@ -1,36 +0,0 @@
package info.nightscout.androidaps.plugins.general.careportal;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
public class CareportalPlugin extends PluginBase {
static CareportalPlugin careportalPlugin;
static public CareportalPlugin getPlugin() {
if (careportalPlugin == null) {
careportalPlugin = new CareportalPlugin();
}
return careportalPlugin;
}
public CareportalPlugin() {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(CareportalFragment.class.getName())
.pluginName(R.string.careportal)
.shortName(R.string.careportal_shortname)
.visibleByDefault(Config.NSCLIENT)
.enableByDefault(Config.NSCLIENT)
.description(R.string.description_careportal)
);
}
@Override
public boolean specialEnableCondition() {
return Config.NSCLIENT;
}
}

View file

@ -0,0 +1,25 @@
package info.nightscout.androidaps.plugins.general.careportal
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class CareportalPlugin @Inject constructor() : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(CareportalFragment::class.java.name)
.pluginName(R.string.careportal)
.shortName(R.string.careportal_shortname)
.visibleByDefault(Config.NSCLIENT)
.enableByDefault(Config.NSCLIENT)
.description(R.string.description_careportal)
) {
override fun specialEnableCondition(): Boolean {
return Config.NSCLIENT
}
}

View file

@ -125,7 +125,7 @@ public class FoodFragment extends Fragment {
@Override
public synchronized void onResume() {
super.onResume();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventFoodDatabaseChanged.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), FabricPrivacy::logException)

View file

@ -12,6 +12,7 @@ public class FoodPlugin extends PluginBase {
private static FoodPlugin plugin = null;
@Deprecated
public static FoodPlugin getPlugin() {
if (plugin == null)
plugin = new FoodPlugin();

View file

@ -53,7 +53,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public FoodService() {
onCreate();
dbInitialize();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNsFood.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -166,7 +166,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void run() {
if (L.isEnabled(L.DATAFOOD))
log.debug("Firing EventFoodChange");
RxBus.INSTANCE.send(event);
RxBus.Companion.getINSTANCE().send(event);
callback.setPost(null);
}
}

View file

@ -110,7 +110,7 @@ public class ImportExportPrefs {
SP.putBoolean(R.string.key_setupwizard_processed, true);
OKDialog.show(context, MainApp.gs(R.string.setting_imported), MainApp.gs(R.string.restartingapp), () -> {
log.debug("Exiting");
RxBus.INSTANCE.send(new EventAppExit());
RxBus.Companion.getINSTANCE().send(new EventAppExit());
if (context instanceof Activity) {
((Activity) context).finish();
}

View file

@ -39,6 +39,7 @@ public class MaintenancePlugin extends PluginBase {
private static MaintenancePlugin maintenancePlugin;
@Deprecated
public static MaintenancePlugin getPlugin() {
return maintenancePlugin;
}

View file

@ -82,7 +82,7 @@ public class NSClientFragment extends Fragment implements View.OnClickListener,
@Override
public synchronized void onResume() {
super.onResume();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNSClientUpdateGUI.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updateGui(), FabricPrivacy::logException)
@ -100,7 +100,7 @@ public class NSClientFragment extends Fragment implements View.OnClickListener,
public void onClick(View view) {
switch (view.getId()) {
case R.id.nsclientinternal_restart:
RxBus.INSTANCE.send(new EventNSClientRestart());
RxBus.Companion.getINSTANCE().send(new EventNSClientRestart());
FabricPrivacy.getInstance().logCustom("NSClientRestart");
break;
case R.id.nsclientinternal_delivernow:
@ -118,7 +118,7 @@ public class NSClientFragment extends Fragment implements View.OnClickListener,
});
break;
case R.id.nsclientinternal_showqueue:
RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList()));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList()));
break;
}
}

View file

@ -50,6 +50,7 @@ public class NSClientPlugin extends PluginBase {
static NSClientPlugin nsClientPlugin;
@Deprecated
static public NSClientPlugin getPlugin() {
if (nsClientPlugin == null) {
nsClientPlugin = new NSClientPlugin();
@ -110,25 +111,25 @@ public class NSClientPlugin extends PluginBase {
super.onStart();
nsClientReceiverDelegate.grabReceiversState();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNSClientStatus.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
status = event.getStatus();
RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI());
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNetworkChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventPreferenceChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventAppExit.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -137,7 +138,7 @@ public class NSClientPlugin extends PluginBase {
}
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNSClientNewLog.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -146,7 +147,7 @@ public class NSClientPlugin extends PluginBase {
log.debug(event.getAction() + " " + event.getLogText());
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventChargingState.class)
.observeOn(Schedulers.io())
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException)
@ -199,7 +200,7 @@ public class NSClientPlugin extends PluginBase {
synchronized (listLog) {
listLog.clear();
}
RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI());
});
}
@ -212,7 +213,7 @@ public class NSClientPlugin extends PluginBase {
listLog.remove(0);
}
}
RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI());
});
}
@ -238,7 +239,7 @@ public class NSClientPlugin extends PluginBase {
public void pause(boolean newState) {
SP.putBoolean(R.string.key_nsclientinternal_paused, newState);
paused = newState;
RxBus.INSTANCE.send(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
RxBus.Companion.getINSTANCE().send(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
}
public UploadQueue queue() {

View file

@ -26,10 +26,10 @@ class NsClientReceiverDelegate {
Context context = MainApp.instance().getApplicationContext();
EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(context);
if (event != null) RxBus.INSTANCE.send(event);
if (event != null) RxBus.Companion.getINSTANCE().send(event);
EventChargingState eventChargingState = ChargingStateReceiver.grabChargingState(context);
if (eventChargingState != null) RxBus.INSTANCE.send(eventChargingState);
if (eventChargingState != null) RxBus.Companion.getINSTANCE().send(eventChargingState);
}
@ -40,11 +40,11 @@ class NsClientReceiverDelegate {
) {
EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext());
if (event != null)
RxBus.INSTANCE.send(event);
RxBus.Companion.getINSTANCE().send(event);
} else if (ev.isChanged(R.string.key_ns_chargingonly)) {
EventChargingState event = ChargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext());
if (event != null)
RxBus.INSTANCE.send(event);
RxBus.Companion.getINSTANCE().send(event);
}
}
@ -70,7 +70,7 @@ class NsClientReceiverDelegate {
boolean newAllowedState = allowedChargingState && allowedNetworkState;
if (newAllowedState != allowed) {
allowed = newAllowedState;
RxBus.INSTANCE.send(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
RxBus.Companion.getINSTANCE().send(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
}
}

View file

@ -33,7 +33,7 @@ public class NSAddAck extends Event implements Ack {
nsClientID = response.getString("NSCLIENT_ID");
}
}
RxBus.INSTANCE.send(this);
RxBus.Companion.getINSTANCE().send(this);
return;
} catch (Exception e) {
log.error("Unhandled exception", e);
@ -44,7 +44,7 @@ public class NSAddAck extends Event implements Ack {
if (response.has("result")) {
_id = null;
if (response.getString("result").contains("Not")) {
RxBus.INSTANCE.send(new EventNSClientRestart());
RxBus.Companion.getINSTANCE().send(new EventNSClientRestart());
return;
}
if (L.isEnabled(L.NSCLIENT))

View file

@ -16,6 +16,6 @@ public class NSAuthAck extends Event implements Ack{
read = response.optBoolean("read");
write = response.optBoolean("write");
write_treatment = response.optBoolean("write_treatment");
RxBus.INSTANCE.send(this);
RxBus.Companion.getINSTANCE().send(this);
}
}

View file

@ -28,7 +28,7 @@ public class NSUpdateAck extends Event implements Ack {
result = true;
log.debug("Internal error: Missing _id returned on dbUpdate ack");
}
RxBus.INSTANCE.send(this);
RxBus.Companion.getINSTANCE().send(this);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}

View file

@ -156,22 +156,22 @@ public class NSSettingsStatus {
try {
if (nsClientVersionCode < MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), 0).versionCode) {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} else {
RxBus.INSTANCE.send(new EventDismissNotification(Notification.OLD_NSCLIENT));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.OLD_NSCLIENT));
}
} catch (PackageManager.NameNotFoundException e) {
log.error("Unhandled exception", e);
}
if (nightscoutVersionCode < Config.SUPPORTEDNSVERSION) {
Notification notification = new Notification(Notification.OLD_NS, MainApp.gs(R.string.unsupportednsversion), Notification.NORMAL);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
} else {
RxBus.INSTANCE.send(new EventDismissNotification(Notification.OLD_NS));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.OLD_NS));
}
} else {
Notification notification = new Notification(Notification.OLD_NSCLIENT, MainApp.gs(R.string.unsupportedclientver), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(notification));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(notification));
}
if (bundle.containsKey("status")) {
try {

View file

@ -130,7 +130,7 @@ public class NSClientService extends Service {
public void onCreate() {
super.onCreate();
mWakeLock.acquire();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventConfigBuilderChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -141,7 +141,7 @@ public class NSClientService extends Service {
}
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventPreferenceChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -155,7 +155,7 @@ public class NSClientService extends Service {
}
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventAppExit.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -165,7 +165,7 @@ public class NSClientService extends Service {
stopSelf();
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNSClientRestart.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -173,17 +173,17 @@ public class NSClientService extends Service {
restart();
}, FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(NSAuthAck.class)
.observeOn(Schedulers.io())
.subscribe(event -> processAuthAck(event), FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(NSUpdateAck.class)
.observeOn(Schedulers.io())
.subscribe(event -> processUpdateAck(event), FabricPrivacy::logException)
);
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(NSAddAck.class)
.observeOn(Schedulers.io())
.subscribe(event -> processAddAck(event), FabricPrivacy::logException)
@ -200,18 +200,18 @@ public class NSClientService extends Service {
public void processAddAck(NSAddAck ack) {
if (ack.nsClientID != null) {
uploadQueue.removeID(ack.json);
RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
} else {
RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBADD Unknown response"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ERROR", "DBADD Unknown response"));
}
}
public void processUpdateAck(NSUpdateAck ack) {
if (ack.result) {
uploadQueue.removeID(ack.action, ack._id);
RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id));
} else {
RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));
}
}
@ -223,19 +223,19 @@ public class NSClientService extends Service {
connectionStatus += ')';
isConnected = true;
hasWriteAuth = ack.write && ack.write_treatment;
RxBus.INSTANCE.send(new EventNSClientStatus(connectionStatus));
RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", connectionStatus));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus(connectionStatus));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("AUTH", connectionStatus));
if (!ack.write) {
RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!"));
}
if (!ack.write_treatment) {
RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!"));
}
if (!hasWriteAuth) {
Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(noperm));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(noperm));
} else {
RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
}
}
@ -264,19 +264,19 @@ public class NSClientService extends Service {
if (!nsAPISecret.equals(""))
nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString();
RxBus.INSTANCE.send(new EventNSClientStatus("Initializing"));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Initializing"));
if (!NSClientPlugin.getPlugin().isAllowed()) {
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "not allowed"));
RxBus.INSTANCE.send(new EventNSClientStatus("Not allowed"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "not allowed"));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Not allowed"));
} else if (NSClientPlugin.getPlugin().paused) {
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "paused"));
RxBus.INSTANCE.send(new EventNSClientStatus("Paused"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "paused"));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Paused"));
} else if (!nsEnabled) {
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "disabled"));
RxBus.INSTANCE.send(new EventNSClientStatus("Disabled"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "disabled"));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Disabled"));
} else if (!nsURL.equals("")) {
try {
RxBus.INSTANCE.send(new EventNSClientStatus("Connecting ..."));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Connecting ..."));
IO.Options opt = new IO.Options();
opt.forceNew = true;
opt.reconnection = true;
@ -284,7 +284,7 @@ public class NSClientService extends Service {
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_PING, onPing);
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "do connect"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "do connect"));
mSocket.connect();
mSocket.on("dataUpdate", onDataUpdate);
mSocket.on("announcement", onAnnouncement);
@ -292,12 +292,12 @@ public class NSClientService extends Service {
mSocket.on("urgent_alarm", onUrgentAlarm);
mSocket.on("clear_alarm", onClearAlarm);
} catch (URISyntaxException | RuntimeException e) {
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax"));
RxBus.INSTANCE.send(new EventNSClientStatus("Wrong URL syntax"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax"));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Wrong URL syntax"));
}
} else {
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "No NS URL specified"));
RxBus.INSTANCE.send(new EventNSClientStatus("Not configured"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "No NS URL specified"));
RxBus.Companion.getINSTANCE().send(new EventNSClientStatus("Not configured"));
}
}
@ -306,7 +306,7 @@ public class NSClientService extends Service {
public void call(Object... args) {
connectCounter++;
String socketId = mSocket != null ? mSocket.id() : "NULL";
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId));
if (mSocket != null)
sendAuthMessage(new NSAuthAck());
watchdog();
@ -323,16 +323,16 @@ public class NSClientService extends Service {
reconnections.remove(r);
}
}
RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS));
if (reconnections.size() >= WATCHDOG_MAXCONNECTIONS) {
Notification n = new Notification(Notification.NSMALFUNCTION, MainApp.gs(R.string.nsmalfunction), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(n));
RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
NSClientPlugin.getPlugin().pause(true);
RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
RxBus.Companion.getINSTANCE().send(new EventNSClientUpdateGUI());
new Thread(() -> {
SystemClock.sleep(T.mins(WATCHDOG_RECONNECT_IN).msecs());
RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient"));
NSClientPlugin.getPlugin().pause(false);
}).start();
}
@ -344,7 +344,7 @@ public class NSClientService extends Service {
public void call(Object... args) {
if (L.isEnabled(L.NSCLIENT))
log.debug("disconnect reason: {}", args);
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
}
};
@ -359,7 +359,7 @@ public class NSClientService extends Service {
mSocket.off("urgent_alarm");
mSocket.off("clear_alarm");
RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "destroy"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "destroy"));
isConnected = false;
hasWriteAuth = false;
mSocket.disconnect();
@ -380,7 +380,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
return;
}
RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", "requesting auth"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("AUTH", "requesting auth"));
if (mSocket != null)
mSocket.emit("authorize", authMessage, ack);
}
@ -395,7 +395,7 @@ public class NSClientService extends Service {
private Emitter.Listener onPing = new Emitter.Listener() {
@Override
public void call(final Object... args) {
RxBus.INSTANCE.send(new EventNSClientNewLog("PING", "received"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("PING", "received"));
// send data if there is something waiting
resend("Ping received");
}
@ -424,7 +424,7 @@ public class NSClientService extends Service {
return;
}
try {
RxBus.INSTANCE.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received")));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received")));
} catch (Exception e) {
FabricPrivacy.logException(e);
log.error("Unhandled exception", e);
@ -451,7 +451,7 @@ public class NSClientService extends Service {
*/
@Override
public void call(final Object... args) {
RxBus.INSTANCE.send(new EventNSClientNewLog("ALARM", "received"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ALARM", "received"));
JSONObject data;
try {
data = (JSONObject) args[0];
@ -490,7 +490,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
return;
}
RxBus.INSTANCE.send(new EventNSClientNewLog("URGENTALARM", "received"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("URGENTALARM", "received"));
BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext());
if (L.isEnabled(L.NSCLIENT))
log.debug(data.toString());
@ -516,7 +516,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
return;
}
RxBus.INSTANCE.send(new EventNSClientNewLog("CLEARALARM", "received"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("CLEARALARM", "received"));
BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext());
if (L.isEnabled(L.NSCLIENT))
log.debug(data.toString());
@ -541,7 +541,7 @@ public class NSClientService extends Service {
// delta means only increment/changes are comming
boolean isDelta = data.has("delta");
boolean isFull = !isDelta;
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full")));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full")));
if (data.has("profiles")) {
JSONArray profiles = data.getJSONArray("profiles");
@ -549,7 +549,7 @@ public class NSClientService extends Service {
JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1);
profileStore = new ProfileStore(profile);
broadcastProfile = true;
RxBus.INSTANCE.send(new EventNSClientNewLog("PROFILE", "profile received"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("PROFILE", "profile received"));
}
}
@ -559,7 +559,7 @@ public class NSClientService extends Service {
if (!status.has("versionNum")) {
if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) {
RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
}
} else {
nightscoutVersionName = nsSettingsStatus.getVersion();
@ -584,13 +584,13 @@ public class NSClientService extends Service {
}
*/
} else if (!isDelta) {
RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
}
// If new profile received or change detected broadcast it
if (broadcastProfile && profileStore != null) {
BroadcastProfile.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta);
RxBus.INSTANCE.send(new EventNSClientNewLog("PROFILE", "broadcasting"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("PROFILE", "broadcasting"));
}
if (data.has("treatments")) {
@ -599,7 +599,7 @@ public class NSClientService extends Service {
JSONArray updatedTreatments = new JSONArray();
JSONArray addedTreatments = new JSONArray();
if (treatments.length() > 0)
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments"));
for (Integer index = 0; index < treatments.length(); index++) {
JSONObject jsonTreatment = treatments.getJSONObject(index);
NSTreatment treatment = new NSTreatment(jsonTreatment);
@ -633,7 +633,7 @@ public class NSClientService extends Service {
if (data.has("devicestatus")) {
JSONArray devicestatuses = data.getJSONArray("devicestatus");
if (devicestatuses.length() > 0) {
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses"));
for (Integer index = 0; index < devicestatuses.length(); index++) {
JSONObject jsonStatus = devicestatuses.getJSONObject(index);
// remove from upload queue if Ack is failing
@ -648,7 +648,7 @@ public class NSClientService extends Service {
JSONArray updatedFoods = new JSONArray();
JSONArray addedFoods = new JSONArray();
if (foods.length() > 0)
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods"));
for (Integer index = 0; index < foods.length(); index++) {
JSONObject jsonFood = foods.getJSONObject(index);
@ -678,7 +678,7 @@ public class NSClientService extends Service {
if (data.has("mbgs")) {
JSONArray mbgs = data.getJSONArray("mbgs");
if (mbgs.length() > 0)
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs"));
for (Integer index = 0; index < mbgs.length(); index++) {
JSONObject jsonMbg = mbgs.getJSONObject(index);
// remove from upload queue if Ack is failing
@ -689,7 +689,7 @@ public class NSClientService extends Service {
if (data.has("cals")) {
JSONArray cals = data.getJSONArray("cals");
if (cals.length() > 0)
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals"));
// Retreive actual calibration
for (Integer index = 0; index < cals.length(); index++) {
// remove from upload queue if Ack is failing
@ -700,10 +700,10 @@ public class NSClientService extends Service {
if (data.has("sgvs")) {
JSONArray sgvs = data.getJSONArray("sgvs");
if (sgvs.length() > 0)
RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
for (Integer index = 0; index < sgvs.length(); index++) {
JSONObject jsonSgv = sgvs.getJSONObject(index);
// RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString());
// RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString());
NSSgv sgv = new NSSgv(jsonSgv);
// Handle new sgv here
// remove from upload queue if Ack is failing
@ -718,15 +718,15 @@ public class NSClientService extends Service {
if ((System.currentTimeMillis() - latestDateInReceivedData) / (60 * 1000L) < 15L)
lessThan15MinAgo = true;
if (Notification.isAlarmForStaleData() && lessThan15MinAgo) {
RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSALARM));
RxBus.Companion.getINSTANCE().send(new EventDismissNotification(Notification.NSALARM));
}
BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta);
}
RxBus.INSTANCE.send(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData)));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData)));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
//RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
//RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
} finally {
if (wakeLock.isHeld()) wakeLock.release();
}
@ -744,7 +744,7 @@ public class NSClientService extends Service {
message.put("_id", dbr._id);
message.put("data", new JSONObject(dbr.data));
mSocket.emit("dbUpdate", message, ack);
RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@ -758,7 +758,7 @@ public class NSClientService extends Service {
message.put("_id", dbr._id);
message.put("data", new JSONObject(dbr.data));
mSocket.emit("dbUpdateUnset", message, ack);
RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@ -771,7 +771,7 @@ public class NSClientService extends Service {
message.put("collection", dbr.collection);
message.put("_id", dbr._id);
mSocket.emit("dbRemove", message, ack);
RxBus.INSTANCE.send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@ -784,7 +784,7 @@ public class NSClientService extends Service {
message.put("collection", dbr.collection);
message.put("data", new JSONObject(dbr.data));
mSocket.emit("dbAdd", message, ack);
RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@ -793,7 +793,7 @@ public class NSClientService extends Service {
public void sendAlarmAck(AlarmAck alarmAck) {
if (!isConnected || !hasWriteAuth) return;
mSocket.emit("ack", alarmAck.level, alarmAck.group, alarmAck.silenceTime);
RxBus.INSTANCE.send(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime));
}
public void resend(final String reason) {
@ -814,7 +814,7 @@ public class NSClientService extends Service {
}
lastResendTime = System.currentTimeMillis();
RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
CloseableIterator<DbRequest> iterator = null;
int maxcount = 30;
@ -845,7 +845,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
}
RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason));
RxBus.Companion.getINSTANCE().send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason));
}
});
}

View file

@ -45,6 +45,9 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import dagger.android.support.DaggerFragment;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
@ -95,6 +98,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus;
import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity;
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
@ -122,7 +126,9 @@ import io.reactivex.disposables.CompositeDisposable;
import static info.nightscout.androidaps.utils.DateUtil.now;
public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
public class OverviewFragment extends DaggerFragment implements View.OnClickListener, View.OnLongClickListener {
@Inject NotificationStore notificationStore;
private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
private CompositeDisposable disposable = new CompositeDisposable();
@ -355,85 +361,85 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
@Override
public void onResume() {
super.onResume();
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventRefreshOverview.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(eventOpenAPSUpdateGui -> scheduleUpdateGUI(eventOpenAPSUpdateGui.getFrom()),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventExtendedBolusChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventExtendedBolusChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventTempBasalChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventTempBasalChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventTreatmentChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventTreatmentChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventTempTargetChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventTempTargetChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventAcceptOpenLoopChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventAcceptOpenLoopChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventCareportalEventChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventCareportalEventChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventInitializationChanged.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventInitializationChanged"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventAutosensCalculationFinished.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventAutosensCalculationFinished"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventProfileNeedsUpdate.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventProfileNeedsUpdate"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventPreferenceChange.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventPreferenceChange"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventNewOpenLoopNotification.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> scheduleUpdateGUI("EventNewOpenLoopNotification"),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventPumpStatusChanged.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> updatePumpStatus(event.getStatus()),
FabricPrivacy::logException
));
disposable.add(RxBus.INSTANCE
disposable.add(RxBus.Companion.getINSTANCE()
.toObservable(EventIobCalculationProgress.class)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(event -> {
@ -1002,7 +1008,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
timeView.setText(DateUtil.timeString(new Date()));
}
OverviewPlugin.INSTANCE.getNotificationStore().updateNotifications(notificationsView);
notificationStore.updateNotifications(notificationsView);
pumpStatusLayout.setVisibility(View.GONE);
loopStatusLayout.setVisibility(View.GONE);

View file

@ -7,8 +7,7 @@ import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore
@ -17,46 +16,59 @@ import info.nightscout.androidaps.utils.SP
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.slf4j.LoggerFactory
import javax.inject.Inject
import javax.inject.Singleton
object OverviewPlugin : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(OverviewFragment::class.qualifiedName)
.alwaysVisible(true)
.alwaysEnabled(true)
.pluginName(R.string.overview)
.shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview)
.description(R.string.description_overview)) {
@Singleton
class OverviewPlugin @Inject constructor(
private val rxBus: RxBusWrapper,
private val notificationStore: NotificationStore
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(OverviewFragment::class.qualifiedName)
.alwaysVisible(true)
.alwaysEnabled(true)
.pluginName(R.string.overview)
.shortName(R.string.overview_shortname)
.preferencesId(R.xml.pref_overview)
.description(R.string.description_overview)) {
init {
INSTANCE = this
}
companion object {
@JvmStatic
@Deprecated("Get via Dagger. Will be removed once fully transitioned to Dagger")
lateinit var INSTANCE: OverviewPlugin //TODO: remove as soon as Dagger is fully set up
}
private val log = LoggerFactory.getLogger(L.OVERVIEW)
private var disposable: CompositeDisposable = CompositeDisposable()
var bgTargetLow = 80.0
var bgTargetHigh = 180.0
var notificationStore = NotificationStore()
override fun onStart() {
super.onStart()
disposable += RxBus
.toObservable(EventNewNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.add(n.notification))
RxBus.send(EventRefreshOverview("EventNewNotification"))
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventDismissNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.remove(n.id))
RxBus.send(EventRefreshOverview("EventDismissNotification"))
}, {
FabricPrivacy.logException(it)
})
notificationStore.createNotificationChannel()
disposable += rxBus
.toObservable(EventNewNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.add(n.notification))
rxBus.send(EventRefreshOverview("EventNewNotification"))
}, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventDismissNotification::class.java)
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.remove(n.id))
rxBus.send(EventRefreshOverview("EventDismissNotification"))
}, {
FabricPrivacy.logException(it)
})
}
override fun onStop() {

View file

@ -12,18 +12,21 @@ import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.data.QuickWizard
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.dialogs.EditQuickWizardDialog
import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.plusAssign
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.overview_quickwizardlist_activity.*
import javax.inject.Inject
class QuickWizardListActivity : NoSplashAppCompatActivity() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var resourceHelper: ResourceHelper
private var disposable: CompositeDisposable = CompositeDisposable()
@ -37,7 +40,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
holder.from.text = DateUtil.timeString(QuickWizard[position].validFromDate())
holder.to.text = DateUtil.timeString(QuickWizard[position].validToDate())
holder.buttonText.text = QuickWizard[position].buttonText()
holder.carbs.text = DecimalFormatter.to0Decimal(QuickWizard[position].carbs().toDouble()) + " g"
holder.carbs.text = resourceHelper.gs(R.string.format_carbs, QuickWizard[position].carbs())
}
override fun getItemCount(): Int = QuickWizard.size()
@ -59,7 +62,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
}
removeButton.setOnClickListener {
QuickWizard.remove(adapterPosition)
RxBus.send(EventQuickWizardChange())
rxBus.send(EventQuickWizardChange())
}
}
}
@ -82,15 +85,15 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
override fun onResume() {
super.onResume()
disposable += RxBus
.toObservable(EventQuickWizardChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
val adapter = RecyclerViewAdapter(supportFragmentManager)
overview_quickwizardactivity_recyclerview?.swapAdapter(adapter, false)
}, {
FabricPrivacy.logException(it)
})
disposable += rxBus
.toObservable(EventQuickWizardChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
val adapter = RecyclerViewAdapter(supportFragmentManager)
overview_quickwizardactivity_recyclerview?.swapAdapter(adapter, false)
}, {
FabricPrivacy.logException(it)
})
}
override fun onPause() {

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