From ada6e38f5f9b8982e89a9128f676b8be14c2af69 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 17:23:31 +0200 Subject: [PATCH 01/13] Events to RxBus --- .../activities/TDDStatsActivity.java | 24 +- .../androidaps/db/DatabaseHelper.java | 12 +- .../events/EventCustomActionsChanged.java | 4 - .../events/EventCustomActionsChanged.kt | 3 + .../events/EventExtendedBolusChange.java | 8 - .../events/EventExtendedBolusChange.kt | 3 + .../androidaps/events/EventLoop.java | 5 - .../nightscout/androidaps/events/EventLoop.kt | 4 + .../events/EventPumpStatusChanged.java | 63 ---- .../events/EventPumpStatusChanged.kt | 62 ++++ .../events/EventRefreshOverview.java | 13 - .../androidaps/events/EventRefreshOverview.kt | 3 + .../events/EventReloadProfileSwitchData.java | 8 - .../events/EventReloadProfileSwitchData.kt | 3 + .../events/EventReloadTempBasalData.java | 8 - .../events/EventReloadTempBasalData.kt | 3 + .../events/EventReloadTreatmentData.java | 13 - .../events/EventReloadTreatmentData.kt | 3 + .../androidaps/events/EventStatus.kt | 6 + .../events/EventTempBasalChange.java | 7 - .../androidaps/events/EventTempBasalChange.kt | 3 + .../events/EventTempTargetChange.java | 8 - .../events/EventTempTargetChange.kt | 3 + .../events/EventTreatmentChange.java | 17 - .../androidaps/events/EventTreatmentChange.kt | 5 + .../plugins/aps/loop/LoopPlugin.java | 19 +- .../general/actions/ActionsFragment.java | 329 ------------------ .../general/actions/ActionsFragment.kt | 242 +++++++++++++ .../plugins/general/actions/ActionsPlugin.kt | 2 +- .../general/nsclient/NSClientPlugin.java | 19 +- .../nsclient/events/EventNSClientStatus.java | 18 - .../nsclient/events/EventNSClientStatus.kt | 7 + .../nsclient/services/NSClientService.java | 16 +- .../general/overview/OverviewFragment.java | 78 +++-- .../general/overview/OverviewPlugin.kt | 4 +- .../overview/dialogs/BolusProgressDialog.java | 34 +- .../PersistentNotificationPlugin.java | 53 +-- .../SmsCommunicatorPlugin.java | 8 +- .../plugins/general/wear/WearPlugin.java | 52 +-- .../xdripStatusline/StatuslinePlugin.java | 60 ++-- .../plugins/pump/combo/ComboPlugin.java | 1 + .../plugins/pump/danaR/DanaRFragment.kt | 51 ++- .../activities/DanaRHistoryActivity.java | 19 +- .../AbstractDanaRExecutionService.java | 7 +- .../danaR/services/DanaRExecutionService.java | 42 +-- .../services/DanaRKoreanExecutionService.java | 40 ++- .../DanaRS_Packet_APS_History_Events.java | 3 +- .../plugins/pump/danaRS/services/BLEComm.java | 10 +- .../pump/danaRS/services/DanaRSService.java | 59 ++-- .../danaRv2/comm/MsgHistoryEvents_v2.java | 3 +- .../services/DanaRv2ExecutionService.java | 59 ++-- .../pump/insight/LocalInsightPlugin.java | 10 +- .../pump/medtronic/MedtronicFragment.kt | 27 +- .../pump/medtronic/MedtronicPumpPlugin.java | 4 +- .../plugins/treatments/TreatmentService.java | 2 + .../treatments/TreatmentsFragment.java | 73 ++-- .../plugins/treatments/TreatmentsPlugin.java | 75 ++-- .../fragments/TreatmentsBolusFragment.java | 38 +- .../TreatmentsExtendedBolusesFragment.java | 52 +-- .../TreatmentsTempTargetFragment.java | 46 +-- .../TreatmentsTemporaryBasalsFragment.java | 47 ++- .../androidaps/queue/QueueThread.java | 19 +- .../androidaps/setupwizard/SWDefinition.java | 17 +- .../setupwizard/SWEventListener.java | 45 +-- .../setupwizard/SetupWizardActivity.java | 26 +- .../androidaps/utils/BolusWizard.kt | 3 +- 66 files changed, 984 insertions(+), 1026 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventLoop.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index 487def0241..6c2b9417d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -37,8 +37,10 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TDD; +import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; @@ -49,11 +51,15 @@ import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class TDDStatsActivity extends NoSplashActivity { private static Logger log = LoggerFactory.getLogger(TDDStatsActivity.class); + private CompositeDisposable disposable = new CompositeDisposable(); TextView statusView, statsMessage, totalBaseBasal2; EditText totalBaseBasal; @@ -75,12 +81,18 @@ public class TDDStatsActivity extends NoSplashActivity { protected void onResume() { super.onResume(); MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventPumpStatusChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) + ); } @Override protected void onPause() { super.onPause(); MainApp.bus().unregister(this); + disposable.clear(); } @Override @@ -531,18 +543,6 @@ public class TDDStatsActivity extends NoSplashActivity { }); } - @Subscribe - public void onStatusEvent(final EventPumpStatusChanged c) { - runOnUiThread( - new Runnable() { - @Override - public void run() { - statusView.setText(c.textStatus()); - } - } - ); - } - public static boolean isOldData(List historyList) { Object activePump = ConfigBuilderPlugin.getPlugin().getActivePump(); diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 9fa3ab9929..fd9af55eca 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -243,7 +243,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { new java.util.TimerTask() { @Override public void run() { - MainApp.bus().post(new EventRefreshOverview("resetDatabases")); + RxBus.INSTANCE.send(new EventRefreshOverview("resetDatabases")); } }, 3000 @@ -738,7 +738,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventTempTargetChange"); - MainApp.bus().post(new EventTempTargetChange()); + RxBus.INSTANCE.send(new EventTempTargetChange()); scheduledTemTargetPost = null; } } @@ -1035,8 +1035,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventTempBasalChange"); - MainApp.bus().post(new EventReloadTempBasalData()); - MainApp.bus().post(new EventTempBasalChange()); + RxBus.INSTANCE.send(new EventReloadTempBasalData()); + RxBus.INSTANCE.send(new EventTempBasalChange()); if (earliestDataChange != null) MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; @@ -1371,7 +1371,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventExtendedBolusChange"); - MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange())); + RxBus.INSTANCE.send(new EventReloadTreatmentData(new EventExtendedBolusChange())); if (earliestDataChange != null) MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; @@ -1720,7 +1720,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventProfileNeedsUpdate"); - MainApp.bus().post(new EventReloadProfileSwitchData()); + RxBus.INSTANCE.send(new EventReloadProfileSwitchData()); MainApp.bus().post(new EventProfileNeedsUpdate()); scheduledProfileSwitchEventPost = null; } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.java deleted file mode 100644 index 81d1f60271..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.events; - -public class EventCustomActionsChanged extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt new file mode 100644 index 0000000000..d75bf612ce --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventCustomActionsChanged : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java deleted file mode 100644 index 8881b0ecc1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 15.05.2017. - */ - -public class EventExtendedBolusChange extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt new file mode 100644 index 0000000000..4ed0ca5ffe --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventExtendedBolusChange : EventLoop() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLoop.java b/app/src/main/java/info/nightscout/androidaps/events/EventLoop.java deleted file mode 100644 index d694d52537..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventLoop.java +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.events; - -/** Supeclass for all events concerned with input or output into or from the LoopPlugin. */ -public abstract class EventLoop extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt b/app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt new file mode 100644 index 0000000000..dd28e2323b --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.events + +/** Supeclass for all events concerned with input or output into or from the LoopPlugin. */ +abstract class EventLoop : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java deleted file mode 100644 index 6729a4e703..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java +++ /dev/null @@ -1,63 +0,0 @@ -package info.nightscout.androidaps.events; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; - -/** - * Created by mike on 19.02.2017. - */ - -public class EventPumpStatusChanged extends Event { - public static final int CONNECTING = 0; - public static final int CONNECTED = 1; - public static final int HANDSHAKING = 2; - public static final int PERFORMING = 3; - public static final int DISCONNECTING = 4; - public static final int DISCONNECTED = 5; - - public int sStatus = DISCONNECTED; - public int sSecondsElapsed = 0; - public String sPerfomingAction = ""; - - public static String error = ""; - - public EventPumpStatusChanged(int status) { - sStatus = status; - sSecondsElapsed = 0; - error = ""; - } - - public EventPumpStatusChanged(int status, int secondsElapsed) { - sStatus = status; - sSecondsElapsed = secondsElapsed; - error = ""; - } - - public EventPumpStatusChanged(int status, String error) { - sStatus = status; - sSecondsElapsed = 0; - this.error = error; - } - - public EventPumpStatusChanged(String action) { - sStatus = PERFORMING; - sSecondsElapsed = 0; - sPerfomingAction = action; - } - - public String textStatus() { - if (sStatus == CONNECTING) - return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed); - else if (sStatus == HANDSHAKING) - return MainApp.gs(R.string.handshaking); - else if (sStatus == CONNECTED) - return MainApp.gs(R.string.connected); - else if (sStatus == PERFORMING) - return sPerfomingAction; - else if (sStatus == DISCONNECTING) - return MainApp.gs(R.string.disconnecting); - else if (sStatus == DISCONNECTED) - return ""; - return ""; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt new file mode 100644 index 0000000000..3d25bc1ca5 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt @@ -0,0 +1,62 @@ +package info.nightscout.androidaps.events + +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R + +class EventPumpStatusChanged : EventStatus { + + enum class Status { + CONNECTING, + CONNECTED, + HANDSHAKING, + PERFORMING, + DISCONNECTING, + DISCONNECTED + } + + var sStatus: Status = Status.DISCONNECTED + var sSecondsElapsed = 0 + var sPerfomingAction = "" + var error = "" + + constructor(status: Status) { + sStatus = status + sSecondsElapsed = 0 + error = "" + } + + constructor(status: Status, secondsElapsed: Int) { + sStatus = status + sSecondsElapsed = secondsElapsed + error = "" + } + + constructor(status: Status, error: String) { + sStatus = status + sSecondsElapsed = 0 + this.error = error + } + + constructor(action: String) { + sStatus = Status.PERFORMING + sSecondsElapsed = 0 + sPerfomingAction = action + } + + // status for startup wizard + override fun getStatus(): String { + if (sStatus == Status.CONNECTING) + return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed) + else if (sStatus == Status.HANDSHAKING) + return MainApp.gs(R.string.handshaking) + else if (sStatus == Status.CONNECTED) + return MainApp.gs(R.string.connected) + else if (sStatus == Status.PERFORMING) + return sPerfomingAction + else if (sStatus == Status.DISCONNECTING) + return MainApp.gs(R.string.disconnecting) + else if (sStatus == Status.DISCONNECTED) + return "" + return "" + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java deleted file mode 100644 index 2ba78fa9ec..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 16.06.2017. - */ - -public class EventRefreshOverview extends Event { - public String from; - - public EventRefreshOverview(String from) { - this.from = from; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt new file mode 100644 index 0000000000..533a25dd40 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventRefreshOverview(var from: String) : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java deleted file mode 100644 index 212e8856d9..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 12.06.2017. - */ - -public class EventReloadProfileSwitchData extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt b/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt new file mode 100644 index 0000000000..6f6d848b5e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventReloadProfileSwitchData : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java deleted file mode 100644 index 80125cbb4a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 29.05.2017. - */ - -public class EventReloadTempBasalData extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt new file mode 100644 index 0000000000..fa8f720896 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventReloadTempBasalData : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java deleted file mode 100644 index 0ba9b95ad7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 29.05.2017. - */ - -public class EventReloadTreatmentData extends Event { - public Object next; - - public EventReloadTreatmentData(Object next) { - this.next = next; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt new file mode 100644 index 0000000000..1f8b2938b9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventReloadTreatmentData(var next: Event) : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt b/app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt new file mode 100644 index 0000000000..193c3b1fdb --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.events + +// pass string to startup wizard +abstract class EventStatus :Event() { + abstract fun getStatus() : String +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java deleted file mode 100644 index 73660bb00e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 05.06.2016. - */ -public class EventTempBasalChange extends EventLoop { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt new file mode 100644 index 0000000000..3f3ecf732e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventTempBasalChange : EventLoop() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java deleted file mode 100644 index 4e3bf5c5f8..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 13.01.2017. - */ - -public class EventTempTargetChange extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt new file mode 100644 index 0000000000..c108d6589c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventTempTargetChange : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java deleted file mode 100644 index e1d9d527e1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.events; - -import androidx.annotation.Nullable; - -import info.nightscout.androidaps.plugins.treatments.Treatment; - -/** - * Created by mike on 04.06.2016. - */ -public class EventTreatmentChange extends EventLoop { - @Nullable - public final Treatment treatment; - - public EventTreatmentChange(Treatment treatment) { - this.treatment = treatment; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt new file mode 100644 index 0000000000..9cbc9d1563 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.events + +import info.nightscout.androidaps.plugins.treatments.Treatment + +class EventTreatmentChange(val treatment: Treatment?) : EventLoop() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index c9444acb33..c87e938d8a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -62,12 +62,15 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.ToastUtils; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 05.08.2016. */ public class LoopPlugin extends PluginBase { private static Logger log = LoggerFactory.getLogger(L.APS); + private CompositeDisposable disposable = new CompositeDisposable(); private static final String CHANNEL_ID = "AndroidAPS-Openloop"; @@ -119,6 +122,13 @@ public class LoopPlugin extends PluginBase { MainApp.bus().register(this); createNotificationChannel(); super.onStart(); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempTargetChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + invoke("EventTempTargetChange", true); + }, FabricPrivacy::logException) + ); } private void createNotificationChannel() { @@ -135,8 +145,9 @@ public class LoopPlugin extends PluginBase { @Override protected void onStop() { - super.onStop(); MainApp.bus().unregister(this); + disposable.clear(); + super.onStop(); } @Override @@ -176,12 +187,6 @@ public class LoopPlugin extends PluginBase { return loopSuspendedTill; } - @Subscribe - public void onStatusEvent(final EventTempTargetChange ev) { - new Thread(() -> invoke("EventTempTargetChange", true)).start(); - } - - public void suspendTo(long endTime) { loopSuspendedTill = endTime; isSuperBolus = false; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java deleted file mode 100644 index 579700be4c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java +++ /dev/null @@ -1,329 +0,0 @@ -package info.nightscout.androidaps.plugins.general.actions; - - -import android.app.Activity; -import android.content.Intent; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.LinearLayout; - -import androidx.fragment.app.FragmentManager; - -import com.squareup.otto.Subscribe; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.activities.HistoryBrowseActivity; -import info.nightscout.androidaps.activities.TDDStatsActivity; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.events.EventCustomActionsChanged; -import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.events.EventInitializationChanged; -import info.nightscout.androidaps.events.EventRefreshOverview; -import info.nightscout.androidaps.events.EventTempBasalChange; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; -import info.nightscout.androidaps.plugins.general.actions.dialogs.FillDialog; -import info.nightscout.androidaps.plugins.general.actions.dialogs.NewExtendedBolusDialog; -import info.nightscout.androidaps.plugins.general.actions.dialogs.NewTempBasalDialog; -import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; -import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.SP; -import info.nightscout.androidaps.utils.SingleClickButton; - -public class ActionsFragment extends SubscriberFragment implements View.OnClickListener { - - private View actionsFragmentView; - private SingleClickButton profileSwitch; - private SingleClickButton tempTarget; - private SingleClickButton extendedBolus; - private SingleClickButton extendedBolusCancel; - private SingleClickButton tempBasal; - private SingleClickButton tempBasalCancel; - private SingleClickButton fill; - private SingleClickButton tddStats; - private SingleClickButton history; - - private Map pumpCustomActions = new HashMap<>(); - private List pumpCustomButtons = new ArrayList<>(); - - public ActionsFragment() { - super(); - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View view = inflater.inflate(R.layout.actions_fragment, container, false); - - profileSwitch = view.findViewById(R.id.actions_profileswitch); - tempTarget = view.findViewById(R.id.actions_temptarget); - extendedBolus = view.findViewById(R.id.actions_extendedbolus); - extendedBolusCancel = view.findViewById(R.id.actions_extendedbolus_cancel); - tempBasal = view.findViewById(R.id.actions_settempbasal); - tempBasalCancel = view.findViewById(R.id.actions_canceltempbasal); - fill = view.findViewById(R.id.actions_fill); - tddStats = view.findViewById(R.id.actions_tddstats); - history = view.findViewById(R.id.actions_historybrowser); - - profileSwitch.setOnClickListener(this); - tempTarget.setOnClickListener(this); - extendedBolus.setOnClickListener(this); - extendedBolusCancel.setOnClickListener(this); - tempBasal.setOnClickListener(this); - tempBasalCancel.setOnClickListener(this); - fill.setOnClickListener(this); - history.setOnClickListener(this); - tddStats.setOnClickListener(this); - - actionsFragmentView = view; - - updateGUI(); - SP.putBoolean(R.string.key_objectiveuseactions, true); - return view; - } - - @Subscribe - public void onStatusEvent(final EventInitializationChanged ev) { - updateGUI(); - } - - @Subscribe - public void onStatusEvent(final EventRefreshOverview ev) { - updateGUI(); - } - - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - updateGUI(); - } - - @Subscribe - public void onStatusEvent(final EventTempBasalChange ev) { - updateGUI(); - } - - @Subscribe - public void onStatusEvent(final EventCustomActionsChanged ev) { - updateGUI(); - } - - @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) { - profileSwitch.setVisibility(View.VISIBLE); - } else { - profileSwitch.setVisibility(View.GONE); - } - - if (ProfileFunctions.getInstance().getProfile() == null) { - tempTarget.setVisibility(View.GONE); - extendedBolus.setVisibility(View.GONE); - extendedBolusCancel.setVisibility(View.GONE); - tempBasal.setVisibility(View.GONE); - tempBasalCancel.setVisibility(View.GONE); - fill.setVisibility(View.GONE); - return; - } - - final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); - final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease() - && pump.getPumpDescription().isSetBasalProfileCapable; - - if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended()) - profileSwitch.setVisibility(View.GONE); - else - profileSwitch.setVisibility(View.VISIBLE); - - if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) { - extendedBolus.setVisibility(View.GONE); - extendedBolusCancel.setVisibility(View.GONE); - } else { - ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); - if (activeExtendedBolus != null) { - extendedBolus.setVisibility(View.GONE); - extendedBolusCancel.setVisibility(View.VISIBLE); - extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString()); - } else { - extendedBolus.setVisibility(View.VISIBLE); - extendedBolusCancel.setVisibility(View.GONE); - } - } - - - if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) { - tempBasal.setVisibility(View.GONE); - tempBasalCancel.setVisibility(View.GONE); - } else { - final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - tempBasal.setVisibility(View.GONE); - tempBasalCancel.setVisibility(View.VISIBLE); - tempBasalCancel.setText(MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort()); - } else { - tempBasal.setVisibility(View.VISIBLE); - tempBasalCancel.setVisibility(View.GONE); - } - } - - if (!pump.getPumpDescription().isRefillingCapable || !pump.isInitialized() || pump.isSuspended()) - fill.setVisibility(View.GONE); - else - fill.setVisibility(View.VISIBLE); - - if (!Config.APS) - tempTarget.setVisibility(View.GONE); - else - tempTarget.setVisibility(View.VISIBLE); - - if (!pump.getPumpDescription().supportsTDDs) - tddStats.setVisibility(View.GONE); - else - tddStats.setVisibility(View.VISIBLE); - - checkPumpCustomActions(); - - } - }); - } - - - View.OnClickListener pumpCustomActionsListener = v -> { - - SingleClickButton btn = (SingleClickButton) v; - - CustomAction customAction = this.pumpCustomActions.get(btn.getText().toString()); - - ConfigBuilderPlugin.getPlugin().getActivePump().executeCustomAction(customAction.getCustomActionType()); - - }; - - - private void checkPumpCustomActions() { - - PumpInterface activePump = ConfigBuilderPlugin.getPlugin().getActivePump(); - - removePumpCustomActions(); - - if (activePump == null) { - return; - } - - List customActions = activePump.getCustomActions(); - - if (customActions != null && customActions.size() > 0) { - - LinearLayout ll = actionsFragmentView.findViewById(R.id.action_buttons_layout); - - for (CustomAction customAction : customActions) { - - if (!customAction.isEnabled()) - continue; - - SingleClickButton btn = new SingleClickButton(getContext(), null, android.R.attr.buttonStyle); - btn.setText(MainApp.gs(customAction.getName())); - - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f); - layoutParams.setMargins(20, 8, 20, 8); // 10,3,10,3 - - btn.setLayoutParams(layoutParams); - btn.setOnClickListener(pumpCustomActionsListener); - - Drawable top = getResources().getDrawable(customAction.getIconResourceId()); - btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null); - - ll.addView(btn); - - this.pumpCustomActions.put(MainApp.gs(customAction.getName()), customAction); - this.pumpCustomButtons.add(btn); - } - } - } - - - private void removePumpCustomActions() { - - if (pumpCustomActions.size() == 0) - return; - - LinearLayout ll = actionsFragmentView.findViewById(R.id.action_buttons_layout); - - for (SingleClickButton customButton : pumpCustomButtons) { - ll.removeView(customButton); - } - - pumpCustomButtons.clear(); - } - - - @Override - public void onClick(View view) { - FragmentManager manager = getFragmentManager(); - switch (view.getId()) { - case R.id.actions_profileswitch: - NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog(); - final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCH; - profileswitch.executeProfileSwitch = true; - newDialog.setOptions(profileswitch, R.string.careportal_profileswitch); - newDialog.show(manager, "NewNSTreatmentDialog"); - break; - case R.id.actions_temptarget: - NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog(); - final OptionsToShow temptarget = CareportalFragment.TEMPTARGET; - temptarget.executeTempTarget = true; - newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget); - newTTDialog.show(manager, "NewNSTreatmentDialog"); - break; - case R.id.actions_extendedbolus: - NewExtendedBolusDialog newExtendedDialog = new NewExtendedBolusDialog(); - newExtendedDialog.show(manager, "NewExtendedDialog"); - break; - case R.id.actions_extendedbolus_cancel: - if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(null); - } - break; - case R.id.actions_canceltempbasal: - if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) { - ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null); - } - break; - case R.id.actions_settempbasal: - NewTempBasalDialog newTempDialog = new NewTempBasalDialog(); - newTempDialog.show(manager, "NewTempDialog"); - break; - case R.id.actions_fill: - FillDialog fillDialog = new FillDialog(); - fillDialog.show(manager, "FillDialog"); - break; - case R.id.actions_historybrowser: - startActivity(new Intent(getContext(), HistoryBrowseActivity.class)); - break; - case R.id.actions_tddstats: - startActivity(new Intent(getContext(), TDDStatsActivity.class)); - break; - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt new file mode 100644 index 0000000000..cb431f9f69 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -0,0 +1,242 @@ +package info.nightscout.androidaps.plugins.general.actions + + +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.LinearLayout +import androidx.fragment.app.Fragment +import info.nightscout.androidaps.Config +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.activities.HistoryBrowseActivity +import info.nightscout.androidaps.activities.TDDStatsActivity +import info.nightscout.androidaps.events.* +import info.nightscout.androidaps.plugins.bus.RxBus +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.plugins.general.actions.dialogs.FillDialog +import info.nightscout.androidaps.plugins.general.actions.dialogs.NewExtendedBolusDialog +import info.nightscout.androidaps.plugins.general.actions.dialogs.NewTempBasalDialog +import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment +import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.utils.* +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.disposables.CompositeDisposable +import kotlinx.android.synthetic.main.actions_fragment.* +import java.util.* + +class ActionsFragment : Fragment() { + + private var disposable: CompositeDisposable = CompositeDisposable() + + private val pumpCustomActions = HashMap() + private val pumpCustomButtons = ArrayList() + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, + savedInstanceState: Bundle?): View? { + return inflater.inflate(R.layout.actions_fragment, container, false) + } + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + actions_profileswitch.setOnClickListener { + val newDialog = NewNSTreatmentDialog() + val profileSwitch = CareportalFragment.PROFILESWITCH + profileSwitch.executeProfileSwitch = true + newDialog.setOptions(profileSwitch, R.string.careportal_profileswitch) + fragmentManager?.let { newDialog.show(it, "NewNSTreatmentDialog") } + } + actions_temptarget.setOnClickListener { + val newTTDialog = NewNSTreatmentDialog() + val temptarget = CareportalFragment.TEMPTARGET + temptarget.executeTempTarget = true + newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget) + fragmentManager?.let { newTTDialog.show(it, "NewNSTreatmentDialog") } + } + actions_extendedbolus.setOnClickListener { + fragmentManager?.let { NewExtendedBolusDialog().show(it, "NewExtendedDialog") } + } + actions_extendedbolus_cancel.setOnClickListener { + if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress) { + ConfigBuilderPlugin.getPlugin().commandQueue.cancelExtended(object : Callback() { + override fun run() { + if (!result.success) + ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.extendedbolusdeliveryerror)) + } + }) + } + } + actions_settempbasal.setOnClickListener { fragmentManager?.let { NewTempBasalDialog().show(it, "NewTempDialog") } } + actions_canceltempbasal.setOnClickListener { + if (TreatmentsPlugin.getPlugin().isTempBasalInProgress) { + ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() { + override fun run() { + if (!result.success) + ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.tempbasaldeliveryerror)) + } + }) + } + } + actions_fill.setOnClickListener { fragmentManager?.let { FillDialog().show(it, "FillDialog") } } + actions_historybrowser.setOnClickListener { startActivity(Intent(context, HistoryBrowseActivity::class.java)) } + actions_tddstats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } + + SP.putBoolean(R.string.key_objectiveuseactions, true) + } + + @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) + }) + updateGui() + } + + @Synchronized + override fun onPause() { + super.onPause() + disposable.clear() + } + + @Synchronized + fun updateGui() { + actions_profileswitch?.visibility = + if (ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile != null) View.VISIBLE + else View.GONE + + if (ProfileFunctions.getInstance().profile == null) { + actions_temptarget?.visibility = View.GONE + actions_extendedbolus?.visibility = View.GONE + actions_extendedbolus_cancel?.visibility = View.GONE + actions_settempbasal?.visibility = View.GONE + actions_canceltempbasal?.visibility = View.GONE + actions_fill?.visibility = View.GONE + return + } + + val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return + val basalProfileEnabled = MainApp.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable + + actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE + + if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized || pump.isSuspended || pump.isFakingTempsByExtendedBoluses) { + actions_extendedbolus?.visibility = View.GONE + actions_extendedbolus_cancel?.visibility = View.GONE + } else { + val activeExtendedBolus = TreatmentsPlugin.getPlugin().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() + } else { + actions_extendedbolus?.visibility = View.VISIBLE + actions_extendedbolus_cancel?.visibility = View.GONE + } + } + + if (!pump.pumpDescription.isTempBasalCapable || !pump.isInitialized || pump.isSuspended) { + actions_settempbasal?.visibility = View.GONE + actions_canceltempbasal?.visibility = View.GONE + } else { + val activeTemp = TreatmentsPlugin.getPlugin().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() + } else { + actions_settempbasal?.visibility = View.VISIBLE + actions_canceltempbasal?.visibility = View.GONE + } + } + + actions_fill?.visibility = + if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE + else View.VISIBLE + + actions_temptarget?.visibility = if (!Config.APS) View.GONE else View.VISIBLE + actions_tddstats?.visibility = if (!pump.pumpDescription.supportsTDDs) View.GONE else View.VISIBLE + checkPumpCustomActions() + } + + private fun checkPumpCustomActions() { + val activePump = ConfigBuilderPlugin.getPlugin().activePump ?: return + val customActions = activePump.customActions ?: return + removePumpCustomActions() + + for (customAction in customActions) { + if (!customAction.isEnabled) continue + + val btn = SingleClickButton(context, null, android.R.attr.buttonStyle) + btn.text = MainApp.gs(customAction.name) + + val layoutParams = LinearLayout.LayoutParams( + 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) + } + + val top = resources.getDrawable(customAction.iconResourceId) + btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null) + + action_buttons_layout?.addView(btn) + + this.pumpCustomActions[MainApp.gs(customAction.name)] = customAction + this.pumpCustomButtons.add(btn) + } + } + + private fun removePumpCustomActions() { + for (customButton in pumpCustomButtons) action_buttons_layout?.removeView(customButton) + pumpCustomButtons.clear() + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt index 086c75a157..04afb826a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.PluginType object ActionsPlugin : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) - .fragmentClass(ActionsFragment::class.java.name) + .fragmentClass(ActionsFragment::class.qualifiedName) .pluginName(R.string.actions) .shortName(R.string.actions_shortname) .description(R.string.description_actions)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index 4b6072ee1e..e7cfc7a0dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -35,11 +35,15 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientN import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.ToastUtils; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class NSClientPlugin extends PluginBase { private Logger log = LoggerFactory.getLogger(L.NSCLIENT); + private CompositeDisposable disposable = new CompositeDisposable(); static NSClientPlugin nsClientPlugin; @@ -104,6 +108,14 @@ public class NSClientPlugin extends PluginBase { super.onStart(); nsClientReceiverDelegate.registerReceivers(); + disposable.add(RxBus.INSTANCE + .toObservable(EventNSClientStatus.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + status = event.getStatus(); + MainApp.bus().post(new EventNSClientUpdateGUI()); + }, FabricPrivacy::logException) + ); } @Override @@ -113,6 +125,7 @@ public class NSClientPlugin extends PluginBase { context.unbindService(mConnection); nsClientReceiverDelegate.unregisterReceivers(); + disposable.clear(); super.onStop(); } @@ -164,12 +177,6 @@ public class NSClientPlugin extends PluginBase { log.debug(ev.action + " " + ev.logText); } - @Subscribe - public void onStatusEvent(final EventNSClientStatus ev) { - status = ev.status; - MainApp.bus().post(new EventNSClientUpdateGUI()); - } - synchronized void clearLog() { handler.post(() -> { synchronized (listLog) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java deleted file mode 100644 index c3bf74321c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java +++ /dev/null @@ -1,18 +0,0 @@ -package info.nightscout.androidaps.plugins.general.nsclient.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 02.01.2016. - */ -public class EventNSClientStatus extends Event { - public String status = ""; - - public EventNSClientStatus(String status) { - this.status = status; - } - - public EventNSClientStatus() { - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt new file mode 100644 index 0000000000..4d0c9dcd6e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.general.nsclient.events + +import info.nightscout.androidaps.events.EventStatus + +class EventNSClientStatus(var text: String) : EventStatus() { + override fun getStatus(): String = text +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 98ac099851..b3e14a7669 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -208,19 +208,19 @@ public class NSClientService extends Service { if (!nsAPISecret.equals("")) nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); - MainApp.bus().post(new EventNSClientStatus("Initializing")); + RxBus.INSTANCE.send(new EventNSClientStatus("Initializing")); if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "not allowed")); - MainApp.bus().post(new EventNSClientStatus("Not allowed")); + RxBus.INSTANCE.send(new EventNSClientStatus("Not allowed")); } else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused")); - MainApp.bus().post(new EventNSClientStatus("Paused")); + RxBus.INSTANCE.send(new EventNSClientStatus("Paused")); } else if (!nsEnabled) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled")); - MainApp.bus().post(new EventNSClientStatus("Disabled")); + RxBus.INSTANCE.send(new EventNSClientStatus("Disabled")); } else if (!nsURL.equals("")) { try { - MainApp.bus().post(new EventNSClientStatus("Connecting ...")); + RxBus.INSTANCE.send(new EventNSClientStatus("Connecting ...")); IO.Options opt = new IO.Options(); opt.forceNew = true; opt.reconnection = true; @@ -237,11 +237,11 @@ public class NSClientService extends Service { mSocket.on("clear_alarm", onClearAlarm); } catch (URISyntaxException | RuntimeException e) { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax")); - MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax")); + RxBus.INSTANCE.send(new EventNSClientStatus("Wrong URL syntax")); } } else { MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified")); - MainApp.bus().post(new EventNSClientStatus("Not configured")); + RxBus.INSTANCE.send(new EventNSClientStatus("Not configured")); } } @@ -338,7 +338,7 @@ public class NSClientService extends Service { connectionStatus += ')'; isConnected = true; hasWriteAuth = ack.write && ack.write_treatment; - MainApp.bus().post(new EventNSClientStatus(connectionStatus)); + RxBus.INSTANCE.send(new EventNSClientStatus(connectionStatus)); MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus)); if (!ack.write) { MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index b7d7cae4a0..f16bd1c383 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -83,8 +83,11 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; +import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui; import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; @@ -113,18 +116,24 @@ import info.nightscout.androidaps.utils.BolusWizard; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DefaultValueHelper; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SingleClickButton; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.ToastUtils; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.utils.DateUtil.now; public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener { private static Logger log = LoggerFactory.getLogger(L.OVERVIEW); + private CompositeDisposable disposable = new CompositeDisposable(); + TextView timeView; TextView bgView; TextView arrowView; @@ -850,6 +859,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, public void onPause() { super.onPause(); MainApp.bus().unregister(this); + disposable.clear(); sLoopHandler.removeCallbacksAndMessages(null); unregisterForContextMenu(apsModeView); unregisterForContextMenu(activeProfileView); @@ -860,6 +870,42 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, public void onResume() { super.onResume(); MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventRefreshOverview.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(eventOpenAPSUpdateGui -> scheduleUpdateGUI(eventOpenAPSUpdateGui.getFrom()), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventExtendedBolusChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempBasalChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventTempBasalChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTreatmentChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventTreatmentChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempTargetChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventTempTargetChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPumpStatusChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updatePumpStatus(event.getStatus()), + FabricPrivacy::logException + )); sRefreshLoop = () -> { scheduleUpdateGUI("refreshLoop"); sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); @@ -881,36 +927,16 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, scheduleUpdateGUI("EventPreferenceChange"); } - @Subscribe - public void onStatusEvent(final EventRefreshOverview ev) { - scheduleUpdateGUI(ev.from); - } - @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { scheduleUpdateGUI("EventAutosensCalculationFinished"); } - @Subscribe - public void onStatusEvent(final EventTreatmentChange ev) { - scheduleUpdateGUI("EventTreatmentChange"); - } - @Subscribe public void onStatusEvent(final EventCareportalEventChange ev) { scheduleUpdateGUI("EventCareportalEventChange"); } - @Subscribe - public void onStatusEvent(final EventTempBasalChange ev) { - scheduleUpdateGUI("EventTempBasalChange"); - } - - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - scheduleUpdateGUI("EventExtendedBolusChange"); - } - @Subscribe public void onStatusEvent(final EventNewOpenLoopNotification ev) { scheduleUpdateGUI("EventNewOpenLoopNotification"); @@ -921,23 +947,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, scheduleUpdateGUI("EventAcceptOpenLoopChange"); } - @Subscribe - public void onStatusEvent(final EventTempTargetChange ev) { - scheduleUpdateGUI("EventTempTargetChange"); - } - @Subscribe public void onStatusEvent(final EventProfileNeedsUpdate ev) { scheduleUpdateGUI("EventProfileNeedsUpdate"); } - @Subscribe - public void onStatusEvent(final EventPumpStatusChanged s) { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> updatePumpStatus(s.textStatus())); - } - @Subscribe public void onStatusEvent(final EventIobCalculationProgress e) { Activity activity = getActivity(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 0c5b3b4370..cece359f22 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -45,7 +45,7 @@ object OverviewPlugin : PluginBase(PluginDescription() .observeOn(Schedulers.io()) .subscribe({ n -> if (notificationStore.add(n.notification)) - MainApp.bus().post(EventRefreshOverview("EventNewNotification")) + RxBus.send(EventRefreshOverview("EventNewNotification")) }, { FabricPrivacy.logException(it) }) @@ -54,7 +54,7 @@ object OverviewPlugin : PluginBase(PluginDescription() .observeOn(Schedulers.io()) .subscribe({ n -> if (notificationStore.remove(n.id)) - MainApp.bus().post(EventRefreshOverview("EventDismissNotification")) + RxBus.send(EventRefreshOverview("EventDismissNotification")) }, { FabricPrivacy.logException(it) }) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java index 04da9761a3..35c8edd656 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java @@ -23,12 +23,18 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; 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 io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class BolusProgressDialog extends DialogFragment implements View.OnClickListener { private static Logger log = LoggerFactory.getLogger(L.UI); + private CompositeDisposable disposable = new CompositeDisposable(); + Button stopButton; TextView statusView; TextView stopPressedView; @@ -91,11 +97,12 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL if (L.isEnabled(L.UI)) log.debug("onResume running"); } - try { - MainApp.bus().register(this); - } catch (IllegalArgumentException e) { - log.error("Already registered"); - } + disposable.add(RxBus.INSTANCE + .toObservable(EventPumpStatusChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) + ); + MainApp.bus().register(this); } @Override @@ -121,11 +128,8 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL log.debug("onPause"); running = false; super.onPause(); - try { - MainApp.bus().unregister(this); - } catch (IllegalArgumentException e) { - log.error("Already unregistered"); - } + MainApp.bus().unregister(this); + disposable.clear(); } @Override @@ -176,16 +180,6 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL } } - @Subscribe - public void onStatusEvent(final EventPumpStatusChanged c) { - if (L.isEnabled(L.UI)) - log.debug("EventPumpStatusChanged"); - Activity activity = getActivity(); - if (activity != null) { - activity.runOnUiThread(() -> statusView.setText(c.textStatus())); - } - } - private void scheduleDismiss() { if (L.isEnabled(L.UI)) log.debug("scheduleDismiss"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java index 655435f400..dd9ff00c4c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java @@ -17,8 +17,6 @@ import androidx.core.app.TaskStackBuilder; import com.squareup.otto.Subscribe; -import javax.annotation.Nonnull; - import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -37,6 +35,7 @@ import info.nightscout.androidaps.events.EventTreatmentChange; 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.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; @@ -44,6 +43,9 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by adrian on 23/12/16. @@ -51,6 +53,8 @@ import info.nightscout.androidaps.utils.DecimalFormatter; public class PersistentNotificationPlugin extends PluginBase { + private CompositeDisposable disposable = new CompositeDisposable(); + private static PersistentNotificationPlugin plugin; private Notification notification; @@ -92,6 +96,30 @@ public class PersistentNotificationPlugin extends PluginBase { super.onStart(); createNotificationChannel(); // make sure channels exist before triggering updates through the bus MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventRefreshOverview.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempBasalChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTreatmentChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); triggerNotificationUpdate(true); } @@ -110,6 +138,7 @@ public class PersistentNotificationPlugin extends PluginBase { @Override protected void onStop() { MainApp.bus().unregister(this); + disposable.clear(); MainApp.instance().stopService(new Intent(MainApp.instance(), DummyService.class)); super.onStop(); } @@ -292,21 +321,6 @@ public class PersistentNotificationPlugin extends PluginBase { triggerNotificationUpdate(false); } - @Subscribe - public void onStatusEvent(final EventTreatmentChange ev) { - triggerNotificationUpdate(false); - } - - @Subscribe - public void onStatusEvent(final EventTempBasalChange ev) { - triggerNotificationUpdate(false); - } - - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - triggerNotificationUpdate(false); - } - @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { triggerNotificationUpdate(false); @@ -322,9 +336,4 @@ public class PersistentNotificationPlugin extends PluginBase { triggerNotificationUpdate(false); } - @Subscribe - public void onStatusEvent(final EventRefreshOverview ev) { - triggerNotificationUpdate(false); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java index d1494e6033..8cc81a901a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java @@ -309,7 +309,7 @@ public class SmsCommunicatorPlugin extends PluginBase { ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { @Override public void run() { - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP")); + RxBus.INSTANCE.send(new EventRefreshOverview("SMS_LOOP_STOP")); String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " + MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); sendSMS(new Sms(receivedSms.phoneNumber, reply)); @@ -326,7 +326,7 @@ public class SmsCommunicatorPlugin extends PluginBase { if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.setPluginEnabled(PluginType.LOOP, true); sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loophasbeenenabled)); - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START")); + RxBus.INSTANCE.send(new EventRefreshOverview("SMS_LOOP_START")); } else { sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisenabled)); } @@ -349,7 +349,7 @@ public class SmsCommunicatorPlugin extends PluginBase { break; case "RESUME": LoopPlugin.getPlugin().suspendTo(0); - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME")); + RxBus.INSTANCE.send(new EventRefreshOverview("SMS_LOOP_RESUME")); NSUpload.uploadOpenAPSOffline(0); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopresumed)); break; @@ -376,7 +376,7 @@ public class SmsCommunicatorPlugin extends PluginBase { if (result.success) { LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + anInteger * 60L * 1000); NSUpload.uploadOpenAPSOffline(anInteger * 60); - MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED")); + RxBus.INSTANCE.send(new EventRefreshOverview("SMS_LOOP_SUSPENDED")); String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " + MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed); sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java index 53b421ace3..d74643cd14 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java @@ -82,7 +82,34 @@ public class WearPlugin extends PluginBase { .toObservable(EventOpenAPSUpdateGui.class) .observeOn(Schedulers.io()) .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), - error -> FabricPrivacy.logException(error) + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(Schedulers.io()) + .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempBasalChange.class) + .observeOn(Schedulers.io()) + .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTreatmentChange.class) + .observeOn(Schedulers.io()) + .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventRefreshOverview.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) + sendDataToWatch(true, false, false); + }, + FabricPrivacy::logException )); } @@ -142,21 +169,6 @@ public class WearPlugin extends PluginBase { sendDataToWatch(true, false, false); } - @Subscribe - public void onStatusEvent(final EventTreatmentChange ev) { - sendDataToWatch(true, true, false); - } - - @Subscribe - public void onStatusEvent(final EventTempBasalChange ev) { - sendDataToWatch(true, true, false); - } - - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - sendDataToWatch(true, true, false); - } - @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { sendDataToWatch(true, true, true); @@ -167,14 +179,6 @@ public class WearPlugin extends PluginBase { sendDataToWatch(false, true, false); } - @Subscribe - public void onStatusEvent(final EventRefreshOverview ev) { - if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) { - sendDataToWatch(true, false, false); - } - } - - @Subscribe public void onStatusEvent(final EventOverviewBolusProgress ev) { if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index 2421a1561e..2f219de651 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -5,6 +5,7 @@ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; + import androidx.annotation.NonNull; import com.squareup.otto.Subscribe; @@ -26,12 +27,16 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by adrian on 17/11/16. @@ -39,6 +44,8 @@ import info.nightscout.androidaps.utils.DecimalFormatter; public class StatuslinePlugin extends PluginBase { + private CompositeDisposable disposable = new CompositeDisposable(); + private static StatuslinePlugin statuslinePlugin; public static StatuslinePlugin getPlugin() { @@ -80,14 +87,42 @@ public class StatuslinePlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); super.onStart(); + MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventRefreshOverview.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if ((lastLoopStatus != LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) + sendStatus(); + }, + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempBasalChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTreatmentChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); } @Override protected void onStop() { super.onStop(); MainApp.bus().unregister(this); + disposable.clear(); sendStatus(); } @@ -166,21 +201,6 @@ public class StatuslinePlugin extends PluginBase { sendStatus(); } - @Subscribe - public void onStatusEvent(final EventTreatmentChange ev) { - sendStatus(); - } - - @Subscribe - public void onStatusEvent(final EventTempBasalChange ev) { - sendStatus(); - } - - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - sendStatus(); - } - @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { sendStatus(); @@ -196,12 +216,4 @@ public class StatuslinePlugin extends PluginBase { sendStatus(); } - @Subscribe - public void onStatusEvent(final EventRefreshOverview ev) { - //Filter events where loop is (de)activated - if ((lastLoopStatus != LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) { - sendStatus(); - } - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 7058252eb3..affbf49465 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -376,6 +376,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint pump.initialized = true; MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); // show notification to check pump date if last bolus is older than 24 hours // or is in the future diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt index b01bb22104..f6eb1c3069 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt @@ -87,6 +87,30 @@ class DanaRFragment : Fragment() { .toObservable(EventDanaRNewStatus::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(EventPumpStatusChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ + when { + it.sStatus == EventPumpStatusChanged.Status.CONNECTING -> danar_btconnection?.text = "{fa-bluetooth-b spin} " + it.sSecondsElapsed + "s" + it.sStatus == EventPumpStatusChanged.Status.CONNECTED -> danar_btconnection?.text = "{fa-bluetooth}" + it.sStatus == EventPumpStatusChanged.Status.DISCONNECTED -> danar_btconnection?.text = "{fa-bluetooth-b}" + } + if (it.getStatus() != "") { + dana_pumpstatus?.text = it.getStatus() + dana_pumpstatuslayout?.visibility = View.VISIBLE + } else { + dana_pumpstatuslayout?.visibility = View.GONE + } + }, { FabricPrivacy.logException(it) }) updateGUI() } @@ -98,33 +122,6 @@ class DanaRFragment : Fragment() { loopHandler.removeCallbacks(refreshLoop) } - @Subscribe - fun onStatusEvent(c: EventPumpStatusChanged) { - activity?.runOnUiThread { - when { - c.sStatus == EventPumpStatusChanged.CONNECTING -> danar_btconnection?.text = "{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s" - c.sStatus == EventPumpStatusChanged.CONNECTED -> danar_btconnection?.text = "{fa-bluetooth}" - c.sStatus == EventPumpStatusChanged.DISCONNECTED -> danar_btconnection?.text = "{fa-bluetooth-b}" - } - if (c.textStatus() != "") { - dana_pumpstatus?.text = c.textStatus() - dana_pumpstatuslayout?.visibility = View.VISIBLE - } else { - dana_pumpstatuslayout?.visibility = View.GONE - } - } - - } - - @Subscribe - fun onStatusEvent(s: EventTempBasalChange) = - activity?.runOnUiThread { updateGUI() } - - - @Subscribe - fun onStatusEvent(s: EventExtendedBolusChange) = - activity?.runOnUiThread { updateGUI() } - @Subscribe fun onStatusEvent(s: EventQueueChanged) = activity?.runOnUiThread { updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java index 2d31510e71..a5f99def77 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java @@ -32,6 +32,7 @@ import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; @@ -41,10 +42,14 @@ import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.ToastUtils; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class DanaRHistoryActivity extends NoSplashActivity { private static Logger log = LoggerFactory.getLogger(L.PUMP); + private CompositeDisposable disposable = new CompositeDisposable(); static Profile profile = null; @@ -82,12 +87,18 @@ public class DanaRHistoryActivity extends NoSplashActivity { protected void onResume() { super.onResume(); MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventPumpStatusChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) + ); } @Override protected void onPause() { super.onPause(); MainApp.bus().unregister(this); + disposable.clear(); } @Override @@ -325,12 +336,4 @@ public class DanaRHistoryActivity extends NoSplashActivity { () -> statusView.setText(s.message)); } - @Subscribe - public void onStatusEvent(final EventPumpStatusChanged s) { - runOnUiThread( - () -> statusView.setText(s.textStatus()) - ); - } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java index 9e3c1ff3ca..839debe9be 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java @@ -23,6 +23,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStop; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgHistoryAlarm; @@ -105,7 +106,7 @@ public abstract class AbstractDanaRExecutionService extends Service { if (mSerialIOThread != null) { mSerialIOThread.disconnect("BT disconnection broadcast"); } - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); } } } @@ -135,7 +136,7 @@ public abstract class AbstractDanaRExecutionService extends Service { public void finishHandshaking() { mHandshakeInProgress = false; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED, 0)); } public void disconnect(String from) { @@ -243,7 +244,7 @@ public abstract class AbstractDanaRExecutionService extends Service { long timeToWholeMinute = (60000 - time % 60000); if (timeToWholeMinute > 59800 || timeToWholeMinute < 3000) break; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); SystemClock.sleep(Math.min(timeToWholeMinute, 100)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index f623f292aa..b30da3f004 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -127,7 +127,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } mSerialIOThread = new SerialIOThread(mRfcommSocket, MessageHashTableR.INSTANCE); mHandshakeInProgress = true; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, 0)); } mConnectionInProgress = false; @@ -137,7 +137,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public void getPumpStatus() { DanaRPump danaRPump = DanaRPump.getInstance(); try { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); MsgStatus statusMsg = new MsgStatus(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); @@ -153,11 +153,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusBasicMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); mSerialIOThread.sendMessage(tempStatusMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); mSerialIOThread.sendMessage(exStatusMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); long now = System.currentTimeMillis(); danaRPump.lastConnection = now; @@ -165,15 +165,15 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); } } if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingShippingInfo()); mSerialIOThread.sendMessage(new MsgSettingActiveProfile()); mSerialIOThread.sendMessage(new MsgSettingMeal()); @@ -185,7 +185,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSettingProfileRatios()); mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll()); mSerialIOThread.sendMessage(new MsgSettingUserOptions()); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); if (danaRPump.pumpTime == 0) { // initial handshake was not successfull @@ -194,6 +194,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { danaRPump.lastSettingsRead = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); return; } long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L; @@ -211,6 +212,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { if (L.isEnabled(L.PUMP)) @@ -231,41 +233,41 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; if (danaRPump.isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean tempBasalStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolusStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -395,7 +397,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); mSerialIOThread.sendMessage(msgSet); @@ -403,7 +405,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(msgActivate); danaRPump.lastSettingsRead = 0; // force read full settings getPumpStatus(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index 6a10ffd7f6..9f59beb096 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -132,7 +132,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { } mSerialIOThread = new SerialIOThread(mRfcommSocket, MessageHashTableRkorean.INSTANCE); mHandshakeInProgress = true; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, 0)); } mConnectionInProgress = false; @@ -142,7 +142,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public void getPumpStatus() { DanaRPump danaRPump = DanaRPump.getInstance(); try { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); //MsgStatus_k statusMsg = new MsgStatus_k(); MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(); @@ -158,11 +158,11 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { //mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusBasicMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); mSerialIOThread.sendMessage(tempStatusMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); mSerialIOThread.sendMessage(exStatusMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); long now = System.currentTimeMillis(); danaRPump.lastConnection = now; @@ -170,7 +170,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { MainApp.bus().post(new EventProfileNeedsUpdate()); @@ -178,7 +178,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { } if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingShippingInfo()); mSerialIOThread.sendMessage(new MsgSettingMeal()); mSerialIOThread.sendMessage(new MsgSettingBasal_k()); @@ -186,7 +186,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSettingMaxValues()); mSerialIOThread.sendMessage(new MsgSettingGlucose()); mSerialIOThread.sendMessage(new MsgSettingProfileRatios()); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); if (danaRPump.pumpTime == 0) { // initial handshake was not successfull @@ -195,6 +195,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { danaRPump.lastSettingsRead = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); return; } long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L; @@ -214,6 +215,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { if (L.isEnabled(L.PUMP)) @@ -234,41 +236,41 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; if (danaRPump.isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean tempBasalStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgStatusTempBasal()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolusStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended()); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -336,13 +338,13 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal); mSerialIOThread.sendMessage(msgSet); danaRPump.lastSettingsRead = 0; // force read full settings getPumpStatus(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java index 6723e5a0a2..fde34c58e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; @@ -223,7 +224,7 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet { if (datetime > lastEventTimeLoaded) lastEventTimeLoaded = datetime; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status)); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java index 3ce5c49a1e..20ce8f485b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java @@ -339,7 +339,7 @@ public class BLEComm { close(); isConnected = false; isConnecting = false; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); if (L.isEnabled(L.PUMPBTCOMM)) log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected } @@ -452,7 +452,7 @@ public class BLEComm { if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer)); mSendQueue.clear(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumperror))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumperror))); NSUpload.uploadError(MainApp.gs(R.string.pumperror)); Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT); RxBus.INSTANCE.send(new EventNewNotification(n)); @@ -460,13 +460,13 @@ public class BLEComm { if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer)); mSendQueue.clear(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumpbusy))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumpbusy))); } else { // ERROR in response, wrong serial number if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer)); mSendQueue.clear(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.connectionerror))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.connectionerror))); SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName); Notification n = new Notification(Notification.WRONGSERIALNUMBER, MainApp.gs(R.string.wrongpassword), Notification.URGENT); RxBus.INSTANCE.send(new EventNewNotification(n)); @@ -515,7 +515,7 @@ public class BLEComm { if (L.isEnabled(L.PUMPBTCOMM)) log.debug("Pump user password: " + Integer.toHexString(pass)); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED)); isConnected = true; isConnecting = false; if (L.isEnabled(L.PUMPBTCOMM)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index 4c46f80de7..8da728692b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -132,14 +132,14 @@ public class DanaRSService extends Service { public void getPumpStatus() { DanaRPump danaRPump = DanaRPump.getInstance(); try { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); bleComm.sendMessage(new DanaRS_Packet_General_Initial_Screen_Information()); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State()); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // last bolus, bolusStep, maxBolus - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State()); danaRPump.lastConnection = System.currentTimeMillis(); @@ -147,14 +147,14 @@ public class DanaRSService extends Service { Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate()); // basal profile, basalStep, maxBasal if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { MainApp.bus().post(new EventProfileNeedsUpdate()); } } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time()); long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L; @@ -164,6 +164,7 @@ public class DanaRSService extends Service { danaRPump.lastConnection = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); return; } if (L.isEnabled(L.PUMPCOMM)) @@ -184,6 +185,7 @@ public class DanaRSService extends Service { danaRPump.lastConnection = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); return; } else { waitForWholeMinute(); // Dana can set only whole minute @@ -198,7 +200,7 @@ public class DanaRSService extends Service { long now = System.currentTimeMillis(); if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); bleComm.sendMessage(new DanaRS_Packet_General_Get_Shipping_Information()); // serial no bleComm.sendMessage(new DanaRS_Packet_General_Get_Pump_Check()); // firmware bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Profile_Number()); @@ -214,6 +216,7 @@ public class DanaRSService extends Service { MainApp.bus().post(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { if (L.isEnabled(L.PUMPCOMM)) @@ -278,7 +281,7 @@ public class DanaRSService extends Service { if (!isConnected()) return false; if (BolusProgressDialog.stopPressed) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus))); bolusingTreatment = t; final int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); DanaRS_Packet_Bolus_Set_Step_Bolus_Start start = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(insulin, preferencesSpeed); @@ -344,10 +347,10 @@ public class DanaRSService extends Service { @Override public void run() { // reread bolus status - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // last bolus bolusingEvent.percent = 100; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting))); } }); return !start.failed; @@ -372,30 +375,30 @@ public class DanaRSService extends Service { public boolean tempBasal(Integer percent, int durationInHours) { if (!isConnected()) return false; if (DanaRPump.getInstance().isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Temporary_Basal(percent, durationInHours)); SystemClock.sleep(200); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean highTempBasal(Integer percent) { if (DanaRPump.getInstance().isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(percent)); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -406,52 +409,52 @@ public class DanaRSService extends Service { } if (DanaRPump.getInstance().isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(percent, durationInMinutes == 15, durationInMinutes == 30)); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean tempBasalStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal()); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolus(Double insulin, int durationInHalfHours) { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus(insulin, durationInHalfHours)); SystemClock.sleep(200); bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolusStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel()); bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean updateBasalsInPump(Profile profile) { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(0, basal); bleComm.sendMessage(msgSet); @@ -459,7 +462,7 @@ public class DanaRSService extends Service { bleComm.sendMessage(msgActivate); DanaRPump.getInstance().lastSettingsRead = 0; // force read full settings getPumpStatus(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -543,7 +546,7 @@ public class DanaRSService extends Service { long timeToWholeMinute = (60000 - time % 60000); if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); SystemClock.sleep(Math.min(timeToWholeMinute, 100)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java index 43ec35702f..3ef43cad86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java @@ -13,6 +13,7 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase; @@ -199,6 +200,6 @@ public class MsgHistoryEvents_v2 extends MessageBase { if (datetime > lastEventTimeLoaded) lastEventTimeLoaded = datetime; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 2721ec7ff8..3be2f16c73 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -150,7 +150,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } mSerialIOThread = new SerialIOThread(mRfcommSocket, MessageHashTableRv2.INSTANCE); mHandshakeInProgress = true; - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, 0)); } mConnectionInProgress = false; @@ -160,7 +160,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public void getPumpStatus() { DanaRPump danaRPump = DanaRPump.getInstance(); try { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus))); MsgStatus statusMsg = new MsgStatus(); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(); MsgStatusTempBasal_v2 tempStatusMsg = new MsgStatusTempBasal_v2(); @@ -174,12 +174,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); mSerialIOThread.sendMessage(statusMsg); mSerialIOThread.sendMessage(statusBasicMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus))); mSerialIOThread.sendMessage(tempStatusMsg); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus))); mSerialIOThread.sendMessage(exStatusMsg); danaRPump.lastConnection = System.currentTimeMillis(); @@ -187,14 +187,14 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { Profile profile = ProfileFunctions.getInstance().getProfile(); PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { MainApp.bus().post(new EventProfileNeedsUpdate()); } } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime))); mSerialIOThread.sendMessage(new MsgSettingPumpTime()); if (danaRPump.pumpTime == 0) { // initial handshake was not successfull @@ -203,6 +203,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { danaRPump.lastSettingsRead = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); return; } long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L; @@ -224,6 +225,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { danaRPump.lastConnection = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); return; } else { waitForWholeMinute(); // Dana can set only whole minute @@ -238,7 +240,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { long now = System.currentTimeMillis(); if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingShippingInfo()); mSerialIOThread.sendMessage(new MsgSettingActiveProfile()); mSerialIOThread.sendMessage(new MsgSettingMeal()); @@ -257,6 +259,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { RxBus.INSTANCE.send(new EventDanaRNewStatus()); MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { if (L.isEnabled(L.PUMP)) @@ -277,15 +280,15 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; if (danaRPump.isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours)); mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -293,15 +296,15 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; if (danaRPump.isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(percent)); mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -314,45 +317,45 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; if (danaRPump.isTempBasalInProgress) { - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); SystemClock.sleep(500); } - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(percent, durationInMinutes == 15, durationInMinutes == 30)); mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean tempBasalStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop()); mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolus(double insulin, int durationInHalfHours) { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF))); mSerialIOThread.sendMessage(new MsgStatusBolusExtended_v2()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } public boolean extendedBolusStop() { if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop()); mSerialIOThread.sendMessage(new MsgStatusBolusExtended_v2()); loadEvents(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -360,7 +363,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; if (BolusProgressDialog.stopPressed) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus))); mBolusingTreatment = t; final int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0); MessageBase start; @@ -428,10 +431,10 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Override public void run() { // load last bolus status - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); mSerialIOThread.sendMessage(new MsgStatus()); bolusingEvent.percent = 100; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting))); } }); return !start.failed; @@ -496,7 +499,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { public boolean updateBasalsInPump(final Profile profile) { DanaRPump danaRPump = DanaRPump.getInstance(); if (!isConnected()) return false; - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates))); double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile); MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal); mSerialIOThread.sendMessage(msgSet); @@ -504,7 +507,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(msgActivate); danaRPump.lastSettingsRead = 0; // force read full settings getPumpStatus(); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 087e9e8d7a..2977b306f4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -147,8 +147,10 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } else if (binder instanceof InsightAlertService.LocalBinder) { alertService = ((InsightAlertService.LocalBinder) binder).getService(); } - if (connectionService != null && alertService != null) + if (connectionService != null && alertService != null) { MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventInitializationChanged()); + } } @Override @@ -424,7 +426,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con lastUpdated = System.currentTimeMillis(); new Handler(Looper.getMainLooper()).post(() -> { MainApp.bus().post(new EventLocalInsightUpdateGUI()); - MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::fetchStatus")); + RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::fetchStatus")); }); } @@ -1164,7 +1166,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } catch (Exception e) { log.error("Exception while reading history", e); } - new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::readHistory"))); + new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::readHistory"))); } private void processHistoryEvents(String serial, List historyEvents) { @@ -1599,7 +1601,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con activeTBR = null; activeBoluses = null; tbrOverNotificationBlock = null; - new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); + new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); } new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventLocalInsightUpdateGUI())); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index d60a639106..9999bed27f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -122,6 +122,14 @@ class MedtronicFragment : Fragment() { .toObservable(EventMedtronicPumpValuesChanged::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(EventMedtronicPumpConfigurationChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) @@ -131,6 +139,10 @@ class MedtronicFragment : Fragment() { MedtronicUtil.getPumpStatus().verifyConfiguration() updateGUI() }, { FabricPrivacy.logException(it) }) + disposable += RxBus + .toObservable(EventPumpStatusChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) }) updateGUI() } @@ -143,21 +155,6 @@ class MedtronicFragment : Fragment() { loopHandler.removeCallbacks(refreshLoop) } - @Subscribe - fun onStatusEvent(c: EventPumpStatusChanged) { - activity?.runOnUiThread { updateGUI() } - } - - @Subscribe - fun onStatusEvent(s: EventTempBasalChange) { - activity?.runOnUiThread { updateGUI() } - } - - @Subscribe - fun onStatusEvent(s: EventExtendedBolusChange) { - activity?.runOnUiThread { updateGUI() } - } - @Subscribe fun onStatusEvent(s: EventQueueChanged) { activity?.runOnUiThread { updateGUI() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index cd5066d645..ae6d754493 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -1080,7 +1080,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private void finishAction(String overviewKey) { if (overviewKey != null) - MainApp.bus().post(new EventRefreshOverview(overviewKey)); + RxBus.INSTANCE.send(new EventRefreshOverview(overviewKey)); triggerUIChange(); @@ -1603,7 +1603,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter } private void refreshCustomActionsList() { - MainApp.bus().post(new EventCustomActionsChanged()); + RxBus.INSTANCE.send(new EventCustomActionsChanged()); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 309191fdc0..389968eebe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -38,6 +38,7 @@ import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.utils.JsonHelper; @@ -181,6 +182,7 @@ public class TreatmentService extends OrmLiteBaseService { if (L.isEnabled(L.DATATREATMENTS)) log.debug("Firing EventReloadTreatmentData"); MainApp.bus().post(event); + RxBus.INSTANCE.send(event); if (DatabaseHelper.earliestDataChange != null) { if (L.isEnabled(L.DATATREATMENTS)) log.debug("Firing EventNewHistoryData"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java index 192952057d..731042c237 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java @@ -1,19 +1,18 @@ package info.nightscout.androidaps.plugins.treatments; import android.os.Bundle; -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentTransaction; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment; import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment; @@ -22,8 +21,12 @@ import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfile import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment; import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment; import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; + +public class TreatmentsFragment extends Fragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); -public class TreatmentsFragment extends SubscriberFragment implements View.OnClickListener { TextView treatmentsTab; TextView extendedBolusesTab; TextView tempBasalsTab; @@ -34,32 +37,42 @@ public class TreatmentsFragment extends SubscriberFragment implements View.OnCli @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.treatments_fragment, container, false); + View view = inflater.inflate(R.layout.treatments_fragment, container, false); - treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments); - extendedBolusesTab = (TextView) view.findViewById(R.id.treatments_extendedboluses); - tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals); - tempTargetTab = (TextView) view.findViewById(R.id.treatments_temptargets); - profileSwitchTab = (TextView) view.findViewById(R.id.treatments_profileswitches); - careportalTab = (TextView) view.findViewById(R.id.treatments_careportal); - treatmentsTab.setOnClickListener(this); - extendedBolusesTab.setOnClickListener(this); - tempBasalsTab.setOnClickListener(this); - tempTargetTab.setOnClickListener(this); - profileSwitchTab.setOnClickListener(this); - careportalTab.setOnClickListener(this); + treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments); + extendedBolusesTab = (TextView) view.findViewById(R.id.treatments_extendedboluses); + tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals); + tempTargetTab = (TextView) view.findViewById(R.id.treatments_temptargets); + profileSwitchTab = (TextView) view.findViewById(R.id.treatments_profileswitches); + careportalTab = (TextView) view.findViewById(R.id.treatments_careportal); + treatmentsTab.setOnClickListener(this); + extendedBolusesTab.setOnClickListener(this); + tempBasalsTab.setOnClickListener(this); + tempTargetTab.setOnClickListener(this); + profileSwitchTab.setOnClickListener(this); + careportalTab.setOnClickListener(this); - setFragment(new TreatmentsBolusFragment()); - setBackgroundColorOnSelected(treatmentsTab); + setFragment(new TreatmentsBolusFragment()); + setBackgroundColorOnSelected(treatmentsTab); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } + return view; + } - return null; + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } @Override @@ -111,13 +124,7 @@ public class TreatmentsFragment extends SubscriberFragment implements View.OnCli selected.setBackgroundColor(MainApp.gc(R.color.tabBgColorSelected)); } - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - updateGUI(); - } - - @Override - protected void updateGUI() { + private void updateGui() { if (ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().isExtendedBolusCapable || TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory().size() > 0) { extendedBolusesTab.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 195005e87a..faa32b0638 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -6,7 +6,6 @@ import android.os.Bundle; import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -59,6 +58,8 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 05.08.2016. @@ -66,6 +67,8 @@ import info.nightscout.androidaps.utils.T; public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface { private Logger log = LoggerFactory.getLogger(L.DATATREATMENTS); + private CompositeDisposable disposable = new CompositeDisposable(); + private static TreatmentsPlugin treatmentsPlugin; public static TreatmentsPlugin getPlugin() { @@ -106,11 +109,48 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface initializeTempTargetData(); initializeProfileSwitchData(); super.onStart(); + disposable.add(RxBus.INSTANCE + .toObservable(EventReloadTreatmentData.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("EventReloadTreatmentData"); + initializeTreatmentData(); + initializeExtendedBolusData(); + updateTotalIOBTreatments(); + RxBus.INSTANCE.send(event.getNext()); + }, + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventReloadProfileSwitchData.class) + .observeOn(Schedulers.io()) + .subscribe(event -> initializeProfileSwitchData(), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempTargetChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> initializeTempTargetData(), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventReloadTempBasalData.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.DATATREATMENTS)) + log.debug("EventReloadTempBasalData"); + initializeTempBasalData(); + updateTotalIOBTempBasals(); + }, + FabricPrivacy::logException + )); } @Override protected void onStop() { MainApp.bus().register(this); + disposable.clear(); super.onStop(); } @@ -387,25 +427,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return getExtendedBolusFromHistory(System.currentTimeMillis()) != null; //TODO: crosscheck here } - @Subscribe - public void onStatusEvent(final EventReloadTreatmentData ev) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("EventReloadTreatmentData"); - initializeTreatmentData(); - initializeExtendedBolusData(); - updateTotalIOBTreatments(); - MainApp.bus().post(ev.next); - } - - @Subscribe - @SuppressWarnings("unused") - public void onStatusEvent(final EventReloadTempBasalData ev) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("EventReloadTempBasalData"); - initializeTempBasalData(); - updateTotalIOBTempBasals(); - } - @Override public IobTotal getLastCalculationTempBasals() { return lastTempBasalsCalculation; @@ -681,13 +702,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return oldestTime; } - // TempTargets - @Subscribe - @SuppressWarnings("unused") - public void onStatusEvent(final EventTempTargetChange ev) { - initializeTempTargetData(); - } - @Nullable @Override public TempTarget getTempTargetFromHistory() { @@ -718,13 +732,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface NSUpload.uploadTempTarget(tempTarget); } - // Profile Switch - @Subscribe - @SuppressWarnings("unused") - public void onStatusEvent(final EventReloadProfileSwitchData ev) { - initializeProfileSwitchData(); - } - @Override @Nullable public ProfileSwitch getProfileSwitchFromHistory(long time) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java index 556d80f321..81cfcd16a9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java @@ -14,6 +14,7 @@ import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.cardview.widget.CardView; import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -28,7 +29,7 @@ import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventTreatmentChange; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; @@ -39,11 +40,16 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.dialogs.WizardInfoDialog; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; import static info.nightscout.androidaps.utils.DateUtil.now; -public class TreatmentsBolusFragment extends SubscriberFragment implements View.OnClickListener { +public class TreatmentsBolusFragment extends Fragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); + RecyclerView recyclerView; LinearLayoutManager llm; @@ -162,7 +168,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. } TreatmentsPlugin.getPlugin().getService().delete(treatment); } - updateGUI(); + updateGui(); } }); builder.setNegativeButton(MainApp.gs(R.string.cancel), null); @@ -213,7 +219,6 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. context = getContext(); - updateGUI(); return view; } @@ -248,7 +253,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. } TreatmentsPlugin.getPlugin().getService().delete(treatment); } - updateGUI(); + updateGui(); }); builder.setNegativeButton(MainApp.gs(R.string.cancel), null); builder.show(); @@ -256,18 +261,29 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View. } } - @Subscribe - public void onStatusEvent(final EventTreatmentChange ev) { - updateGUI(); + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventTreatmentChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { - updateGUI(); + updateGui(); } - @Override - protected void updateGUI() { + private void updateGui() { Activity activity = getActivity(); if (activity != null) activity.runOnUiThread(() -> { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java index 24a5185ef0..e148ab7cad 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -5,16 +5,18 @@ import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; import android.os.Bundle; -import androidx.core.content.ContextCompat; -import androidx.appcompat.app.AlertDialog; -import androidx.cardview.widget.CardView; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import androidx.appcompat.app.AlertDialog; +import androidx.cardview.widget.CardView; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + import com.squareup.otto.Subscribe; import info.nightscout.androidaps.MainApp; @@ -24,16 +26,21 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventExtendedBolusChange; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; -public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { +public class TreatmentsExtendedBolusesFragment extends Fragment { + private CompositeDisposable disposable = new CompositeDisposable(); + RecyclerView recyclerView; LinearLayoutManager llm; @@ -173,30 +180,35 @@ public class TreatmentsExtendedBolusesFragment extends SubscriberFragment { context = getContext(); - updateGUI(); return view; } - @Subscribe - public void onStatusEvent(final EventExtendedBolusChange ev) { - updateGUI(); + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ev) { - updateGUI(); + updateGui(); } - @Override - protected void updateGUI() { + private void updateGui() { Activity activity = getActivity(); if (activity != null && recyclerView != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory()), false); - } - }); + activity.runOnUiThread(() -> recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory()), false)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java index 3c17e7b762..9aba0a3c9d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java @@ -14,18 +14,17 @@ import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.cardview.widget.CardView; import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventTempTargetChange; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; @@ -33,13 +32,17 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; /** * Created by mike on 13/01/17. */ -public class TreatmentsTempTargetFragment extends SubscriberFragment implements View.OnClickListener { +public class TreatmentsTempTargetFragment extends Fragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); RecyclerView recyclerView; LinearLayoutManager llm; @@ -184,10 +187,26 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements if (nsUploadOnly) refreshFromNS.setVisibility(View.GONE); - updateGUI(); return view; } + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempTargetChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + @Override public void onClick(View view) { switch (view.getId()) { @@ -208,20 +227,7 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements } - @Subscribe - public void onStatusEvent(final EventTempTargetChange ev) { - updateGUI(); - } - - @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTempTargetsFromHistory()), false); - } - }); + private void updateGui() { + recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTempTargetsFromHistory()), false); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 6aed7aea43..59f2fa69c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -4,17 +4,19 @@ import android.app.Activity; import android.content.Context; import android.graphics.Paint; import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; -import androidx.appcompat.app.AlertDialog; -import androidx.cardview.widget.CardView; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.cardview.widget.CardView; +import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + import com.squareup.otto.Subscribe; import info.nightscout.androidaps.MainApp; @@ -25,7 +27,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventTempBasalChange; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; @@ -33,9 +35,14 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutos import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; -public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { +public class TreatmentsTemporaryBasalsFragment extends Fragment { + private CompositeDisposable disposable = new CompositeDisposable(); + RecyclerView recyclerView; LinearLayoutManager llm; @@ -199,22 +206,32 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment { context = getContext(); - updateGUI(); return view; } - @Subscribe - public void onStatusEvent(final EventTempBasalChange ignored) { - updateGUI(); + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempBasalChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } @Subscribe public void onStatusEvent(final EventAutosensCalculationFinished ignored) { - updateGUI(); + updateGui(); } - @Override - protected void updateGUI() { + private void updateGui() { Activity activity = getActivity(); if (activity != null) activity.runOnUiThread(() -> { diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index 59eaf6471e..7016c217dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -14,6 +14,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning; import info.nightscout.androidaps.queue.events.EventQueueChanged; @@ -60,7 +61,7 @@ public class QueueThread extends Thread { if (pump == null) { if (L.isEnabled(L.PUMPQUEUE)) log.debug("pump == null"); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.pumpNotInitialized))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.pumpNotInitialized))); SystemClock.sleep(1000); continue; } @@ -68,7 +69,7 @@ public class QueueThread extends Thread { if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { MainApp.bus().post(new EventDismissBolusprogressIfRunning(null)); - MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout))); + RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout))); if (L.isEnabled(L.PUMPQUEUE)) log.debug("timed out"); pump.stopConnecting(); @@ -100,9 +101,9 @@ public class QueueThread extends Thread { queue.clear(); if (L.isEnabled(L.PUMPQUEUE)) log.debug("no connection possible"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); pump.disconnect("Queue empty"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); return; } } @@ -110,7 +111,7 @@ public class QueueThread extends Thread { if (pump.isHandshakeInProgress()) { if (L.isEnabled(L.PUMPQUEUE)) log.debug("handshaking " + secondsElapsed); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, (int) secondsElapsed)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, (int) secondsElapsed)); SystemClock.sleep(100); continue; } @@ -118,7 +119,7 @@ public class QueueThread extends Thread { if (pump.isConnecting()) { if (L.isEnabled(L.PUMPQUEUE)) log.debug("connecting " + secondsElapsed); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTING, (int) secondsElapsed)); SystemClock.sleep(1000); continue; } @@ -126,7 +127,7 @@ public class QueueThread extends Thread { if (!pump.isConnected()) { if (L.isEnabled(L.PUMPQUEUE)) log.debug("connect"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTING, (int) secondsElapsed)); pump.connect("Connection needed"); SystemClock.sleep(1000); continue; @@ -161,9 +162,9 @@ public class QueueThread extends Thread { waitingForDisconnect = true; if (L.isEnabled(L.PUMPQUEUE)) log.debug("queue empty. disconnect"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); pump.disconnect("Queue empty"); - MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED)); + RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); if (L.isEnabled(L.PUMPQUEUE)) log.debug("disconnected"); return; diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java index 2c6902cb01..8cc02bf687 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java @@ -186,15 +186,9 @@ public class SWDefinition { .label(R.string.nsclientinternal_secret_dialogtitle) .comment(R.string.nsclientinternal_secret_dialogmessage)) .add(new SWBreak()) - .add(new SWEventListener(this) + .add(new SWEventListener(this, EventNSClientStatus.class) .label(R.string.status) .initialStatus(NSClientPlugin.getPlugin().status) - .listener(new Object() { - @Subscribe - public void onEventNSClientStatus(EventNSClientStatus event) { - MainApp.bus().post(new EventSWLabel(event.status)); - } - }) ) .add(new SWBreak()) .validator(() -> NSClientPlugin.getPlugin().nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) @@ -328,14 +322,7 @@ public class SWDefinition { .text(R.string.readstatus) .action(() -> ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Clicked connect to pump", null)) .visibility(() -> ConfigBuilderPlugin.getPlugin().getActivePump() != null)) - .add(new SWEventListener(this) - .listener(new Object() { - @Subscribe - public void onEventPumpStatusChanged(EventPumpStatusChanged event) { - MainApp.bus().post(new EventSWLabel(event.textStatus())); - } - }) - ) + .add(new SWEventListener(this, EventPumpStatusChanged.class)) .validator(() -> ConfigBuilderPlugin.getPlugin().getActivePump() != null && ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized()); private SWScreen screenAps = new SWScreen(R.string.configbuilder_aps) diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java index 487a80d91c..26944effbf 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java @@ -1,33 +1,42 @@ package info.nightscout.androidaps.setupwizard; import android.content.Context; -import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.events.EventStatus; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.setupwizard.elements.SWItem; -import info.nightscout.androidaps.setupwizard.events.EventSWLabel; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class SWEventListener extends SWItem { private static Logger log = LoggerFactory.getLogger(SWEventListener.class); + private CompositeDisposable disposable = new CompositeDisposable(); private int textLabel = 0; private String status = ""; TextView textView; - Object listener; SWDefinition definition; - SWEventListener(SWDefinition definition) { + SWEventListener(SWDefinition definition, Class clazz) { super(Type.LISTENER); this.definition = definition; - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(clazz) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + status = ((EventStatus) event).getStatus(); + if (textView != null) + textView.setText((textLabel != 0 ? MainApp.gs(textLabel) : "") + " " + status); + }) + ); + } public SWEventListener label(int newLabel) { @@ -35,16 +44,11 @@ public class SWEventListener extends SWItem { return this; } - public SWEventListener initialStatus(String status) { + SWEventListener initialStatus(String status) { this.status = status; return this; } - public SWEventListener listener(Object listener) { - this.listener = listener; - return this; - } - @Override public void generateDialog(LinearLayout layout) { Context context = layout.getContext(); @@ -53,20 +57,5 @@ public class SWEventListener extends SWItem { textView.setId(layout.generateViewId()); textView.setText((textLabel != 0 ? MainApp.gs(textLabel) : "") + " " + status); layout.addView(textView); - if (listener != null) - try { - MainApp.bus().register(listener); - } catch (Exception ignored) {} } - - @Subscribe - public void onEventSWLabel(final EventSWLabel l) { - status = l.label; - if (definition != null && definition.getActivity() != null) - definition.getActivity().runOnUiThread(() -> { - if (textView != null) - textView.setText((textLabel != 0 ? MainApp.gs(textLabel) : "") + " " + status); - }); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java index 1d3b867a6d..05ab593bc7 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java @@ -26,17 +26,22 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.events.EventProfileStoreChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus; import info.nightscout.androidaps.setupwizard.elements.SWItem; import info.nightscout.androidaps.setupwizard.events.EventSWUpdate; import info.nightscout.androidaps.utils.AndroidPermission; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class SetupWizardActivity extends NoSplashAppCompatActivity { //logging private static Logger log = LoggerFactory.getLogger(SetupWizardActivity.class); + private CompositeDisposable disposable = new CompositeDisposable(); ScrollView scrollView; @@ -84,6 +89,7 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { public void onPause() { super.onPause(); MainApp.bus().unregister(this); + disposable.clear(); } @Override @@ -91,6 +97,16 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { super.onResume(); MainApp.bus().register(this); swDefinition.setActivity(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventPumpStatusChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateButtons(), FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventNSClientStatus.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateButtons(), FabricPrivacy::logException) + ); } @Subscribe @@ -100,16 +116,6 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { updateButtons(); } - @Subscribe - public void onEventNSClientStatus(EventNSClientStatus ignored) { - updateButtons(); - } - - @Subscribe - public void onEventPumpStatusChanged(EventPumpStatusChanged ignored) { - updateButtons(); - } - @Subscribe public void onEventProfileStoreChanged(EventProfileStoreChanged ignored) { updateButtons(); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt index f4bdd186ec..ef4cae3f83 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt @@ -17,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin +import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity @@ -284,7 +285,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile, val loopPlugin = LoopPlugin.getPlugin() if (loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000) - MainApp.bus().post(EventRefreshOverview("WizardDialog")) + RxBus.send(EventRefreshOverview("WizardDialog")) } val pump1 = ConfigBuilderPlugin.getPlugin().activePump From 64f16c5a7ba26777276c141d9d72cd5cb8db571d Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 19:50:22 +0200 Subject: [PATCH 02/13] Events to RxBus --- .../androidaps/db/DatabaseHelper.java | 2 +- .../events/EventAcceptOpenLoopChange.java | 5 - .../events/EventAcceptOpenLoopChange.kt | 3 + .../events/EventCareportalEventChange.java | 8 -- .../events/EventCareportalEventChange.kt | 3 + .../events/EventConfigBuilderChange.java | 8 -- .../events/EventConfigBuilderChange.kt | 3 + .../events/EventInitializationChanged.java | 8 -- .../events/EventInitializationChanged.kt | 3 + .../events/EventLocationChange.java | 11 -- .../androidaps/events/EventLocationChange.kt | 5 + .../androidaps/events/EventNetworkChange.java | 17 --- .../androidaps/events/EventNetworkChange.kt | 16 +++ .../plugins/aps/loop/LoopPlugin.java | 2 +- .../automation/triggers/TriggerWifiSsid.java | 4 +- .../careportal/CareportalFragment.java | 125 +++++++++--------- .../general/nsclient/NSClientPlugin.java | 11 +- .../nsclient/NsClientReceiverDelegate.java | 10 +- .../nsclient/services/NSClientService.java | 23 ++-- .../general/overview/OverviewFragment.java | 33 ++--- .../PersistentNotificationPlugin.java | 11 +- .../xdripStatusline/StatuslinePlugin.java | 11 +- .../IobCobCalculatorPlugin.java | 53 +++++--- .../profile/local/LocalProfileFragment.java | 35 +++-- .../profile/simple/SimpleProfileFragment.java | 53 +++++--- .../plugins/pump/combo/ComboPlugin.java | 1 - .../activities/DanaRUserOptionsActivity.java | 25 ++-- .../danaR/services/DanaRExecutionService.java | 2 - .../services/DanaRKoreanExecutionService.java | 2 - .../pump/danaRS/services/DanaRSService.java | 5 +- .../services/DanaRv2ExecutionService.java | 3 - .../pump/insight/LocalInsightPlugin.java | 1 - .../TreatmentsCareportalFragment.java | 47 ++++--- .../receivers/NetworkChangeReceiver.java | 19 +-- .../androidaps/setupwizard/SWDefinition.java | 5 +- .../setupwizard/elements/SWPlugin.java | 4 +- .../triggers/TriggerWifiSsidTest.java | 12 +- .../NsClientReceiverDelegateTest.java | 36 ++--- 38 files changed, 322 insertions(+), 303 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index fd9af55eca..691d97947d 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -1577,7 +1577,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing scheduleCareportalEventChange"); - MainApp.bus().post(new EventCareportalEventChange()); + RxBus.INSTANCE.send(new EventCareportalEventChange()); scheduledCareportalEventPost = null; } } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java deleted file mode 100644 index 2dfbf9ae35..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.events; - -/** Base class for events to update the UI, mostly a specific tab. */ -public class EventAcceptOpenLoopChange extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt new file mode 100644 index 0000000000..552564edfc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventAcceptOpenLoopChange : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java deleted file mode 100644 index 9b47ed39cb..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 25.05.2017. - */ - -public class EventCareportalEventChange extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt new file mode 100644 index 0000000000..e7d52d86c0 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventCareportalEventChange : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java deleted file mode 100644 index ad5f558fe8..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 17.02.2017. - */ - -public class EventConfigBuilderChange extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt new file mode 100644 index 0000000000..b674374fad --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventConfigBuilderChange : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java deleted file mode 100644 index f2bef1d3d0..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 13.12.2016. - */ - -public class EventInitializationChanged extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt new file mode 100644 index 0000000000..33ab0062c5 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventInitializationChanged : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.java deleted file mode 100644 index 265ce2998c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.events; - -import android.location.Location; - -public class EventLocationChange extends Event { - public Location location; - - public EventLocationChange(Location location) { - this.location = location; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt new file mode 100644 index 0000000000..fee6c9f800 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.events + +import android.location.Location + +class EventLocationChange(var location: Location) : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java deleted file mode 100644 index 546d6f8624..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.events; - - -import info.nightscout.androidaps.utils.StringUtils; - -public class EventNetworkChange extends Event { - - public boolean mobileConnected = false; - public boolean wifiConnected = false; - - public String ssid = ""; - public boolean roaming = false; - - public String getSsid() { - return StringUtils.removeSurroundingQuotes(ssid); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt new file mode 100644 index 0000000000..62c8bdd13e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.events + +import info.nightscout.androidaps.utils.StringUtils + +class EventNetworkChange : Event() { + + var mobileConnected = false + var wifiConnected = false + + var ssid = "" + var roaming = false + + fun connectedSsid(): String { + return StringUtils.removeSurroundingQuotes(ssid) + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index c87e938d8a..d555ed3615 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -477,7 +477,7 @@ public class LoopPlugin extends PluginBase { NSUpload.uploadDeviceStatus(); SP.incInt(R.string.key_ObjectivesmanualEnacts); } - MainApp.bus().post(new EventAcceptOpenLoopChange()); + RxBus.INSTANCE.send(new EventAcceptOpenLoopChange()); } }); FabricPrivacy.getInstance().logCustom("AcceptTemp"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java index 84094095d5..ba10e81583 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java @@ -59,13 +59,13 @@ public class TriggerWifiSsid extends Trigger { if (lastRun > DateUtil.now() - T.mins(5).msecs()) return false; - if (!eventNetworkChange.wifiConnected && comparator.getValue() == Comparator.Compare.IS_NOT_AVAILABLE) { + if (!eventNetworkChange.getWifiConnected() && comparator.getValue() == Comparator.Compare.IS_NOT_AVAILABLE) { if (L.isEnabled(L.AUTOMATION)) log.debug("Ready for execution: " + friendlyDescription()); return true; } - boolean doRun = eventNetworkChange.wifiConnected && comparator.getValue().check(eventNetworkChange.getSsid(), getValue()); + boolean doRun = eventNetworkChange.getWifiConnected() && comparator.getValue().check(eventNetworkChange.connectedSsid(), getValue()); if (doRun) { if (L.isEnabled(L.AUTOMATION)) log.debug("Ready for execution: " + friendlyDescription()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java index c7f6e1bf64..42ae7fd6fc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java @@ -4,14 +4,14 @@ package info.nightscout.androidaps.plugins.general.careportal; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; -import androidx.fragment.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,19 +22,18 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventCareportalEventChange; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment; -import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.SP; -import info.nightscout.androidaps.utils.SetWarnColor; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; -public class CareportalFragment extends SubscriberFragment implements View.OnClickListener { +public class CareportalFragment extends Fragment implements View.OnClickListener { private static Logger log = LoggerFactory.getLogger(CareportalFragment.class); + private CompositeDisposable disposable = new CompositeDisposable(); TextView iage; TextView cage; @@ -71,59 +70,69 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.careportal_fragment, container, false); + View view = inflater.inflate(R.layout.careportal_fragment, container, false); - view.findViewById(R.id.careportal_bgcheck).setOnClickListener(this); - view.findViewById(R.id.careportal_announcement).setOnClickListener(this); - view.findViewById(R.id.careportal_cgmsensorinsert).setOnClickListener(this); - view.findViewById(R.id.careportal_cgmsensorstart).setOnClickListener(this); - view.findViewById(R.id.careportal_combobolus).setOnClickListener(this); - view.findViewById(R.id.careportal_correctionbolus).setOnClickListener(this); - view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this); - view.findViewById(R.id.careportal_exercise).setOnClickListener(this); - view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this); - view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this); - view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this); - view.findViewById(R.id.careportal_note).setOnClickListener(this); - view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this); - view.findViewById(R.id.careportal_pumpsitechange).setOnClickListener(this); - view.findViewById(R.id.careportal_question).setOnClickListener(this); - view.findViewById(R.id.careportal_snackbolus).setOnClickListener(this); - view.findViewById(R.id.careportal_tempbasalend).setOnClickListener(this); - view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this); - view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this); - view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this); + view.findViewById(R.id.careportal_bgcheck).setOnClickListener(this); + view.findViewById(R.id.careportal_announcement).setOnClickListener(this); + view.findViewById(R.id.careportal_cgmsensorinsert).setOnClickListener(this); + view.findViewById(R.id.careportal_cgmsensorstart).setOnClickListener(this); + view.findViewById(R.id.careportal_combobolus).setOnClickListener(this); + view.findViewById(R.id.careportal_correctionbolus).setOnClickListener(this); + view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this); + view.findViewById(R.id.careportal_exercise).setOnClickListener(this); + view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this); + view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this); + view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this); + view.findViewById(R.id.careportal_note).setOnClickListener(this); + view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this); + view.findViewById(R.id.careportal_pumpsitechange).setOnClickListener(this); + view.findViewById(R.id.careportal_question).setOnClickListener(this); + view.findViewById(R.id.careportal_snackbolus).setOnClickListener(this); + view.findViewById(R.id.careportal_tempbasalend).setOnClickListener(this); + view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this); + view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this); + view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this); - iage = view.findViewById(R.id.careportal_insulinage); - cage = view.findViewById(R.id.careportal_canulaage); - sage = view.findViewById(R.id.careportal_sensorage); - pbage = view.findViewById(R.id.careportal_pbage); + iage = view.findViewById(R.id.careportal_insulinage); + cage = view.findViewById(R.id.careportal_canulaage); + sage = view.findViewById(R.id.careportal_sensorage); + pbage = view.findViewById(R.id.careportal_pbage); - statsLayout = view.findViewById(R.id.careportal_stats); + statsLayout = view.findViewById(R.id.careportal_stats); - noProfileView = view.findViewById(R.id.profileview_noprofile); - butonsLayout = view.findViewById(R.id.careportal_buttons); + noProfileView = view.findViewById(R.id.profileview_noprofile); + butonsLayout = view.findViewById(R.id.careportal_buttons); - ProfileStore profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null ? ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() : null; - if (profileStore == null) { - noProfileView.setVisibility(View.VISIBLE); - butonsLayout.setVisibility(View.GONE); - } else { - noProfileView.setVisibility(View.GONE); - butonsLayout.setVisibility(View.VISIBLE); - } - - if (Config.NSCLIENT) - statsLayout.setVisibility(View.GONE); // visible on overview - - updateGUI(); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); + ProfileStore profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null ? ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() : null; + if (profileStore == null) { + noProfileView.setVisibility(View.VISIBLE); + butonsLayout.setVisibility(View.GONE); + } else { + noProfileView.setVisibility(View.GONE); + butonsLayout.setVisibility(View.VISIBLE); } - return null; + if (Config.NSCLIENT) + statsLayout.setVisibility(View.GONE); // visible on overview + + return view; + } + + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventCareportalEventChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGUI(), FabricPrivacy::logException) + ); + updateGUI(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } @Override @@ -203,12 +212,6 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli newDialog.show(manager, "NewNSTreatmentDialog"); } - @Subscribe - public void onStatusEvent(final EventCareportalEventChange c) { - updateGUI(); - } - - @Override protected void updateGUI() { Activity activity = getActivity(); updateAge(activity, sage, iage, cage, pbage); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index e7cfc7a0dc..cb069bf58d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -116,6 +116,11 @@ public class NSClientPlugin extends PluginBase { MainApp.bus().post(new EventNSClientUpdateGUI()); }, FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventNetworkChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException) + ); } @Override @@ -139,12 +144,6 @@ public class NSClientPlugin extends PluginBase { nsClientReceiverDelegate.onStatusEvent(ev); } - @Subscribe - public void onStatusEvent(final EventNetworkChange ev) { - nsClientReceiverDelegate.onStatusEvent(ev); - } - - private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java index 072ad6cd56..f7df37aa0f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java @@ -46,7 +46,7 @@ class NsClientReceiverDelegate { EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(context); if (event != null) - bus.post(event); + RxBus.INSTANCE.send(event); context.registerReceiver(chargingStateReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); @@ -69,7 +69,7 @@ class NsClientReceiverDelegate { ) { EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext()); if (event != null) - bus.post(event); + RxBus.INSTANCE.send(event); } else if (ev.isChanged(R.string.key_ns_chargingonly)) { EventChargingState event = chargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext()); if (event != null) @@ -123,13 +123,13 @@ class NsClientReceiverDelegate { boolean newAllowedState = true; - if (ev.wifiConnected) { + if (ev.getWifiConnected()) { if (!allowedSSIDs.trim().isEmpty() && - (!allowedSSIDs.contains(ev.getSsid()) && !allowedSSIDs.contains(ev.ssid))) { + (!allowedSSIDs.contains(ev.connectedSsid()) && !allowedSSIDs.contains(ev.getSsid()))) { newAllowedState = false; } } else { - if ((!allowRoaming && ev.roaming) || wifiOnly) { + if ((!allowRoaming && ev.getRoaming()) || wifiOnly) { newAllowedState = false; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index b3e14a7669..d360acd9c3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -69,12 +69,15 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; import io.socket.client.IO; import io.socket.client.Socket; import io.socket.emitter.Emitter; public class NSClientService extends Service { private static Logger log = LoggerFactory.getLogger(L.NSCLIENT); + private CompositeDisposable disposable = new CompositeDisposable(); static public PowerManager.WakeLock mWakeLock; private IBinder mBinder = new NSClientService.LocalBinder(); @@ -114,6 +117,17 @@ public class NSClientService extends Service { public NSClientService() { registerBus(); + disposable.add(RxBus.INSTANCE + .toObservable(EventConfigBuilderChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (nsEnabled != NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL)) { + latestDateInReceivedData = 0; + destroy(); + initialize(); + } + }, FabricPrivacy::logException) + ); if (handler == null) { HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler"); handlerThread.start(); @@ -185,15 +199,6 @@ public class NSClientService extends Service { } } - @Subscribe - public void onStatusEvent(EventConfigBuilderChange ev) { - if (nsEnabled != MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL)) { - latestDateInReceivedData = 0; - destroy(); - initialize(); - } - } - @Subscribe public void onStatusEvent(final EventNSClientRestart ev) { latestDateInReceivedData = 0; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index f16bd1c383..78be541095 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -900,6 +900,24 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, .subscribe(event -> scheduleUpdateGUI("EventTempTargetChange"), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAcceptOpenLoopChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventAcceptOpenLoopChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventCareportalEventChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventCareportalEventChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventInitializationChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventInitializationChanged"), + FabricPrivacy::logException + )); disposable.add(RxBus.INSTANCE .toObservable(EventPumpStatusChanged.class) .observeOn(AndroidSchedulers.mainThread()) @@ -917,11 +935,6 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, updateGUI("onResume"); } - @Subscribe - public void onStatusEvent(final EventInitializationChanged ev) { - scheduleUpdateGUI("EventInitializationChanged"); - } - @Subscribe public void onStatusEvent(final EventPreferenceChange ev) { scheduleUpdateGUI("EventPreferenceChange"); @@ -932,21 +945,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, scheduleUpdateGUI("EventAutosensCalculationFinished"); } - @Subscribe - public void onStatusEvent(final EventCareportalEventChange ev) { - scheduleUpdateGUI("EventCareportalEventChange"); - } - @Subscribe public void onStatusEvent(final EventNewOpenLoopNotification ev) { scheduleUpdateGUI("EventNewOpenLoopNotification"); } - @Subscribe - public void onStatusEvent(final EventAcceptOpenLoopChange ev) { - scheduleUpdateGUI("EventAcceptOpenLoopChange"); - } - @Subscribe public void onStatusEvent(final EventProfileNeedsUpdate ev) { scheduleUpdateGUI("EventProfileNeedsUpdate"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java index dd9ff00c4c..1d26a0ec16 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java @@ -120,6 +120,12 @@ public class PersistentNotificationPlugin extends PluginBase { .subscribe(event -> triggerNotificationUpdate(false), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventInitializationChanged.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); triggerNotificationUpdate(true); } @@ -331,9 +337,4 @@ public class PersistentNotificationPlugin extends PluginBase { triggerNotificationUpdate(false); } - @Subscribe - public void onStatusEvent(final EventInitializationChanged ev) { - triggerNotificationUpdate(false); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index 2f219de651..2d8736351b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -116,6 +116,12 @@ public class StatuslinePlugin extends PluginBase { .subscribe(event -> sendStatus(), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventConfigBuilderChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); } @Override @@ -211,9 +217,4 @@ public class StatuslinePlugin extends PluginBase { sendStatus(); } - @Subscribe - public void onStatusEvent(final EventConfigBuilderChange ev) { - sendStatus(); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index 444b2db67a..8ede44ce9e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator; import android.os.SystemClock; + import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.LongSparseArray; @@ -31,16 +32,20 @@ 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.aps.openAPSSMB.OpenAPSSMBPlugin; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; -import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.utils.DateUtil.now; @@ -50,6 +55,7 @@ import static info.nightscout.androidaps.utils.DateUtil.now; public class IobCobCalculatorPlugin extends PluginBase { private Logger log = LoggerFactory.getLogger(L.AUTOSENS); + private CompositeDisposable disposable = new CompositeDisposable(); private static IobCobCalculatorPlugin plugin = null; @@ -83,14 +89,34 @@ public class IobCobCalculatorPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); super.onStart(); + MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventConfigBuilderChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (this != getPlugin()) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); + return; + } + stopCalculation("onEventConfigBuilderChange"); + synchronized (dataLock) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); + iobTable = new LongSparseArray<>(); + autosensDataTable = new LongSparseArray<>(); + } + runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, event); + }, FabricPrivacy::logException) + ); } @Override protected void onStop() { - super.onStop(); + disposable.clear(); MainApp.bus().unregister(this); + super.onStop(); } public LongSparseArray getAutosensDataTable() { @@ -529,7 +555,7 @@ public class IobCobCalculatorPlugin extends PluginBase { count++; } } - return sum /count; + return sum / count; } @Nullable @@ -712,7 +738,7 @@ public class IobCobCalculatorPlugin extends PluginBase { ev.isChanged(R.string.key_absorption_cutoff) || ev.isChanged(R.string.key_openapsama_autosens_max) || ev.isChanged(R.string.key_openapsama_autosens_min) - ) { + ) { stopCalculation("onEventPreferenceChange"); synchronized (dataLock) { if (L.isEnabled(L.AUTOSENS)) @@ -725,23 +751,6 @@ public class IobCobCalculatorPlugin extends PluginBase { } } - @Subscribe - public void onEventConfigBuilderChange(EventConfigBuilderChange ev) { - if (this != getPlugin()) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Ignoring event for non default instance"); - return; - } - stopCalculation("onEventConfigBuilderChange"); - synchronized (dataLock) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); - iobTable = new LongSparseArray<>(); - autosensDataTable = new LongSparseArray<>(); - } - runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, ev); - } - // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated @Subscribe public void onEventNewHistoryData(EventNewHistoryData ev) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java index a8f77ea54c..f8969e9594 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java @@ -13,8 +13,7 @@ import android.widget.RadioButton; import android.widget.TextView; import androidx.annotation.NonNull; - -import com.squareup.otto.Subscribe; +import androidx.fragment.app.Fragment; import java.text.DecimalFormat; @@ -23,19 +22,24 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.interfaces.PumpDescription; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.NumberPicker; import info.nightscout.androidaps.utils.SafeParse; import info.nightscout.androidaps.utils.TimeListEdit; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; import static info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.MIN_DIA; -public class LocalProfileFragment extends SubscriberFragment { +public class LocalProfileFragment extends Fragment { + private CompositeDisposable disposable = new CompositeDisposable(); + private NumberPicker diaView; private RadioButton mgdlView; private RadioButton mmolView; @@ -143,6 +147,23 @@ public class LocalProfileFragment extends SubscriberFragment { return layout; } + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventInitializationChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGUI(), FabricPrivacy::logException) + ); + updateGUI(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + public void doEdit() { LocalProfilePlugin.getPlugin().setEdited(true); updateGUI(); @@ -157,12 +178,6 @@ public class LocalProfileFragment extends SubscriberFragment { return MainApp.gs(R.string.localprofile); } - @Subscribe - public void onStatusEvent(final EventInitializationChanged e) { - updateGUI(); - } - - @Override protected void updateGUI() { Activity activity = getActivity(); if (activity != null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java index b8a7d16be5..ecf4fc423b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.profile.simple; -import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; @@ -13,19 +12,24 @@ import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.fragment.app.Fragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventInitializationChanged; +import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SafeParse; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; + +public class SimpleProfileFragment extends Fragment { + private CompositeDisposable disposable = new CompositeDisposable(); -public class SimpleProfileFragment extends SubscriberFragment { EditText diaView; RadioButton mgdlView; RadioButton mmolView; @@ -122,27 +126,34 @@ public class SimpleProfileFragment extends SubscriberFragment { return layout; } - @Subscribe - public void onStatusEvent(final EventInitializationChanged e) { + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventInitializationChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGUI(), FabricPrivacy::logException) + ); updateGUI(); } @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - boolean isValid = SimpleProfilePlugin.getPlugin().getProfile() != null && SimpleProfilePlugin.getPlugin().getProfile().getDefaultProfile().isValid(MainApp.gs(R.string.simpleprofile)); - if (!ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized() || ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !isValid) { - profileswitchButton.setVisibility(View.GONE); - } else { - profileswitchButton.setVisibility(View.VISIBLE); - } - if (isValid) - invalidProfile.setVisibility(View.GONE); - else - invalidProfile.setVisibility(View.VISIBLE); - }); + boolean isValid = SimpleProfilePlugin.getPlugin().getProfile() != null && SimpleProfilePlugin.getPlugin().getProfile().getDefaultProfile().isValid(MainApp.gs(R.string.simpleprofile)); + if (!ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized() || ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !isValid) { + profileswitchButton.setVisibility(View.GONE); + } else { + profileswitchButton.setVisibility(View.VISIBLE); + } + if (isValid) + invalidProfile.setVisibility(View.GONE); + else + invalidProfile.setVisibility(View.VISIBLE); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index affbf49465..e867189a80 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -375,7 +375,6 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint setValidBasalRateProfileSelectedOnPump(true); pump.initialized = true; - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); // show notification to check pump date if last bolus is older than 24 hours diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java index d5b4fd3158..23520f3491 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java @@ -1,14 +1,11 @@ package info.nightscout.androidaps.plugins.pump.danaR.activities; -import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Switch; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -21,12 +18,16 @@ import info.nightscout.androidaps.activities.NoSplashActivity; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.NumberPicker; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; /** * Created by Rumen Georgiev on 5/31/2018. @@ -34,6 +35,7 @@ import info.nightscout.androidaps.utils.NumberPicker; public class DanaRUserOptionsActivity extends NoSplashActivity { private static Logger log = LoggerFactory.getLogger(L.PUMP); + private CompositeDisposable disposable = new CompositeDisposable(); Switch timeFormat; Switch buttonScroll; @@ -54,15 +56,19 @@ public class DanaRUserOptionsActivity extends NoSplashActivity { boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP); @Override - protected void onResume() { + protected synchronized void onResume() { super.onResume(); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventInitializationChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> setData(), FabricPrivacy::logException) + ); } @Override - protected void onPause() { + protected synchronized void onPause() { + disposable.clear(); super.onPause(); - MainApp.bus().unregister(this); } @Override @@ -144,11 +150,6 @@ public class DanaRUserOptionsActivity extends NoSplashActivity { lowReservoir.setValue((double) pump.lowReservoirRate); } - @Subscribe - public void onEventInitializationChanged(EventInitializationChanged ignored) { - runOnUiThread(this::setData); - } - public void onSaveClick() { if (!isRS && !isDanaR && !isDanaRv2) { //exit if pump is not DanaRS, Dana!, or DanaR with upgraded firmware diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index b30da3f004..49e79acd1d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -193,7 +193,6 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { danaRPump.lastConnection = 0; danaRPump.lastSettingsRead = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); return; } @@ -211,7 +210,6 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index 9f59beb096..aed225b68d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -194,7 +194,6 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { danaRPump.lastConnection = 0; danaRPump.lastSettingsRead = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); return; } @@ -214,7 +213,6 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { } RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index 8da728692b..eb8ece1c06 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -163,7 +163,6 @@ public class DanaRSService extends Service { // deinitialize pump danaRPump.lastConnection = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); return; } @@ -184,7 +183,6 @@ public class DanaRSService extends Service { //deinitialize pump danaRPump.lastConnection = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); return; } else { @@ -214,8 +212,7 @@ public class DanaRSService extends Service { loadEvents(); - MainApp.bus().post(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); + RxBus.INSTANCE.send(new EventDanaRNewStatus()); RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 3be2f16c73..b4f43f01e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -202,7 +202,6 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { danaRPump.lastConnection = 0; danaRPump.lastSettingsRead = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); return; } @@ -224,7 +223,6 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { //deinitialize pump danaRPump.lastConnection = 0; RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); return; } else { @@ -258,7 +256,6 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { loadEvents(); RxBus.INSTANCE.send(new EventDanaRNewStatus()); - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); NSUpload.uploadDeviceStatus(); if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 2977b306f4..99118549a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -148,7 +148,6 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con alertService = ((InsightAlertService.LocalBinder) binder).getService(); } if (connectionService != null && alertService != null) { - MainApp.bus().post(new EventInitializationChanged()); RxBus.INSTANCE.send(new EventInitializationChanged()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java index 4a0e767cbb..6dcedd7f3e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.treatments.fragments; -import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; @@ -13,30 +12,33 @@ import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.cardview.widget.CardView; +import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventCareportalEventChange; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.Translator; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; /** * Created by mike on 13/01/17. */ -public class TreatmentsCareportalFragment extends SubscriberFragment implements View.OnClickListener { +public class TreatmentsCareportalFragment extends Fragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); RecyclerView recyclerView; LinearLayoutManager llm; @@ -148,10 +150,26 @@ public class TreatmentsCareportalFragment extends SubscriberFragment implements if (nsUploadOnly) refreshFromNS.setVisibility(View.GONE); - updateGUI(); return view; } + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventCareportalEventChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + @Override public void onClick(View view) { switch (view.getId()) { @@ -182,21 +200,8 @@ public class TreatmentsCareportalFragment extends SubscriberFragment implements } - @Subscribe - public void onStatusEvent(final EventCareportalEventChange ev) { - updateGUI(); - } - - @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)), false); - } - }); + private void updateGui() { + recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)), false); } private void removeAndroidAPSStatedEvents() { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java index 2695ad64f2..a920d13698 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java @@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.EventNetworkChange; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; public class NetworkChangeReceiver extends BroadcastReceiver { @@ -27,7 +28,7 @@ public class NetworkChangeReceiver extends BroadcastReceiver { public void onReceive(final Context context, final Intent intent) { EventNetworkChange event = grabNetworkStatus(context); if (event != null) - MainApp.bus().post(event); + RxBus.INSTANCE.send(event); } @Nullable @@ -40,23 +41,23 @@ public class NetworkChangeReceiver extends BroadcastReceiver { if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) { - event.wifiConnected = true; + event.setWifiConnected(true); WifiManager wifiManager = (WifiManager) MainApp.instance().getApplicationContext().getSystemService(Context.WIFI_SERVICE); if (wifiManager != null) { WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) { - event.ssid = wifiInfo.getSSID(); + event.setSsid(wifiInfo.getSSID()); } if (L.isEnabled(L.CORE)) - log.debug("NETCHANGE: Wifi connected. SSID: " + event.ssid); + log.debug("NETCHANGE: Wifi connected. SSID: " + event.connectedSsid()); } } if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { - event.mobileConnected = true; - event.roaming = activeNetwork.isRoaming(); + event.setMobileConnected(true); + event.setRoaming(activeNetwork.isRoaming()); if (L.isEnabled(L.CORE)) - log.debug("NETCHANGE: Mobile connected. Roaming: " + event.roaming); + log.debug("NETCHANGE: Mobile connected. Roaming: " + event.getRoaming()); } } else { if (L.isEnabled(L.CORE)) @@ -68,11 +69,11 @@ public class NetworkChangeReceiver extends BroadcastReceiver { } public static boolean isWifiConnected() { - return lastEvent != null && lastEvent.wifiConnected; + return lastEvent != null && lastEvent.getWifiConnected(); } public static boolean isConnected() { - return lastEvent != null && (lastEvent.wifiConnected || lastEvent.mobileConnected); + return lastEvent != null && (lastEvent.getWifiConnected() || lastEvent.getMobileConnected()); } public static EventNetworkChange getLastEvent() { diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java index 8cc02bf687..718e21b099 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment; @@ -170,7 +171,7 @@ public class SWDefinition { NSClientPlugin.getPlugin().setFragmentVisible(PluginType.GENERAL, true); ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(NSClientPlugin.getPlugin(), PluginType.GENERAL); ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard"); - MainApp.bus().post(new EventConfigBuilderChange()); + RxBus.INSTANCE.send(new EventConfigBuilderChange()); MainApp.bus().post(new EventSWUpdate(true)); }) .visibility(() -> !NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL))) @@ -372,7 +373,7 @@ public class SWDefinition { LoopPlugin.getPlugin().setFragmentVisible(PluginType.LOOP, true); ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(LoopPlugin.getPlugin(), PluginType.LOOP); ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard"); - MainApp.bus().post(new EventConfigBuilderChange()); + RxBus.INSTANCE.send(new EventConfigBuilderChange()); MainApp.bus().post(new EventSWUpdate(true)); }) .visibility(() -> !LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java index 8c0be61598..e09cbb6e17 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java @@ -17,7 +17,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.setupwizard.events.EventSWUpdate; @@ -88,7 +88,7 @@ public class SWPlugin extends SWItem { plugin.setFragmentVisible(pType, rb.isChecked() && makeVisible); ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(plugin, pType); ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard"); - MainApp.bus().post(new EventConfigBuilderChange()); + RxBus.INSTANCE.send(new EventConfigBuilderChange()); MainApp.bus().post(new EventSWUpdate()); }); layout.addView(radioGroup); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java index 8156e483cc..6c5a359ec7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java @@ -36,22 +36,22 @@ public class TriggerWifiSsidTest { TriggerWifiSsid t = new TriggerWifiSsid().setValue("aSSID").comparator(Comparator.Compare.IS_EQUAL); - e.wifiConnected = false; + e.setWifiConnected(false); Assert.assertFalse(t.shouldRun()); - e.wifiConnected = true; - e.ssid = "otherSSID"; + e.setWifiConnected(true); + e.setSsid("otherSSID"); Assert.assertFalse(t.shouldRun()); - e.wifiConnected = true; - e.ssid = "aSSID"; + e.setWifiConnected(true); + e.setSsid("aSSID"); Assert.assertTrue(t.shouldRun()); t.lastRun(now - 1); Assert.assertFalse(t.shouldRun()); t = new TriggerWifiSsid().setValue("aSSID").comparator(Comparator.Compare.IS_NOT_AVAILABLE); - e.wifiConnected = false; + e.setWifiConnected(false); Assert.assertTrue(t.shouldRun()); // no network data diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java index 0400532e9d..0abbf50399 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java @@ -64,67 +64,67 @@ public class NsClientReceiverDelegateTest { when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false); when(SP.getString(anyInt(), anyString())).thenReturn(""); EventNetworkChange ev = new EventNetworkChange(); - ev.ssid = ""; + ev.setSsid(""); - ev.mobileConnected = true; - ev.wifiConnected = true; + ev.setMobileConnected(true); + ev.setWifiConnected(true); assertTrue(sut.calculateStatus(ev)); - ev.ssid = "test"; + ev.setSsid("test"); when(SP.getString(anyInt(), anyString())).thenReturn("\"test\""); assertTrue(sut.calculateStatus(ev)); - ev.ssid = "\"test\""; + ev.setSsid("\"test\""); assertTrue(sut.calculateStatus(ev)); - ev.wifiConnected = false; + ev.setWifiConnected(false); assertTrue(sut.calculateStatus(ev)); // wifiOnly = true // allowRoaming = true as well when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(true); - ev.wifiConnected = true; + ev.setWifiConnected(true); assertTrue(sut.calculateStatus(ev)); - ev.wifiConnected = false; + ev.setWifiConnected(false); assertTrue(!sut.calculateStatus(ev)); // wifiOnly = false // allowRoaming = false as well when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false); - ev.wifiConnected = false; - ev.roaming = true; + ev.setWifiConnected(false); + ev.setRoaming(true); assertTrue(!sut.calculateStatus(ev)); // wifiOnly = false // allowRoaming = true when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false); when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true); - ev.wifiConnected = false; - ev.roaming = true; + ev.setWifiConnected(false); + ev.setRoaming(true); assertTrue(sut.calculateStatus(ev)); // wifiOnly = true // allowRoaming = true when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true); when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true); - ev.wifiConnected = false; - ev.roaming = true; + ev.setWifiConnected(false); + ev.setRoaming(true); assertTrue(!sut.calculateStatus(ev)); // wifiOnly = true // allowRoaming = true when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true); when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true); - ev.wifiConnected = true; - ev.roaming = true; + ev.setWifiConnected(true); + ev.setRoaming(true); assertTrue(sut.calculateStatus(ev)); // wifiOnly = false // allowRoaming = false when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false); when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(false); - ev.wifiConnected = true; - ev.roaming = true; + ev.setWifiConnected(true); + ev.setRoaming(true); assertTrue(sut.calculateStatus(ev)); } } From 0f792dc092d61612b16c6897354fef9ed9e3ace5 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 20:26:33 +0200 Subject: [PATCH 03/13] Events to RxBus --- .../activities/HistoryBrowseActivity.java | 31 ++++---- .../androidaps/db/DatabaseHelper.java | 1 - .../androidaps/events/EventNewBG.java | 17 ---- .../androidaps/events/EventNewBG.kt | 5 ++ .../events/EventNewBasalProfile.java | 7 -- .../androidaps/events/EventNewBasalProfile.kt | 3 + .../plugins/aps/loop/LoopPlugin.java | 51 ++++++------ .../configBuilder/ProfileFunctions.java | 3 +- .../general/overview/OverviewFragment.java | 11 +-- .../PersistentNotificationPlugin.java | 22 +++--- .../plugins/general/wear/WearPlugin.java | 30 +++---- .../xdripStatusline/StatuslinePlugin.java | 11 +-- .../IobCobCalculatorPlugin.java | 78 ++++++++++--------- .../iobCobCalculator/IobCobOref1Thread.java | 2 +- .../iob/iobCobCalculator/IobCobThread.java | 1 - .../plugins/source/BGSourceFragment.java | 42 ++++++---- .../fragments/TreatmentsBolusFragment.java | 34 ++++---- .../TreatmentsExtendedBolusesFragment.java | 14 ++-- .../TreatmentsTemporaryBasalsFragment.java | 22 +++--- 19 files changed, 190 insertions(+), 195 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java index cd969a53a1..b16b48b149 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java @@ -30,6 +30,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.events.EventCustomCalculationFinished; import info.nightscout.androidaps.interfaces.PumpInterface; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment; @@ -39,12 +40,15 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class HistoryBrowseActivity extends NoSplashActivity { private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); - + private CompositeDisposable disposable = new CompositeDisposable(); ImageButton chartButton; @@ -166,6 +170,7 @@ public class HistoryBrowseActivity extends NoSplashActivity { public void onPause() { super.onPause(); MainApp.bus().unregister(this); + disposable.clear(); iobCobCalculatorPlugin.stopCalculation("onPause"); } @@ -173,6 +178,18 @@ public class HistoryBrowseActivity extends NoSplashActivity { public void onResume() { super.onResume(); MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (event.getCause() == eventCustomCalculationFinished) { + log.debug("EventAutosensCalculationFinished"); + synchronized (HistoryBrowseActivity.this) { + updateGUI("EventAutosensCalculationFinished"); + } + } + }, FabricPrivacy::logException) + ); // set start of current day Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); @@ -193,18 +210,6 @@ public class HistoryBrowseActivity extends NoSplashActivity { iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished e) { - if (e.getCause() == eventCustomCalculationFinished) { - log.debug("EventAutosensCalculationFinished"); - runOnUiThread(() -> { - synchronized (HistoryBrowseActivity.this) { - updateGUI("EventAutosensCalculationFinished"); - } - }); - } - } - @Subscribe public void onStatusEvent(final EventIobCalculationProgress e) { runOnUiThread(() -> { diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 691d97947d..f1763e8aa8 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -412,7 +412,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventNewBg"); - MainApp.bus().post(new EventNewBG(bgReading)); RxBus.INSTANCE.send(new EventNewBG(bgReading)); scheduledBgPost = null; } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java deleted file mode 100644 index db3498bed7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.events; - -import androidx.annotation.Nullable; - -import info.nightscout.androidaps.db.BgReading; - -/** - * Created by mike on 05.06.2016. - */ -public class EventNewBG extends EventLoop { - @Nullable - public final BgReading bgReading; - - public EventNewBG(BgReading bgReading) { - this.bgReading = bgReading; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt new file mode 100644 index 0000000000..08c05407c9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.events + +import info.nightscout.androidaps.db.BgReading + +class EventNewBG(val bgReading: BgReading?) : EventLoop() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java deleted file mode 100644 index f26a310b6b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 04.06.2016. - */ -public class EventNewBasalProfile extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt new file mode 100644 index 0000000000..2ffa5a9724 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventNewBasalProfile : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index d555ed3615..e6767a3067 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -129,6 +129,30 @@ public class LoopPlugin extends PluginBase { invoke("EventTempTargetChange", true); }, FabricPrivacy::logException) ); + /** + * This method is triggered once autosens calculation has completed, so the LoopPlugin + * has current data to work with. However, autosens calculation can be triggered by multiple + * sources and currently only a new BG should trigger a loop run. Hence we return early if + * the event causing the calculation is not EventNewBg. + *

+ */ + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + // Autosens calculation not triggered by a new BG + if (!(event.getCause() instanceof EventNewBG)) return; + + BgReading bgReading = DatabaseHelper.actualBg(); + // BG outdated + if (bgReading == null) return; + // already looped with that value + if (bgReading.date <= lastBgTriggeredRun) return; + + lastBgTriggeredRun = bgReading.date; + invoke("AutosenseCalculation for " + bgReading, true); + }, FabricPrivacy::logException) + ); } private void createNotificationChannel() { @@ -156,33 +180,6 @@ public class LoopPlugin extends PluginBase { return pump == null || pump.getPumpDescription().isTempBasalCapable; } - /** - * This method is triggered once autosens calculation has completed, so the LoopPlugin - * has current data to work with. However, autosens calculation can be triggered by multiple - * sources and currently only a new BG should trigger a loop run. Hence we return early if - * the event causing the calculation is not EventNewBg. - *

- */ - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - if (!(ev.getCause() instanceof EventNewBG)) { - // Autosens calculation not triggered by a new BG - return; - } - BgReading bgReading = DatabaseHelper.actualBg(); - if (bgReading == null) { - // BG outdated - return; - } - if (bgReading.date <= lastBgTriggeredRun) { - // already looped with that value - return; - } - - lastBgTriggeredRun = bgReading.date; - invoke("AutosenseCalculation for " + bgReading, true); - } - public long suspendedTo() { return loopSuspendedTill; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java index b9276a5ac3..e9bd53bcf3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -23,6 +23,7 @@ import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; @@ -64,7 +65,7 @@ public class ProfileFunctions { MainApp.instance().startActivity(i); } if (result.enacted) - MainApp.bus().post(new EventNewBasalProfile()); + RxBus.INSTANCE.send(new EventNewBasalProfile()); } }); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 78be541095..e88fe59c80 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -918,6 +918,12 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, .subscribe(event -> scheduleUpdateGUI("EventInitializationChanged"), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventAutosensCalculationFinished"), + FabricPrivacy::logException + )); disposable.add(RxBus.INSTANCE .toObservable(EventPumpStatusChanged.class) .observeOn(AndroidSchedulers.mainThread()) @@ -940,11 +946,6 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, scheduleUpdateGUI("EventPreferenceChange"); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - scheduleUpdateGUI("EventAutosensCalculationFinished"); - } - @Subscribe public void onStatusEvent(final EventNewOpenLoopNotification ev) { scheduleUpdateGUI("EventNewOpenLoopNotification"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java index 1d26a0ec16..c6b24d6438 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java @@ -126,6 +126,18 @@ public class PersistentNotificationPlugin extends PluginBase { .subscribe(event -> triggerNotificationUpdate(false), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventNewBasalProfile.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); triggerNotificationUpdate(true); } @@ -327,14 +339,4 @@ public class PersistentNotificationPlugin extends PluginBase { triggerNotificationUpdate(false); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - triggerNotificationUpdate(false); - } - - @Subscribe - public void onStatusEvent(final EventNewBasalProfile ev) { - triggerNotificationUpdate(false); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java index d74643cd14..f207bd2c84 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java @@ -81,25 +81,37 @@ public class WearPlugin extends PluginBase { disposable.add(RxBus.INSTANCE .toObservable(EventOpenAPSUpdateGui.class) .observeOn(Schedulers.io()) - .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + .subscribe(event -> sendDataToWatch(true, true, false), FabricPrivacy::logException )); disposable.add(RxBus.INSTANCE .toObservable(EventExtendedBolusChange.class) .observeOn(Schedulers.io()) - .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + .subscribe(event -> sendDataToWatch(true, true, false), FabricPrivacy::logException )); disposable.add(RxBus.INSTANCE .toObservable(EventTempBasalChange.class) .observeOn(Schedulers.io()) - .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + .subscribe(event -> sendDataToWatch(true, true, false), FabricPrivacy::logException )); disposable.add(RxBus.INSTANCE .toObservable(EventTreatmentChange.class) .observeOn(Schedulers.io()) - .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false), + .subscribe(event -> sendDataToWatch(true, true, false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventNewBasalProfile.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendDataToWatch(false, true, false), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendDataToWatch(true, true, true), FabricPrivacy::logException )); disposable.add(RxBus.INSTANCE @@ -169,16 +181,6 @@ public class WearPlugin extends PluginBase { sendDataToWatch(true, false, false); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - sendDataToWatch(true, true, true); - } - - @Subscribe - public void onStatusEvent(final EventNewBasalProfile ev) { - sendDataToWatch(false, true, false); - } - @Subscribe public void onStatusEvent(final EventOverviewBolusProgress ev) { if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index 2d8736351b..fec423ea66 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -122,6 +122,12 @@ public class StatuslinePlugin extends PluginBase { .subscribe(event -> sendStatus(), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); } @Override @@ -207,11 +213,6 @@ public class StatuslinePlugin extends PluginBase { sendStatus(); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - sendStatus(); - } - @Subscribe public void onStatusEvent(final EventAppInitialized ev) { sendStatus(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index 8ede44ce9e..2db1f2dc35 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -91,6 +91,7 @@ public class IobCobCalculatorPlugin extends PluginBase { protected void onStart() { super.onStart(); MainApp.bus().register(this); + // EventConfigBuilderChange disposable.add(RxBus.INSTANCE .toObservable(EventConfigBuilderChange.class) .observeOn(Schedulers.io()) @@ -110,6 +111,46 @@ public class IobCobCalculatorPlugin extends PluginBase { runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, event); }, FabricPrivacy::logException) ); + // EventNewBasalProfile + disposable.add(RxBus.INSTANCE + .toObservable(EventNewBasalProfile.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (this != getPlugin()) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); + return; + } + if (ConfigBuilderPlugin.getPlugin() == null) + return; // app still initializing + if (event == null) { // on init no need of reset + return; + } + stopCalculation("onNewProfile"); + synchronized (dataLock) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); + iobTable = new LongSparseArray<>(); + autosensDataTable = new LongSparseArray<>(); + basalDataTable = new LongSparseArray<>(); + } + runCalculation("onNewProfile", System.currentTimeMillis(), false, true, event); + }, FabricPrivacy::logException) + ); + // EventNewBG + disposable.add(RxBus.INSTANCE + .toObservable(EventNewBG.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (this != getPlugin()) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); + return; + } + stopCalculation("onEventNewBG"); + runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, event); + }, FabricPrivacy::logException) + ); } @Override @@ -664,19 +705,7 @@ public class IobCobCalculatorPlugin extends PluginBase { runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev); } - @Subscribe - @SuppressWarnings("unused") - public void onEventNewBG(EventNewBG ev) { - if (this != getPlugin()) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Ignoring event for non default instance"); - return; - } - stopCalculation("onEventNewBG"); - runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, ev); - } - - public void stopCalculation(String from) { + public void stopCalculation(String from) { if (thread != null && thread.getState() != Thread.State.TERMINATED) { stopCalculationTrigger = true; if (L.isEnabled(L.AUTOSENS)) @@ -701,29 +730,6 @@ public class IobCobCalculatorPlugin extends PluginBase { } } - @Subscribe - public void onNewProfile(EventNewBasalProfile ev) { - if (this != getPlugin()) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Ignoring event for non default instance"); - return; - } - if (ConfigBuilderPlugin.getPlugin() == null) - return; // app still initializing - if (ev == null) { // on init no need of reset - return; - } - stopCalculation("onNewProfile"); - synchronized (dataLock) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); - iobTable = new LongSparseArray<>(); - autosensDataTable = new LongSparseArray<>(); - basalDataTable = new LongSparseArray<>(); - } - runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev); - } - @Subscribe public void onEventPreferenceChange(EventPreferenceChange ev) { if (this != getPlugin()) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java index 2b427602f5..84cca4e90f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java @@ -387,7 +387,7 @@ public class IobCobOref1Thread extends Thread { } new Thread(() -> { SystemClock.sleep(1000); - MainApp.bus().post(new EventAutosensCalculationFinished(cause)); + RxBus.INSTANCE.send(new EventAutosensCalculationFinished(cause)); }).start(); } finally { if (mWakeLock != null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java index 756cee9853..65495b1fd2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java @@ -312,7 +312,6 @@ public class IobCobThread extends Thread { } new Thread(() -> { SystemClock.sleep(1000); - MainApp.bus().post(new EventAutosensCalculationFinished(cause)); RxBus.INSTANCE.send(new EventAutosensCalculationFinished(cause)); }).start(); } finally { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java index 269ee2b3f5..6023d70d12 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java @@ -1,19 +1,18 @@ package info.nightscout.androidaps.plugins.source; -import android.app.Activity; import android.content.DialogInterface; import android.graphics.Paint; import android.os.Bundle; -import androidx.annotation.NonNull; -import androidx.appcompat.app.AlertDialog; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; import java.util.List; @@ -21,19 +20,22 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; /** * Created by mike on 16.10.2017. */ -public class BGSourceFragment extends SubscriberFragment { +public class BGSourceFragment extends Fragment { + private CompositeDisposable disposable = new CompositeDisposable(); RecyclerView recyclerView; String units = Constants.MGDL; @@ -66,19 +68,25 @@ public class BGSourceFragment extends SubscriberFragment { return null; } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished unused) { - updateGUI(); + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGUI(), FabricPrivacy::logException) + ); } @Override + public synchronized void onPause() { + disposable.clear(); + super.onPause(); + } + protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - long now = System.currentTimeMillis(); - recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true); - }); + long now = System.currentTimeMillis(); + recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true); } public class RecyclerViewAdapter extends RecyclerView.Adapter { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java index 81cfcd16a9..abce919233 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java @@ -269,6 +269,11 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> updateGui(), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); updateGui(); } @@ -278,26 +283,17 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis disposable.clear(); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - updateGui(); - } - private void updateGui() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTreatmentsFromHistory()), false); - if (TreatmentsPlugin.getPlugin().getLastCalculationTreatments() != null) { - iobTotal.setText(DecimalFormatter.to2Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().iob) + " " + MainApp.gs(R.string.insulin_unit_shortname)); - activityTotal.setText(DecimalFormatter.to3Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().activity) + " " + MainApp.gs(R.string.insulin_unit_shortname)); - } - if (!TreatmentsPlugin.getPlugin().getService().getTreatmentDataFromTime(now() + 1000, true).isEmpty()) { - deleteFutureTreatments.setVisibility(View.VISIBLE); - } else { - deleteFutureTreatments.setVisibility(View.GONE); - } - }); + recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTreatmentsFromHistory()), false); + if (TreatmentsPlugin.getPlugin().getLastCalculationTreatments() != null) { + iobTotal.setText(DecimalFormatter.to2Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().iob) + " " + MainApp.gs(R.string.insulin_unit_shortname)); + activityTotal.setText(DecimalFormatter.to3Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().activity) + " " + MainApp.gs(R.string.insulin_unit_shortname)); + } + if (!TreatmentsPlugin.getPlugin().getService().getTreatmentDataFromTime(now() + 1000, true).isEmpty()) { + deleteFutureTreatments.setVisibility(View.VISIBLE); + } else { + deleteFutureTreatments.setVisibility(View.GONE); + } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java index e148ab7cad..297146d999 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -191,6 +191,11 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> updateGui(), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); updateGui(); } @@ -200,15 +205,8 @@ public class TreatmentsExtendedBolusesFragment extends Fragment { disposable.clear(); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ev) { - updateGui(); - } - private void updateGui() { - Activity activity = getActivity(); - if (activity != null && recyclerView != null) - activity.runOnUiThread(() -> recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory()), false)); + recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory()), false); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 59f2fa69c9..35fb692c64 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -217,6 +217,11 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> updateGui(), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); updateGui(); } @@ -226,20 +231,11 @@ public class TreatmentsTemporaryBasalsFragment extends Fragment { disposable.clear(); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished ignored) { - updateGui(); - } - private void updateGui() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTemporaryBasalsFromHistory()), false); - IobTotal tempBasalsCalculation = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals(); - if (tempBasalsCalculation != null) - tempBasalTotalView.setText(DecimalFormatter.to2Decimal(tempBasalsCalculation.basaliob, " U")); - }); + recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTemporaryBasalsFromHistory()), false); + IobTotal tempBasalsCalculation = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals(); + if (tempBasalsCalculation != null) + tempBasalTotalView.setText(DecimalFormatter.to2Decimal(tempBasalsCalculation.basaliob, " U")); } } From 7596775331343e4927270fd8698b9123db63b7c2 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 21:55:40 +0200 Subject: [PATCH 04/13] clone notification list for viewing --- .../general/overview/notifications/NotificationStore.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java index f46e5184cd..9685445ce0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java @@ -172,7 +172,7 @@ public class NotificationStore { removeExpired(); unSnooze(); if (store.size() > 0) { - NotificationRecyclerViewAdapter adapter = new NotificationRecyclerViewAdapter(store); + NotificationRecyclerViewAdapter adapter = new NotificationRecyclerViewAdapter(cloneStore()); notificationsView.setAdapter(adapter); notificationsView.setVisibility(View.VISIBLE); } else { @@ -180,4 +180,9 @@ public class NotificationStore { } } + private synchronized List cloneStore() { + List clone = new ArrayList<>(store.size()); + clone.addAll(store); + return clone; + } } From 30cf4f77daf251844cf2629211dadde3eee02f40 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 23:16:51 +0200 Subject: [PATCH 05/13] Events to RxBus --- .../nightscout/androidaps/MainActivity.java | 82 ++++++++++--------- .../activities/PreferencesActivity.java | 5 +- .../androidaps/db/DatabaseHelper.java | 2 +- .../androidaps/events/EventAppExit.java | 7 -- .../androidaps/events/EventAppExit.kt | 3 + .../events/EventPreferenceChange.java | 25 ------ .../events/EventPreferenceChange.kt | 19 +++++ .../events/EventProfileNeedsUpdate.java | 8 -- .../events/EventProfileNeedsUpdate.kt | 3 + .../events/EventProfileStoreChanged.java | 4 - .../events/EventProfileStoreChanged.kt | 3 + .../androidaps/events/EventRefreshGui.java | 14 ---- .../androidaps/events/EventRefreshGui.kt | 3 + .../androidaps/interfaces/PluginBase.java | 2 +- .../plugins/configBuilder/PluginViewHolder.kt | 3 +- .../configBuilder/ProfileFunctions.java | 52 ++++++------ .../maintenance/ImportExportPrefs.java | 3 +- .../general/nsclient/NSClientPlugin.java | 31 +++---- .../nsclient/NsClientReceiverDelegate.java | 1 - .../nsclient/services/NSClientService.java | 69 ++++++++-------- .../general/overview/OverviewFragment.java | 22 ++--- .../persistentNotification/DummyService.java | 57 ++++++------- .../PersistentNotificationPlugin.java | 17 ++-- .../SmsCommunicatorPlugin.java | 18 +++- .../plugins/general/wear/WearPlugin.java | 21 ++--- .../xdripStatusline/StatuslinePlugin.java | 12 +-- .../IobCobCalculatorPlugin.java | 57 +++++++------ .../profile/local/LocalProfilePlugin.java | 3 +- .../plugins/profile/ns/NSProfilePlugin.java | 2 +- .../profile/simple/SimpleProfilePlugin.java | 3 +- .../pump/common/PumpPluginAbstract.java | 49 +++++------ .../plugins/pump/danaR/DanaRPlugin.java | 50 +++++------ .../danaR/comm/MsgInitConnStatusTime.java | 2 +- .../danaR/services/DanaRExecutionService.java | 66 ++++++++------- .../pump/danaRKorean/DanaRKoreanPlugin.java | 52 ++++++------ .../comm/MsgInitConnStatusTime_k.java | 2 +- .../services/DanaRKoreanExecutionService.java | 67 ++++++++------- .../plugins/pump/danaRS/DanaRSPlugin.java | 19 +++-- .../pump/danaRS/services/DanaRSService.java | 39 ++++++--- .../plugins/pump/danaRv2/DanaRv2Plugin.java | 23 +++--- .../pump/danaRv2/comm/MsgCheckValue_v2.java | 4 +- .../services/DanaRv2ExecutionService.java | 61 +++++++------- .../pump/virtual/VirtualPumpPlugin.java | 23 +++--- .../TreatmentsProfileSwitchFragment.java | 41 ++++++---- .../receivers/KeepAliveReceiver.java | 3 +- .../androidaps/services/LocationService.java | 26 +++--- .../setupwizard/SetupWizardActivity.java | 20 ++--- .../setupwizard/elements/SWItem.java | 1 - 48 files changed, 582 insertions(+), 517 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 83dab8130d..cca6fb3100 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -52,6 +52,7 @@ import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.general.versionChecker.VersionCheckerUtilsKt; @@ -63,9 +64,12 @@ import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.PasswordProtection; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; public class MainActivity extends NoSplashAppCompatActivity { private static Logger log = LoggerFactory.getLogger(L.CORE); + private CompositeDisposable disposable = new CompositeDisposable(); protected PowerManager.WakeLock mWakeLock; @@ -99,7 +103,6 @@ public class MainActivity extends NoSplashAppCompatActivity { doMigrations(); - registerBus(); setupTabs(); setupViews(false); @@ -142,6 +145,36 @@ public class MainActivity extends NoSplashAppCompatActivity { @Override protected void onResume() { super.onResume(); + MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventRefreshGui.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + String lang = SP.getString(R.string.key_language, "en"); + LocaleHelper.setLocale(getApplicationContext(), lang); + if (event.getRecreate()) { + recreate(); + } else { + try { // activity may be destroyed + setupTabs(); + setupViews(false); + } catch (IllegalStateException e) { + log.error("Unhandled exception", e); + } + } + + boolean keepScreenOn = Config.NSCLIENT && SP.getBoolean(R.string.key_keep_screen_on, false); + if (keepScreenOn) + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + else + getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> onEventPreferenceChange(event), FabricPrivacy::logException) + ); if (L.isEnabled(L.CORE)) log.debug("onResume"); @@ -160,7 +193,9 @@ public class MainActivity extends NoSplashAppCompatActivity { AndroidPermission.notifyForSMSPermissions(this); } - MainApp.bus().post(new EventFeatureRunning(EventFeatureRunning.Feature.MAIN)); + MainApp.bus(). + + post(new EventFeatureRunning(EventFeatureRunning.Feature.MAIN)); } @Override @@ -173,7 +208,13 @@ public class MainActivity extends NoSplashAppCompatActivity { super.onDestroy(); } - @Subscribe + @Override + public void onPause() { + super.onPause(); + MainApp.bus().unregister(this); + disposable.clear(); + } + public void onEventPreferenceChange(final EventPreferenceChange ev) { if (ev.isChanged(R.string.key_keep_screen_on)) { boolean keepScreenOn = SP.getBoolean(R.string.key_keep_screen_on, false); @@ -189,30 +230,6 @@ public class MainActivity extends NoSplashAppCompatActivity { } } - @Subscribe - public void onStatusEvent(final EventRefreshGui ev) { - String lang = SP.getString(R.string.key_language, "en"); - LocaleHelper.setLocale(getApplicationContext(), lang); - runOnUiThread(() -> { - if (ev.recreate) { - recreate(); - } else { - try { // activity may be destroyed - setupTabs(); - setupViews(false); - } catch (IllegalStateException e) { - log.error("Unhandled exception", e); - } - } - - boolean keepScreenOn = Config.NSCLIENT && SP.getBoolean(R.string.key_keep_screen_on, false); - if (keepScreenOn) - getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - else - getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - }); - } - private void setupViews(boolean switchToLast) { TabPageAdapter pageAdapter = new TabPageAdapter(getSupportFragmentManager(), this); NavigationView navigationView = findViewById(R.id.navigation_view); @@ -264,15 +281,6 @@ public class MainActivity extends NoSplashAppCompatActivity { } } - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); - } - private void checkEula() { //SP.removeBoolean(R.string.key_i_understand); boolean IUnderstand = SP.getBoolean(R.string.key_i_understand, false); @@ -405,7 +413,7 @@ public class MainActivity extends NoSplashAppCompatActivity { case R.id.nav_exit: log.debug("Exiting"); MainApp.instance().stopKeepAliveService(); - MainApp.bus().post(new EventAppExit()); + RxBus.INSTANCE.send(new EventAppExit()); MainApp.closeDbHelper(); finish(); System.runFinalization(); diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java index 5096a82250..941366f8f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -68,17 +68,16 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - MainApp.bus().post(new EventPreferenceChange(key)); RxBus.INSTANCE.send(new EventPreferenceChange(key)); if (key.equals("language")) { String lang = sharedPreferences.getString("language", "en"); LocaleHelper.setLocale(getApplicationContext(), lang); - MainApp.bus().post(new EventRefreshGui(true)); + RxBus.INSTANCE.send(new EventRefreshGui(true)); //recreate() does not update language so better close settings finish(); } if (key.equals("short_tabtitles")) { - MainApp.bus().post(new EventRefreshGui()); + RxBus.INSTANCE.send(new EventRefreshGui()); } if (key.equals(MainApp.gs(R.string.key_openapsama_useautosens)) && SP.getBoolean(R.string.key_openapsama_useautosens, false)) { OKDialog.show(this, MainApp.gs(R.string.configbuilder_sensitivity), MainApp.gs(R.string.sensitivity_warning), null); diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index f1763e8aa8..338a662201 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -1720,7 +1720,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventProfileNeedsUpdate"); RxBus.INSTANCE.send(new EventReloadProfileSwitchData()); - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); scheduledProfileSwitchEventPost = null; } } diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java b/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java deleted file mode 100644 index 9ce91a9a39..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 07.07.2016. - */ -public class EventAppExit extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt b/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt new file mode 100644 index 0000000000..640b586f5f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventAppExit : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java deleted file mode 100644 index f23d4e802a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java +++ /dev/null @@ -1,25 +0,0 @@ -package info.nightscout.androidaps.events; - -import info.nightscout.androidaps.MainApp; - -/** - * Created by mike on 19.06.2016. - */ -public class EventPreferenceChange extends Event { - public String changedKey; - public EventPreferenceChange(String key) { - changedKey = key; - } - - public EventPreferenceChange(int resourceID) { - changedKey = MainApp.gs(resourceID); - } - - public boolean isChanged(int id) { - return changedKey.equals(MainApp.gs(id)); - } - - public boolean isChanged(String id) { - return changedKey.equals(id); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt new file mode 100644 index 0000000000..d224d75df1 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.events + +import info.nightscout.androidaps.MainApp + +class EventPreferenceChange : Event { + private var changedKey: String? = null + + constructor(key: String) { + changedKey = key + } + + constructor(resourceID: Int) { + changedKey = MainApp.gs(resourceID) + } + + fun isChanged(id: Int): Boolean { + return changedKey == MainApp.gs(id) + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.java deleted file mode 100644 index 9e3f3b08c7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 02.06.2017. - */ - -public class EventProfileNeedsUpdate extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt b/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt new file mode 100644 index 0000000000..2baf1db945 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventProfileNeedsUpdate : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java deleted file mode 100644 index 0b2d933c12..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.events; - -public class EventProfileStoreChanged extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt new file mode 100644 index 0000000000..0e839ca2d3 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventProfileStoreChanged : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java deleted file mode 100644 index 390ad8ea4f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 13.06.2016. - */ -public class EventRefreshGui extends Event { - public boolean recreate = false; - public EventRefreshGui(boolean recreate) { - this.recreate = recreate; - } - public EventRefreshGui(){ - this(false); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.kt b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.kt new file mode 100644 index 0000000000..724adaae91 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventRefreshGui @JvmOverloads constructor(var recreate: Boolean = false) : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java index 7b1d0c6175..ef83e535f6 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java @@ -81,7 +81,7 @@ public abstract class PluginBase { setFragmentVisible(type, enabled); ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, getType()); ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled"); - MainApp.bus().post(new EventRefreshGui()); + RxBus.INSTANCE.send(new EventRefreshGui()); MainApp.bus().post(new EventConfigBuilderChange()); RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui()); ConfigBuilderPlugin.getPlugin().logPluginStatus(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt index ddb5356f70..0821728fe2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt @@ -9,6 +9,7 @@ import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.events.EventRefreshGui import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.PasswordProtection class PluginViewHolder internal constructor(private val fragment: ConfigBuilderFragment, @@ -34,7 +35,7 @@ class PluginViewHolder internal constructor(private val fragment: ConfigBuilderF pluginVisibility.setOnClickListener { plugin.setFragmentVisible(pluginType, pluginVisibility.isChecked) ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxVisible") - MainApp.bus().post(EventRefreshGui()) + RxBus.send(EventRefreshGui()) ConfigBuilderPlugin.getPlugin().logPluginStatus() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java index e9bd53bcf3..025d8dac1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.configBuilder; import android.content.Intent; import android.os.Bundle; + import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,9 +29,12 @@ 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 io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class ProfileFunctions { private static Logger log = LoggerFactory.getLogger(L.PROFILE); + private CompositeDisposable disposable = new CompositeDisposable(); private static ProfileFunctions profileFunctions = null; @@ -45,29 +48,30 @@ public class ProfileFunctions { ProfileFunctions.getInstance(); // register to bus at start } - ProfileFunctions() { - MainApp.bus().register(this); - } - - @Subscribe - public void onProfileSwitch(EventProfileNeedsUpdate ignored) { - if (L.isEnabled(L.PROFILE)) - log.debug("onProfileSwitch"); - ConfigBuilderPlugin.getPlugin().getCommandQueue().setProfile(getProfile(), new Callback() { - @Override - public void run() { - if (!result.success) { - Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); - i.putExtra("soundid", R.raw.boluserror); - i.putExtra("status", result.comment); - i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile)); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); - } - if (result.enacted) - RxBus.INSTANCE.send(new EventNewBasalProfile()); - } - }); + private ProfileFunctions() { + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileNeedsUpdate.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.PROFILE)) + log.debug("onProfileSwitch"); + ConfigBuilderPlugin.getPlugin().getCommandQueue().setProfile(getProfile(), new Callback() { + @Override + public void run() { + if (!result.success) { + Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); + i.putExtra("soundid", R.raw.boluserror); + i.putExtra("status", result.comment); + i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile)); + i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + MainApp.instance().startActivity(i); + } + if (result.enacted) + RxBus.INSTANCE.send(new EventNewBasalProfile()); + } + }); + }, FabricPrivacy::logException) + ); } public String getProfileName() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java index ea56115347..7a801a44c0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java @@ -28,6 +28,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.utils.OKDialog; import info.nightscout.androidaps.utils.ToastUtils; @@ -136,7 +137,7 @@ public class ImportExportPrefs { OKDialog.show(context, MainApp.gs(R.string.setting_imported), MainApp.gs(R.string.restartingapp), () -> { log.debug("Exiting"); MainApp.instance().stopKeepAliveService(); - MainApp.bus().post(new EventAppExit()); + RxBus.INSTANCE.send(new EventAppExit()); MainApp.closeDbHelper(); if (context instanceof Activity) { ((Activity)context).finish(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index cb069bf58d..150e75a119 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -22,7 +22,6 @@ import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventChargingState; import info.nightscout.androidaps.events.EventNetworkChange; @@ -31,6 +30,7 @@ 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.general.nsclient.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; @@ -121,6 +121,21 @@ public class NSClientPlugin extends PluginBase { .observeOn(Schedulers.io()) .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (nsClientService != null) { + MainApp.instance().getApplicationContext().unbindService(mConnection); + nsClientReceiverDelegate.unregisterReceivers(); + } + }, FabricPrivacy::logException) + ); } @Override @@ -134,11 +149,6 @@ public class NSClientPlugin extends PluginBase { super.onStop(); } - @Subscribe - public void onStatusEvent(EventPreferenceChange ev) { - nsClientReceiverDelegate.onStatusEvent(ev); - } - @Subscribe public void onStatusEvent(final EventChargingState ev) { nsClientReceiverDelegate.onStatusEvent(ev); @@ -161,14 +171,6 @@ public class NSClientPlugin extends PluginBase { } }; - @Subscribe - public void onStatusEvent(final EventAppExit ignored) { - if (nsClientService != null) { - MainApp.instance().getApplicationContext().unbindService(mConnection); - nsClientReceiverDelegate.unregisterReceivers(); - } - } - @Subscribe public void onStatusEvent(final EventNSClientNewLog ev) { addToLog(ev); @@ -220,7 +222,6 @@ public class NSClientPlugin extends PluginBase { public void pause(boolean newState) { SP.putBoolean(R.string.key_nsclientinternal_paused, newState); paused = newState; - MainApp.bus().post(new EventPreferenceChange(R.string.key_nsclientinternal_paused)); RxBus.INSTANCE.send(new EventPreferenceChange(R.string.key_nsclientinternal_paused)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java index f7df37aa0f..31bd7305e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java @@ -99,7 +99,6 @@ class NsClientReceiverDelegate { boolean newAllowedState = allowedChargingState && allowedNetworkState; if (newAllowedState != allowed) { allowed = newAllowedState; - bus.post(new EventPreferenceChange(R.string.key_nsclientinternal_paused)); RxBus.INSTANCE.send(new EventPreferenceChange(R.string.key_nsclientinternal_paused)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index d360acd9c3..ab964ccac6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -117,17 +117,6 @@ public class NSClientService extends Service { public NSClientService() { registerBus(); - disposable.add(RxBus.INSTANCE - .toObservable(EventConfigBuilderChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> { - if (nsEnabled != NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL)) { - latestDateInReceivedData = 0; - destroy(); - initialize(); - } - }, FabricPrivacy::logException) - ); if (handler == null) { HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler"); handlerThread.start(); @@ -143,11 +132,47 @@ public class NSClientService extends Service { public void onCreate() { super.onCreate(); mWakeLock.acquire(); + disposable.add(RxBus.INSTANCE + .toObservable(EventConfigBuilderChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (nsEnabled != NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL)) { + latestDateInReceivedData = 0; + destroy(); + initialize(); + } + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (event.isChanged(R.string.key_nsclientinternal_url) || + event.isChanged(R.string.key_nsclientinternal_api_secret) || + event.isChanged(R.string.key_nsclientinternal_paused) + ) { + latestDateInReceivedData = 0; + destroy(); + initialize(); + } + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.NSCLIENT)) + log.debug("EventAppExit received"); + destroy(); + stopSelf(); + }, FabricPrivacy::logException) + ); } @Override public void onDestroy() { super.onDestroy(); + disposable.clear(); if (mWakeLock.isHeld()) mWakeLock.release(); } @@ -177,28 +202,6 @@ public class NSClientService extends Service { MainApp.bus().register(this); } - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.NSCLIENT)) - log.debug("EventAppExit received"); - - destroy(); - - stopSelf(); - } - - @Subscribe - public void onStatusEvent(EventPreferenceChange ev) { - if (ev.isChanged(R.string.key_nsclientinternal_url) || - ev.isChanged(R.string.key_nsclientinternal_api_secret) || - ev.isChanged(R.string.key_nsclientinternal_paused) - ) { - latestDateInReceivedData = 0; - destroy(); - initialize(); - } - } - @Subscribe public void onStatusEvent(final EventNSClientRestart ev) { latestDateInReceivedData = 0; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index e88fe59c80..b57ab1d35d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -924,6 +924,18 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, .subscribe(event -> scheduleUpdateGUI("EventAutosensCalculationFinished"), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileNeedsUpdate.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventProfileNeedsUpdate"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventPreferenceChange"), + FabricPrivacy::logException + )); disposable.add(RxBus.INSTANCE .toObservable(EventPumpStatusChanged.class) .observeOn(AndroidSchedulers.mainThread()) @@ -941,21 +953,11 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, updateGUI("onResume"); } - @Subscribe - public void onStatusEvent(final EventPreferenceChange ev) { - scheduleUpdateGUI("EventPreferenceChange"); - } - @Subscribe public void onStatusEvent(final EventNewOpenLoopNotification ev) { scheduleUpdateGUI("EventNewOpenLoopNotification"); } - @Subscribe - public void onStatusEvent(final EventProfileNeedsUpdate ev) { - scheduleUpdateGUI("EventProfileNeedsUpdate"); - } - @Subscribe public void onStatusEvent(final EventIobCalculationProgress e) { Activity activity = getActivity(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java index 13310d70a8..007298ac76 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java @@ -1,26 +1,27 @@ package info.nightscout.androidaps.plugins.general.persistentNotification; -import android.app.Notification; import android.app.Service; import android.content.Intent; import android.os.IBinder; import androidx.annotation.Nullable; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Keeps AndroidAPS in foreground state, so it won't be terminated by Android nor get restricted by the background execution limits */ public class DummyService extends Service { private static Logger log = LoggerFactory.getLogger(L.CORE); + private CompositeDisposable disposable = new CompositeDisposable(); @Nullable @Override @@ -28,6 +29,30 @@ public class DummyService extends Service { return null; } + @Override + public void onCreate() { + super.onCreate(); + // TODO: I guess this was moved here in order to adhere to the 5 seconds rule to call "startForeground" after a Service was called as Foreground service? + // As onCreate() is not called every time a service is started, copied to onStartCommand(). + startForeground(PersistentNotificationPlugin.ONGOING_NOTIFICATION_ID, PersistentNotificationPlugin.getPlugin().getLastNotification()); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received"); + stopSelf(); + }, FabricPrivacy::logException) + ); + } + + @Override + public void onDestroy() { + if (L.isEnabled(L.CORE)) log.debug("onDestroy"); + disposable.clear(); + super.onDestroy(); + stopForeground(true); + } + @Override public int onStartCommand(Intent intent, int flags, int startId) { super.onStartCommand(intent, flags, startId); @@ -35,28 +60,4 @@ public class DummyService extends Service { return START_STICKY; } - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.CORE)) - log.debug("EventAppExit received"); - - stopSelf(); - } - - @Override - public void onCreate() { - super.onCreate(); - // TODO: I guess this was moved here in order to adhere to the 5 seconds rule to call "startForeground" after a Service was called as Foreground service? - // As onCreate() is not called every time a service is started, copied to onStartCommand(). - startForeground(PersistentNotificationPlugin.ONGOING_NOTIFICATION_ID, PersistentNotificationPlugin.getPlugin().getLastNotification()); - MainApp.bus().register(this); - } - - @Override - public void onDestroy() { - if (L.isEnabled(L.CORE)) - log.debug("onDestroy"); - MainApp.bus().unregister(this); - stopForeground(true); - } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java index c6b24d6438..fdee040682 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java @@ -15,8 +15,6 @@ import androidx.core.app.NotificationCompat; import androidx.core.app.RemoteInput; import androidx.core.app.TaskStackBuilder; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -95,7 +93,6 @@ public class PersistentNotificationPlugin extends PluginBase { protected void onStart() { super.onStart(); createNotificationChannel(); // make sure channels exist before triggering updates through the bus - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventRefreshOverview.class) .observeOn(Schedulers.io()) @@ -138,6 +135,12 @@ public class PersistentNotificationPlugin extends PluginBase { .subscribe(event -> triggerNotificationUpdate(false), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> triggerNotificationUpdate(false), + FabricPrivacy::logException + )); triggerNotificationUpdate(true); } @@ -155,7 +158,6 @@ public class PersistentNotificationPlugin extends PluginBase { @Override protected void onStop() { - MainApp.bus().unregister(this); disposable.clear(); MainApp.instance().stopService(new Intent(MainApp.instance(), DummyService.class)); super.onStop(); @@ -332,11 +334,4 @@ public class PersistentNotificationPlugin extends PluginBase { throw new IllegalStateException("Notification is null"); } } - - - @Subscribe - public void onStatusEvent(final EventPreferenceChange ev) { - triggerNotificationUpdate(false); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java index 8cc81a901a..e14b3878b1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java @@ -25,6 +25,7 @@ import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; +import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.Constraint; @@ -50,15 +51,19 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.SafeParse; import info.nightscout.androidaps.utils.XdripCalibrations; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 05.08.2016. */ public class SmsCommunicatorPlugin extends PluginBase { private static Logger log = LoggerFactory.getLogger(L.SMS); + private CompositeDisposable disposable = new CompositeDisposable(); private static SmsCommunicatorPlugin smsCommunicatorPlugin; @@ -92,18 +97,23 @@ public class SmsCommunicatorPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); super.onStart(); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + processSettings(event); + }, FabricPrivacy::logException) + ); } @Override protected void onStop() { - MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } - @Subscribe - public void processSettings(final EventPreferenceChange ev) { + private void processSettings(final EventPreferenceChange ev) { if (ev == null || ev.isChanged(R.string.key_smscommunicator_allowednumbers)) { String settings = SP.getString(R.string.key_smscommunicator_allowednumbers, ""); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java index f207bd2c84..8816cf58cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.general.wear; import android.content.Context; import android.content.Intent; -import android.util.Log; import com.squareup.otto.Subscribe; @@ -28,7 +27,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutos import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; /** @@ -114,6 +112,17 @@ public class WearPlugin extends PluginBase { .subscribe(event -> sendDataToWatch(true, true, true), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + // possibly new high or low mark + resendDataToWatch(); + // status may be formated differently + sendDataToWatch(true, false, false); + }, + FabricPrivacy::logException + )); disposable.add(RxBus.INSTANCE .toObservable(EventRefreshOverview.class) .observeOn(Schedulers.io()) @@ -173,14 +182,6 @@ public class WearPlugin extends PluginBase { } - @Subscribe - public void onStatusEvent(final EventPreferenceChange ev) { - // possibly new high or low mark - resendDataToWatch(); - // status may be formated differently - sendDataToWatch(true, false, false); - } - @Subscribe public void onStatusEvent(final EventOverviewBolusProgress ev) { if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index fec423ea66..2713a0ef08 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -128,6 +128,12 @@ public class StatuslinePlugin extends PluginBase { .subscribe(event -> sendStatus(), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); } @Override @@ -207,12 +213,6 @@ public class StatuslinePlugin extends PluginBase { } - @Subscribe - public void onStatusEvent(final EventPreferenceChange ev) { - // status may be formated differently - sendStatus(); - } - @Subscribe public void onStatusEvent(final EventAppInitialized ev) { sendStatus(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index 2db1f2dc35..e5aec47b43 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -151,6 +151,36 @@ public class IobCobCalculatorPlugin extends PluginBase { runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, event); }, FabricPrivacy::logException) ); + // EventPreferenceChange + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (this != getPlugin()) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); + return; + } + if (event.isChanged(R.string.key_openapsama_autosens_period) || + event.isChanged(R.string.key_age) || + event.isChanged(R.string.key_absorption_maxtime) || + event.isChanged(R.string.key_openapsama_min_5m_carbimpact) || + event.isChanged(R.string.key_absorption_cutoff) || + event.isChanged(R.string.key_openapsama_autosens_max) || + event.isChanged(R.string.key_openapsama_autosens_min) + ) { + stopCalculation("onEventPreferenceChange"); + synchronized (dataLock) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records" + " BasalData: " + basalDataTable.size() + " records"); + iobTable = new LongSparseArray<>(); + autosensDataTable = new LongSparseArray<>(); + basalDataTable = new LongSparseArray<>(); + } + runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, event); + } + }, FabricPrivacy::logException) + ); } @Override @@ -730,33 +760,6 @@ public class IobCobCalculatorPlugin extends PluginBase { } } - @Subscribe - public void onEventPreferenceChange(EventPreferenceChange ev) { - if (this != getPlugin()) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Ignoring event for non default instance"); - return; - } - if (ev.isChanged(R.string.key_openapsama_autosens_period) || - ev.isChanged(R.string.key_age) || - ev.isChanged(R.string.key_absorption_maxtime) || - ev.isChanged(R.string.key_openapsama_min_5m_carbimpact) || - ev.isChanged(R.string.key_absorption_cutoff) || - ev.isChanged(R.string.key_openapsama_autosens_max) || - ev.isChanged(R.string.key_openapsama_autosens_min) - ) { - stopCalculation("onEventPreferenceChange"); - synchronized (dataLock) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records" + " BasalData: " + basalDataTable.size() + " records"); - iobTable = new LongSparseArray<>(); - autosensDataTable = new LongSparseArray<>(); - basalDataTable = new LongSparseArray<>(); - } - runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, ev); - } - } - // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated @Subscribe public void onEventNewHistoryData(EventNewHistoryData ev) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java index 089611b40d..e3e068c1cb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java @@ -18,6 +18,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.SP; @@ -83,7 +84,7 @@ public class LocalProfilePlugin extends PluginBase implements ProfileInterface { edited = false; if (L.isEnabled(L.PROFILE)) log.debug("Storing settings: " + getRawProfile().getData().toString()); - MainApp.bus().post(new EventProfileStoreChanged()); + RxBus.INSTANCE.send(new EventProfileStoreChanged()); } public synchronized void loadSettings() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java index a6088f5515..0dd48fa0bb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java @@ -78,7 +78,7 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface { profile = new ProfileStore(new JSONObject(profileString)); storeNSProfile(); if (isEnabled(PluginType.PROFILE)) { - MainApp.bus().post(new EventProfileStoreChanged()); + RxBus.INSTANCE.send(new EventProfileStoreChanged()); RxBus.INSTANCE.send(new EventNSProfileUpdateGUI()); } if (L.isEnabled(L.PROFILE)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java index d3d3952fae..61ca403f55 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java @@ -19,6 +19,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.utils.SP; /** @@ -75,7 +76,7 @@ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface createConvertedProfile(); if (L.isEnabled(L.PROFILE)) log.debug("Storing settings: " + getRawProfile().getData().toString()); - MainApp.bus().post(new EventProfileStoreChanged()); + RxBus.INSTANCE.send(new EventProfileStoreChanged()); } private void loadSettings() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index fa68e55616..496859f38f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -6,8 +6,6 @@ import android.content.ServiceConnection; import androidx.fragment.app.FragmentActivity; -import com.squareup.otto.Subscribe; - import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -31,6 +29,7 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; @@ -39,6 +38,9 @@ import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by andy on 23.04.18. @@ -47,13 +49,14 @@ import info.nightscout.androidaps.utils.DecimalFormatter; // When using this class, make sure that your first step is to create mConnection (see MedtronicPumpPlugin) public abstract class PumpPluginAbstract extends PluginBase implements PumpInterface, ConstraintsInterface { + private CompositeDisposable disposable = new CompositeDisposable(); private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false) - .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver)); + .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver)); protected static final PumpEnactResult OPERATION_NOT_YET_SUPPORTED = new PumpEnactResult().success(false) - .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump)); + .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump)); protected PumpDescription pumpDescription = new PumpDescription(); protected PumpStatus pumpStatus; @@ -80,15 +83,21 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter @Override protected void onStart() { + super.onStart(); Context context = MainApp.instance().getApplicationContext(); Intent intent = new Intent(context, getServiceClass()); context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE); serviceRunning = true; - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + MainApp.instance().getApplicationContext().unbindService(serviceConnection); + }, FabricPrivacy::logException) + ); onStartCustomActions(); - super.onStart(); } @@ -99,7 +108,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter serviceRunning = false; - MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } @@ -121,14 +130,6 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter */ public abstract Class getServiceClass(); - - @SuppressWarnings("UnusedParameters") - @Subscribe - public void onStatusEvent(final EventAppExit e) { - MainApp.instance().getApplicationContext().unbindService(serviceConnection); - } - - public PumpStatus getPumpStatusData() { return pumpStatus; } @@ -239,7 +240,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter @Override public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, - boolean enforceNew) { + boolean enforceNew) { if (isLoggingEnabled()) LOG.warn("setTempBasalAbsolute [PumpPluginAbstract] - Not implemented."); return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver); @@ -248,7 +249,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter @Override public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, - boolean enforceNew) { + boolean enforceNew) { if (isLoggingEnabled()) LOG.warn("setTempBasalPercent [PumpPluginAbstract] - Not implemented."); return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver); @@ -340,7 +341,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); if (tb != null) { extended.put("TempBasalAbsoluteRate", - tb.tempBasalConvertedToAbsolute(System.currentTimeMillis(), profile)); + tb.tempBasalConvertedToAbsolute(System.currentTimeMillis(), profile)); extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)); extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); } @@ -372,20 +373,20 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter String ret = ""; if (pumpStatus.lastConnection != 0) { Long agoMsec = System.currentTimeMillis() - pumpStatus.lastConnection; - int agoMin = (int)(agoMsec / 60d / 1000d); + int agoMin = (int) (agoMsec / 60d / 1000d); ret += "LastConn: " + agoMin + " min ago\n"; } if (pumpStatus.lastBolusTime != null && pumpStatus.lastBolusTime.getTime() != 0) { ret += "LastBolus: " + DecimalFormatter.to2Decimal(pumpStatus.lastBolusAmount) + "U @" + // - android.text.format.DateFormat.format("HH:mm", pumpStatus.lastBolusTime) + "\n"; + android.text.format.DateFormat.format("HH:mm", pumpStatus.lastBolusTime) + "\n"; } TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin() - .getRealTempBasalFromHistory(System.currentTimeMillis()); + .getRealTempBasalFromHistory(System.currentTimeMillis()); if (activeTemp != null) { ret += "Temp: " + activeTemp.toStringFull() + "\n"; } ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory( - System.currentTimeMillis()); + System.currentTimeMillis()); if (activeExtendedBolus != null) { ret += "Extended: " + activeExtendedBolus.toString() + "\n"; } @@ -409,7 +410,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter if (isLoggingEnabled()) LOG.error("deliverTreatment: Invalid input"); return new PumpEnactResult().success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d) - .comment(MainApp.gs(R.string.danar_invalidinput)); + .comment(MainApp.gs(R.string.danar_invalidinput)); } else if (detailedBolusInfo.insulin > 0) { // bolus needed, ask pump to deliver it return deliverBolus(detailedBolusInfo); @@ -427,7 +428,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter LOG.debug("deliverTreatment: Carb only treatment."); return new PumpEnactResult().success(true).enacted(true).bolusDelivered(0d) - .carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok)); + .carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok)); } } finally { triggerUIChange(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index 6a01c5fed8..402f2f0ea7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -5,8 +5,6 @@ import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; -import androidx.fragment.app.FragmentActivity; -import androidx.appcompat.app.AlertDialog; import com.squareup.otto.Subscribe; @@ -22,19 +20,23 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed; import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 05.08.2016. */ public class DanaRPlugin extends AbstractDanaRPlugin { + private CompositeDisposable disposable = new CompositeDisposable(); private static DanaRPlugin plugin = null; @@ -55,7 +57,27 @@ public class DanaRPlugin extends AbstractDanaRPlugin { Context context = MainApp.instance().getApplicationContext(); Intent intent = new Intent(context, DanaRExecutionService.class); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (isEnabled(PluginType.PUMP)) { + boolean previousValue = useExtendedBoluses; + useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false); + + if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { + sExecutionService.extendedBolusStop(); + } + } + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + MainApp.instance().getApplicationContext().unbindService(mConnection); + }, FabricPrivacy::logException) + ); super.onStart(); } @@ -64,7 +86,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin { Context context = MainApp.instance().getApplicationContext(); context.unbindService(mConnection); - MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } @@ -84,24 +106,6 @@ public class DanaRPlugin extends AbstractDanaRPlugin { } }; - @SuppressWarnings("UnusedParameters") - @Subscribe - public void onStatusEvent(final EventAppExit e) { - MainApp.instance().getApplicationContext().unbindService(mConnection); - } - - @Subscribe - public void onStatusEvent(final EventPreferenceChange s) { - if (isEnabled(PluginType.PUMP)) { - boolean previousValue = useExtendedBoluses; - useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false); - - if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { - sExecutionService.extendedBolusStop(); - } - } - } - // Plugin base interface @Override public String getName() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java index 1ba35a3614..472fbeb829 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java @@ -47,7 +47,7 @@ public class MsgInitConnStatusTime extends MessageBase { } ConfigBuilderPlugin.getPlugin().storeSettings("ChangingDanaDriver"); - MainApp.bus().post(new EventRefreshGui()); + RxBus.INSTANCE.send(new EventRefreshGui()); ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection failed = false; return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index 49e79acd1d..f9029ca9aa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -67,15 +67,51 @@ import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class DanaRExecutionService extends AbstractDanaRExecutionService { + private CompositeDisposable disposable = new CompositeDisposable(); public DanaRExecutionService() { mBinder = new LocalBinder(); - registerBus(); MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); + } + + @Override + public void onCreate() { + super.onCreate(); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (mSerialIOThread != null) + mSerialIOThread.disconnect("EventPreferenceChange"); + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.PUMP)) + log.debug("EventAppExit received"); + + if (mSerialIOThread != null) + mSerialIOThread.disconnect("Application exit"); + MainApp.instance().getApplicationContext().unregisterReceiver(receiver); + stopSelf(); + }, FabricPrivacy::logException) + ); + } + + @Override + public void onDestroy() { + disposable.clear(); + super.onDestroy(); } public class LocalBinder extends Binder { @@ -84,21 +120,6 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } } - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); - } - - @Subscribe - public void onStatusEvent(final EventPreferenceChange pch) { - if (mSerialIOThread != null) - mSerialIOThread.disconnect("EventPreferenceChange"); - } - public void connect() { if (mConnectionInProgress) return; @@ -407,19 +428,6 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { return true; } - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); - - if (mSerialIOThread != null) - mSerialIOThread.disconnect("Application exit"); - - MainApp.instance().getApplicationContext().unregisterReceiver(receiver); - - stopSelf(); - } - public PumpEnactResult setUserOptions() { if (!isConnected()) return new PumpEnactResult().success(false); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java index 64eccf05f1..2645e25ade 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java @@ -5,10 +5,6 @@ import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; -import androidx.fragment.app.FragmentActivity; -import androidx.appcompat.app.AlertDialog; - -import com.squareup.otto.Subscribe; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -22,7 +18,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; @@ -30,13 +26,17 @@ import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStart; import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 05.08.2016. */ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { + private CompositeDisposable disposable = new CompositeDisposable(); private static DanaRKoreanPlugin plugin = null; @@ -58,7 +58,27 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { Context context = MainApp.instance().getApplicationContext(); Intent intent = new Intent(context, DanaRKoreanExecutionService.class); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (isEnabled(PluginType.PUMP)) { + boolean previousValue = useExtendedBoluses; + useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false); + + if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { + sExecutionService.extendedBolusStop(); + } + } + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + MainApp.instance().getApplicationContext().unbindService(mConnection); + }, FabricPrivacy::logException) + ); super.onStart(); } @@ -67,7 +87,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { Context context = MainApp.instance().getApplicationContext(); context.unbindService(mConnection); - MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } @@ -87,24 +107,6 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { } }; - @SuppressWarnings("UnusedParameters") - @Subscribe - public void onStatusEvent(final EventAppExit e) { - MainApp.instance().getApplicationContext().unbindService(mConnection); - } - - @Subscribe - public void onStatusEvent(final EventPreferenceChange s) { - if (isEnabled(PluginType.PUMP)) { - boolean previousValue = useExtendedBoluses; - useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false); - - if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) { - sExecutionService.extendedBolusStop(); - } - } - } - // Plugin base interface @Override public String getName() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java index 020bc3f3b5..6877fece07 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java @@ -49,7 +49,7 @@ public class MsgInitConnStatusTime_k extends MessageBase { } ConfigBuilderPlugin.getPlugin().storeSettings("ChangingKoreanDanaDriver"); - MainApp.bus().post(new EventRefreshGui()); + RxBus.INSTANCE.send(new EventRefreshGui()); ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection return; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index aed225b68d..dd2547c6eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -59,51 +59,58 @@ import info.nightscout.androidaps.plugins.pump.danaRKorean.comm.MsgStatusBasic_k import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { + private CompositeDisposable disposable = new CompositeDisposable(); public DanaRKoreanExecutionService() { mBinder = new LocalBinder(); - registerBus(); MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); } + @Override + public void onCreate() { + super.onCreate(); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (mSerialIOThread != null) + mSerialIOThread.disconnect("EventPreferenceChange"); + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.PUMP)) + log.debug("EventAppExit received"); + + if (mSerialIOThread != null) + mSerialIOThread.disconnect("Application exit"); + MainApp.instance().getApplicationContext().unregisterReceiver(receiver); + stopSelf(); + }, FabricPrivacy::logException) + ); + } + + @Override + public void onDestroy() { + disposable.clear(); + super.onDestroy(); + } + public class LocalBinder extends Binder { public DanaRKoreanExecutionService getServiceInstance() { return DanaRKoreanExecutionService.this; } } - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); - } - - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); - - if (mSerialIOThread != null) - mSerialIOThread.disconnect("Application exit"); - - MainApp.instance().getApplicationContext().unregisterReceiver(receiver); - - stopSelf(); - } - - @Subscribe - public void onStatusEvent(final EventPreferenceChange pch) { - if (mSerialIOThread != null) - mSerialIOThread.disconnect("EventPreferenceChange"); - } - public void connect() { if (mConnectionInProgress) return; @@ -173,7 +180,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index ef44cad527..4dea025521 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -59,9 +59,12 @@ import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 03.09.2017. @@ -69,6 +72,8 @@ import info.nightscout.androidaps.utils.T; public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface { private Logger log = LoggerFactory.getLogger(L.PUMP); + private CompositeDisposable disposable = new CompositeDisposable(); + private static DanaRSPlugin plugin = null; public static DanaRSPlugin getPlugin() { @@ -114,6 +119,13 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + MainApp.instance().getApplicationContext().unbindService(mConnection); + }, FabricPrivacy::logException) + ); onStatusEvent(new EventDanaRSDeviceChange()); // load device name super.onStart(); } @@ -124,6 +136,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte context.unbindService(mConnection); MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } @@ -148,12 +161,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } }; - @SuppressWarnings("UnusedParameters") - @Subscribe - public void onStatusEvent(final EventAppExit e) { - MainApp.instance().getApplicationContext().unbindService(mConnection); - } - @Subscribe public void onStatusEvent(final EventDanaRSDeviceChange e) { mDeviceAddress = SP.getString(R.string.key_danars_address, ""); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index eb8ece1c06..5e6de8f5cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -6,8 +6,6 @@ import android.os.Binder; import android.os.IBinder; import android.os.SystemClock; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +25,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; @@ -80,12 +79,15 @@ import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class DanaRSService extends Service { private Logger log = LoggerFactory.getLogger(L.PUMPCOMM); + private CompositeDisposable disposable = new CompositeDisposable(); private BLEComm bleComm = BLEComm.getInstance(this); @@ -105,6 +107,25 @@ public class DanaRSService extends Service { MainApp.bus().register(this); } + @Override + public void onCreate() { + super.onCreate(); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received"); + stopSelf(); + }, FabricPrivacy::logException) + ); + } + + @Override + public void onDestroy() { + disposable.clear(); + super.onDestroy(); + } + public boolean isConnected() { return bleComm.isConnected; } @@ -150,7 +171,7 @@ public class DanaRSService extends Service { RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate()); // basal profile, basalStep, maxBasal if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); } } @@ -250,7 +271,7 @@ public class DanaRSService extends Service { } else { msg = new DanaRS_Packet_APS_History_Events(lastHistoryFetched); if (L.isEnabled(L.PUMPCOMM)) - log.debug("Loading event history from: " +DateUtil.dateAndTimeFullString(lastHistoryFetched)); + log.debug("Loading event history from: " + DateUtil.dateAndTimeFullString(lastHistoryFetched)); } bleComm.sendMessage(msg); while (!msg.done && bleComm.isConnected()) { @@ -529,14 +550,6 @@ public class DanaRSService extends Service { return START_STICKY; } - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); - - stopSelf(); - } - void waitForWholeMinute() { while (true) { long time = DateUtil.now(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index 94e6929d21..3437d37656 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -6,8 +6,6 @@ import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -17,6 +15,7 @@ import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; @@ -26,14 +25,18 @@ import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2Execution import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 05.08.2016. */ public class DanaRv2Plugin extends AbstractDanaRPlugin { + private CompositeDisposable disposable = new CompositeDisposable(); private static DanaRv2Plugin plugin = null; @@ -56,7 +59,13 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { Intent intent = new Intent(context, DanaRv2ExecutionService.class); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + MainApp.instance().getApplicationContext().unbindService(mConnection); + }, FabricPrivacy::logException) + ); super.onStart(); } @@ -65,7 +74,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { Context context = MainApp.instance().getApplicationContext(); context.unbindService(mConnection); - MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } @@ -85,12 +94,6 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { } }; - @SuppressWarnings("UnusedParameters") - @Subscribe - public void onStatusEvent(final EventAppExit e) { - MainApp.instance().getApplicationContext().unbindService(mConnection); - } - // Plugin base interface @Override public String getName() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java index f5341f033c..310d5456fe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java @@ -61,7 +61,7 @@ public class MsgCheckValue_v2 extends MessageBase { } ConfigBuilderPlugin.getPlugin().storeSettings("ChangingDanaRv2Driver"); - MainApp.bus().post(new EventRefreshGui()); + RxBus.INSTANCE.send(new EventRefreshGui()); ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection return; } @@ -84,7 +84,7 @@ public class MsgCheckValue_v2 extends MessageBase { } ConfigBuilderPlugin.getPlugin().storeSettings("ChangingDanaRv2Driver"); - MainApp.bus().post(new EventRefreshGui()); + RxBus.INSTANCE.send(new EventRefreshGui()); ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection return; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index b4f43f01e7..3dd68f1af3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -6,8 +6,6 @@ import android.content.IntentFilter; import android.os.Binder; import android.os.SystemClock; -import com.squareup.otto.Subscribe; - import java.io.IOException; import java.util.Date; @@ -74,17 +72,20 @@ import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { + private CompositeDisposable disposable = new CompositeDisposable(); private long lastHistoryFetched = 0; public DanaRv2ExecutionService() { mBinder = new LocalBinder(); - registerBus(); MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); } @@ -94,32 +95,36 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } } - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); + @Override + public void onCreate() { + super.onCreate(); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (mSerialIOThread != null) + mSerialIOThread.disconnect("EventPreferenceChange"); + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.PUMP)) + log.debug("EventAppExit received"); + + if (mSerialIOThread != null) + mSerialIOThread.disconnect("Application exit"); + MainApp.instance().getApplicationContext().unregisterReceiver(receiver); + stopSelf(); + }, FabricPrivacy::logException) + ); } - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.PUMP)) - log.debug("EventAppExit received"); - - if (mSerialIOThread != null) - mSerialIOThread.disconnect("Application exit"); - - MainApp.instance().getApplicationContext().unregisterReceiver(receiver); - - stopSelf(); - } - - @Subscribe - public void onStatusEvent(final EventPreferenceChange pch) { - if (mSerialIOThread != null) - mSerialIOThread.disconnect("EventPreferenceChange"); + @Override + public void onDestroy() { + disposable.clear(); + super.onDestroy(); } public void connect() { @@ -190,7 +195,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings))); mSerialIOThread.sendMessage(new MsgSettingBasal()); if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java index 514ee912ad..76dcdc6316 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java @@ -2,8 +2,6 @@ package info.nightscout.androidaps.plugins.pump.virtual; import android.os.SystemClock; -import com.squareup.otto.Subscribe; - import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -41,8 +39,11 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.InstanceId; import info.nightscout.androidaps.utils.SP; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** @@ -50,6 +51,7 @@ import info.nightscout.androidaps.utils.SP; */ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { private Logger log = LoggerFactory.getLogger(L.PUMP); + private CompositeDisposable disposable = new CompositeDisposable(); Integer batteryPercent = 50; Integer reservoirInUnits = 50; @@ -122,22 +124,23 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { @Override protected void onStart() { super.onStart(); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (event.isChanged(R.string.key_virtualpump_type)) + refreshConfiguration(); + }, FabricPrivacy::logException) + ); refreshConfiguration(); } @Override protected void onStop() { - MainApp.bus().unregister(this); + disposable.clear(); super.onStop(); } - @Subscribe - public void onStatusEvent(final EventPreferenceChange s) { - if (s.isChanged(R.string.key_virtualpump_type)) - refreshConfiguration(); - } - @Override public boolean isFakingTempsByExtendedBoluses() { return (Config.NSCLIENT) && fromNSAreCommingFakedExtendedBoluses; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java index 71d8eb2b18..1c338d54bd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -14,6 +14,7 @@ import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.cardview.widget.CardView; import androidx.core.content.ContextCompat; +import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; @@ -32,6 +33,7 @@ import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -39,14 +41,18 @@ import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; /** * Created by mike on 13/01/17. */ -public class TreatmentsProfileSwitchFragment extends SubscriberFragment implements View.OnClickListener { +public class TreatmentsProfileSwitchFragment extends Fragment implements View.OnClickListener { private Logger log = LoggerFactory.getLogger(L.UI); + private CompositeDisposable disposable = new CompositeDisposable(); RecyclerView recyclerView; LinearLayoutManager llm; @@ -195,10 +201,26 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen if (nsUploadOnly) refreshFromNS.setVisibility(View.GONE); - updateGUI(); return view; } + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileNeedsUpdate.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGUI(), FabricPrivacy::logException) + ); + updateGUI(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + @Override public void onClick(View view) { switch (view.getId()) { @@ -218,20 +240,7 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen } } - @Subscribe - public void onStatusEvent(final EventProfileNeedsUpdate ev) { - updateGUI(); - } - - @Override protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getProfileSwitchData(false)), false); - } - }); + recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getProfileSwitchData(false)), false); } } diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java index 7a9aa31c46..4c8a3f660e 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java @@ -16,6 +16,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.queue.commands.Command; @@ -73,7 +74,7 @@ public class KeepAliveReceiver extends BroadcastReceiver { } if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) { - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); } else if (isStatusOutdated && !pump.isBusy()) { lastReadStatus = System.currentTimeMillis(); ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("KeepAlive. Status outdated.", null); diff --git a/app/src/main/java/info/nightscout/androidaps/services/LocationService.java b/app/src/main/java/info/nightscout/androidaps/services/LocationService.java index 33f92d770a..9600515d6f 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/LocationService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/LocationService.java @@ -11,23 +11,24 @@ import android.os.IBinder; import androidx.core.app.ActivityCompat; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventLocationChange; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; import info.nightscout.androidaps.utils.T; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class LocationService extends Service { private static Logger log = LoggerFactory.getLogger(L.LOCATION); + private CompositeDisposable disposable = new CompositeDisposable(); private LocationManager mLocationManager = null; private static final float LOCATION_DISTANCE = 10f; @@ -125,7 +126,14 @@ public class LocationService extends Service { } catch (IllegalArgumentException ex) { log.error("network provider does not exist, " + ex.getMessage()); } - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppExit.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (L.isEnabled(L.CORE)) log.debug("EventAppExit received"); + stopSelf(); + }, FabricPrivacy::logException) + ); } @Override @@ -143,15 +151,7 @@ public class LocationService extends Service { log.error("fail to remove location listener, ignore", ex); } } - MainApp.bus().unregister(this); - } - - @Subscribe - public void onStatusEvent(EventAppExit event) { - if (L.isEnabled(L.CORE)) - log.debug("EventAppExit received"); - - stopSelf(); + disposable.clear(); } private void initializeLocationManager() { diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java index 05ab593bc7..cb68ce51a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java @@ -107,6 +107,16 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> updateButtons(), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileNeedsUpdate.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateButtons(), FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileStoreChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateButtons(), FabricPrivacy::logException) + ); } @Subscribe @@ -116,16 +126,6 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { updateButtons(); } - @Subscribe - public void onEventProfileStoreChanged(EventProfileStoreChanged ignored) { - updateButtons(); - } - - @Subscribe - public void onEventProfileSwitchChange(EventProfileNeedsUpdate ignored) { - updateButtons(); - } - private void generateLayout() { SWScreen currentScreen = screens.get(currentWizardPage); LinearLayout layout = SWItem.generateLayout(this.findViewById(R.id.sw_content_fields)); diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java index 6206cb0d9a..33e8e5ca85 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java @@ -98,7 +98,6 @@ public class SWItem { public void run() { if (L.isEnabled(L.CORE)) log.debug("Firing EventPreferenceChange"); - MainApp.bus().post(new EventPreferenceChange(preferenceId)); RxBus.INSTANCE.send(new EventPreferenceChange(preferenceId)); MainApp.bus().post(new EventSWUpdate()); scheduledEventPost = null; From 4ed8f0a1e11a08d3fd947d567280fdb7336ab81f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 23:35:24 +0200 Subject: [PATCH 06/13] Events to RxBus --- .../events/EventFoodDatabaseChanged.java | 8 - .../events/EventFoodDatabaseChanged.kt | 3 + .../androidaps/events/EventNsFood.java | 35 ---- .../androidaps/events/EventNsFood.kt | 19 ++ .../androidaps/events/EventNsTreatment.java | 36 ---- .../androidaps/events/EventNsTreatment.kt | 21 +++ .../androidaps/events/EventUpdateGui.java | 5 - .../androidaps/events/EventUpdateGui.kt | 4 + .../plugins/general/food/FoodFragment.java | 178 +++++++++--------- .../plugins/general/food/FoodService.java | 66 ++++--- .../plugins/treatments/TreatmentService.java | 33 ++-- .../androidaps/services/DataService.java | 20 +- 12 files changed, 199 insertions(+), 229 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java deleted file mode 100644 index 48e6be3a14..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 20.09.2017. - */ - -public class EventFoodDatabaseChanged extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt new file mode 100644 index 0000000000..83402c3cb6 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventFoodDatabaseChanged : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java deleted file mode 100644 index 90b6f5681b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.events; - -import android.os.Bundle; - -/** - * Event which is published with data fetched from NightScout specific for the - * Food-class. - * - * Payload is the from NS retrieved JSON-String which should be handled by all - * subscriber. - */ - -public class EventNsFood extends Event { - - public static final int ADD = 0; - public static final int UPDATE = 1; - public static final int REMOVE = 2; - - private final int mode; - - private final Bundle payload; - - public EventNsFood(int mode, Bundle payload) { - this.mode = mode; - this.payload = payload; - } - - public int getMode() { - return mode; - } - - public Bundle getPayload() { - return payload; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt new file mode 100644 index 0000000000..2f34e76c85 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.events + +import android.os.Bundle + +/** + * Event which is published with data fetched from NightScout specific for the + * Food-class. + * + * Payload is the from NS retrieved JSON-String which should be handled by all + * subscriber. + */ + +class EventNsFood(val mode: Int, val payload: Bundle) : Event() { + companion object { + val ADD = 0 + val UPDATE = 1 + val REMOVE = 2 + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java deleted file mode 100644 index 2c5ba6c9c0..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.events; - -import org.json.JSONObject; - - -/** - * Event which is published with data fetched from NightScout specific for the - * Treatment-class. - *

- * Payload is the from NS retrieved JSON-String which should be handled by all - * subscriber. - */ - -public class EventNsTreatment extends Event { - - public static final int ADD = 0; - public static final int UPDATE = 1; - public static final int REMOVE = 2; - - private final int mode; - - private final JSONObject payload; - - public EventNsTreatment(int mode, JSONObject payload) { - this.mode = mode; - this.payload = payload; - } - - public int getMode() { - return mode; - } - - public JSONObject getPayload() { - return payload; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt new file mode 100644 index 0000000000..149894c221 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.events + +import org.json.JSONObject + + +/** + * Event which is published with data fetched from NightScout specific for the + * Treatment-class. + * + * + * Payload is the from NS retrieved JSON-String which should be handled by all + * subscriber. + */ + +class EventNsTreatment(val mode: Int, val payload: JSONObject) : Event() { + companion object { + val ADD = 0 + val UPDATE = 1 + val REMOVE = 2 + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java deleted file mode 100644 index 3471d2e851..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.events; - -/** Base class for events to update the UI, mostly a specific tab. */ -public abstract class EventUpdateGui extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt new file mode 100644 index 0000000000..cc21e784b9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.events + +/** Base class for events to update the UI, mostly a specific tab. */ +abstract class EventUpdateGui : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java index 66727f0f7f..5e21b6efd7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java @@ -1,12 +1,8 @@ package info.nightscout.androidaps.plugins.general.food; -import android.app.Activity; import android.content.DialogInterface; import android.graphics.Paint; import android.os.Bundle; -import androidx.appcompat.app.AlertDialog; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.recyclerview.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; @@ -18,7 +14,10 @@ import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,17 +30,20 @@ import java.util.Set; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventFoodDatabaseChanged; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; -import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SpinnerHelper; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; /** * Created by mike on 16.10.2017. */ -public class FoodFragment extends SubscriberFragment { +public class FoodFragment extends Fragment { private static Logger log = LoggerFactory.getLogger(FoodFragment.class); + private CompositeDisposable disposable = new CompositeDisposable(); EditText filter; ImageView clearFilter; @@ -59,89 +61,93 @@ public class FoodFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.food_fragment, container, false); - filter = (EditText) view.findViewById(R.id.food_filter); - clearFilter = (ImageView) view.findViewById(R.id.food_clearfilter); - category = new SpinnerHelper(view.findViewById(R.id.food_category)); - subcategory = new SpinnerHelper(view.findViewById(R.id.food_subcategory)); - recyclerView = (RecyclerView) view.findViewById(R.id.food_recyclerview); - recyclerView.setHasFixedSize(true); - LinearLayoutManager llm = new LinearLayoutManager(view.getContext()); - recyclerView.setLayoutManager(llm); + View view = inflater.inflate(R.layout.food_fragment, container, false); + filter = (EditText) view.findViewById(R.id.food_filter); + clearFilter = (ImageView) view.findViewById(R.id.food_clearfilter); + category = new SpinnerHelper(view.findViewById(R.id.food_category)); + subcategory = new SpinnerHelper(view.findViewById(R.id.food_subcategory)); + recyclerView = (RecyclerView) view.findViewById(R.id.food_recyclerview); + recyclerView.setHasFixedSize(true); + LinearLayoutManager llm = new LinearLayoutManager(view.getContext()); + recyclerView.setLayoutManager(llm); - clearFilter.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - filter.setText(""); - category.setSelection(0); - subcategory.setSelection(0); - filterData(); - } - }); + clearFilter.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + filter.setText(""); + category.setSelection(0); + subcategory.setSelection(0); + filterData(); + } + }); - category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - fillSubcategories(); - filterData(); - } + category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + fillSubcategories(); + filterData(); + } - @Override - public void onNothingSelected(AdapterView parent) { - fillSubcategories(); - filterData(); - } - }); + @Override + public void onNothingSelected(AdapterView parent) { + fillSubcategories(); + filterData(); + } + }); - subcategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - filterData(); - } + subcategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { + @Override + public void onItemSelected(AdapterView parent, View view, int position, long id) { + filterData(); + } - @Override - public void onNothingSelected(AdapterView parent) { - filterData(); - } - }); + @Override + public void onNothingSelected(AdapterView parent) { + filterData(); + } + }); - filter.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + filter.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - filterData(); - } + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + filterData(); + } - @Override - public void afterTextChanged(Editable s) { - } - }); + @Override + public void afterTextChanged(Editable s) { + } + }); - RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp - .getSpecificPlugin(FoodPlugin.class).getService().getFoodData()); - recyclerView.setAdapter(adapter); + RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp + .getSpecificPlugin(FoodPlugin.class).getService().getFoodData()); + recyclerView.setAdapter(adapter); - loadData(); - fillCategories(); - fillSubcategories(); - filterData(); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } - - return null; + loadData(); + fillCategories(); + fillSubcategories(); + filterData(); + return view; } - @Subscribe - @SuppressWarnings("unused") - public void onStatusEvent(final EventFoodDatabaseChanged ev) { - loadData(); - filterData(); + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventFoodDatabaseChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } void loadData() { @@ -207,19 +213,11 @@ public class FoodFragment extends SubscriberFragment { filtered.add(f); } - updateGUI(); + updateGui(); } - @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - recyclerView.swapAdapter(new FoodFragment.RecyclerViewAdapter(filtered), true); - } - }); + protected void updateGui() { + recyclerView.swapAdapter(new FoodFragment.RecyclerViewAdapter(filtered), true); } public class RecyclerViewAdapter extends RecyclerView.Adapter { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java index 3856ecfc22..065c74eabb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.food; import android.content.Intent; import android.os.Bundle; import android.os.IBinder; + import androidx.annotation.Nullable; import com.j256.ormlite.android.apptools.OpenHelperManager; @@ -11,7 +12,6 @@ import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; -import com.squareup.otto.Subscribe; import org.json.JSONArray; import org.json.JSONException; @@ -34,6 +34,10 @@ import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** * Created by mike on 24.09.2017. @@ -41,6 +45,7 @@ import info.nightscout.androidaps.logging.L; public class FoodService extends OrmLiteBaseService { private Logger log = LoggerFactory.getLogger(L.DATAFOOD); + private CompositeDisposable disposable = new CompositeDisposable(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledFoodEventPost = null; @@ -48,7 +53,34 @@ public class FoodService extends OrmLiteBaseService { public FoodService() { onCreate(); dbInitialize(); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventNsFood.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + int mode = event.getMode(); + Bundle payload = event.getPayload(); + + try { + if (payload.containsKey("food")) { + JSONObject json = new JSONObject(payload.getString("food")); + if (mode == EventNsFood.Companion.getADD() || mode == EventNsFood.Companion.getUPDATE()) + this.createFoodFromJsonIfNotExists(json); + else + this.deleteNS(json); + } + + if (payload.containsKey("foods")) { + JSONArray array = new JSONArray(payload.getString("foods")); + if (mode == EventNsFood.Companion.getADD() || mode == EventNsFood.Companion.getUPDATE()) + this.createFoodFromJsonIfNotExists(array); + else + this.deleteNS(array); + } + } catch (JSONException e) { + log.error("Unhandled Exception", e); + } + }, FabricPrivacy::logException) + ); } /** @@ -79,34 +111,6 @@ public class FoodService extends OrmLiteBaseService { return null; } - @Subscribe - public void handleNsEvent(EventNsFood event) { - int mode = event.getMode(); - Bundle payload = event.getPayload(); - - try { - if (payload.containsKey("food")) { - JSONObject json = new JSONObject(payload.getString("food")); - if (mode == EventNsFood.ADD || mode == EventNsFood.UPDATE) { - this.createFoodFromJsonIfNotExists(json); - } else { - this.deleteNS(json); - } - } - - if (payload.containsKey("foods")) { - JSONArray array = new JSONArray(payload.getString("foods")); - if (mode == EventNsFood.ADD || mode == EventNsFood.UPDATE) { - this.createFoodFromJsonIfNotExists(array); - } else { - this.deleteNS(array); - } - } - } catch (JSONException e) { - log.error("Unhandled Exception", e); - } - } - @Override public void onCreate() { super.onCreate(); @@ -162,7 +166,7 @@ public class FoodService extends OrmLiteBaseService { public void run() { if (L.isEnabled(L.DATAFOOD)) log.debug("Firing EventFoodChange"); - MainApp.bus().post(event); + RxBus.INSTANCE.send(event); callback.setPost(null); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 389968eebe..76d55d8ebf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -35,13 +35,17 @@ import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNsTreatment; +import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.JsonHelper; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; /** @@ -50,6 +54,7 @@ import info.nightscout.androidaps.utils.JsonHelper; public class TreatmentService extends OrmLiteBaseService { private static Logger log = LoggerFactory.getLogger(L.DATATREATMENTS); + private CompositeDisposable disposable = new CompositeDisposable(); private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledTreatmentEventPost = null; @@ -57,7 +62,20 @@ public class TreatmentService extends OrmLiteBaseService { public TreatmentService() { onCreate(); dbInitialize(); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventNsTreatment.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + int mode = event.getMode(); + JSONObject payload = event.getPayload(); + + if (mode == EventNsTreatment.Companion.getADD() || mode == EventNsTreatment.Companion.getUPDATE()) { + this.createTreatmentFromJsonIfNotExists(payload); + } else { // EventNsTreatment.REMOVE + this.deleteNS(payload); + } + }, FabricPrivacy::logException) + ); } /** @@ -88,19 +106,6 @@ public class TreatmentService extends OrmLiteBaseService { return null; } - @Subscribe - @SuppressWarnings("unused") - public void handleNsEvent(EventNsTreatment event) { - int mode = event.getMode(); - JSONObject payload = event.getPayload(); - - if (mode == EventNsTreatment.ADD || mode == EventNsTreatment.UPDATE) { - this.createTreatmentFromJsonIfNotExists(payload); - } else { // EventNsTreatment.REMOVE - this.deleteNS(payload); - } - } - @Override public void onCreate() { super.onCreate(); diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java index 29b9c5fd01..6a4dfe12ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -87,14 +87,14 @@ public class DataService extends IntentService { } else if (Intents.ACTION_NEW_STATUS.equals(action)) { NSSettingsStatus.getInstance().handleNewData(intent); } else if (Intents.ACTION_NEW_FOOD.equals(action)) { - EventNsFood evt = new EventNsFood(EventNsFood.ADD, bundles); - MainApp.bus().post(evt); + EventNsFood evt = new EventNsFood(EventNsFood.Companion.getADD(), bundles); + RxBus.INSTANCE.send(evt); } else if (Intents.ACTION_CHANGED_FOOD.equals(action)) { - EventNsFood evt = new EventNsFood(EventNsFood.UPDATE, bundles); - MainApp.bus().post(evt); + EventNsFood evt = new EventNsFood(EventNsFood.Companion.getUPDATE(), bundles); + RxBus.INSTANCE.send(evt); } else if (Intents.ACTION_REMOVED_FOOD.equals(action)) { - EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles); - MainApp.bus().post(evt); + EventNsFood evt = new EventNsFood(EventNsFood.Companion.getREMOVE(), bundles); + RxBus.INSTANCE.send(evt); } else if (acceptNSData && (Intents.ACTION_NEW_TREATMENT.equals(action) || Intents.ACTION_CHANGED_TREATMENT.equals(action) || @@ -198,8 +198,8 @@ public class DataService extends IntentService { private void handleRemovedTreatmentFromNS(JSONObject json) { // new DB model - EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json); - MainApp.bus().post(evtTreatment); + EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.Companion.getREMOVE(), json); + RxBus.INSTANCE.send(evtTreatment); // old DB model String _id = JsonHelper.safeGetString(json, "_id"); MainApp.getDbHelper().deleteTempTargetById(_id); @@ -211,7 +211,7 @@ public class DataService extends IntentService { private void handleTreatmentFromNS(JSONObject json, Intent intent) { // new DB model - int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE; + int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.Companion.getADD() : EventNsTreatment.Companion.getUPDATE(); double insulin = JsonHelper.safeGetDouble(json, "insulin"); double carbs = JsonHelper.safeGetDouble(json, "carbs"); String eventType = JsonHelper.safeGetString(json, "eventType"); @@ -221,7 +221,7 @@ public class DataService extends IntentService { } if (insulin > 0 || carbs > 0) { EventNsTreatment evtTreatment = new EventNsTreatment(mode, json); - MainApp.bus().post(evtTreatment); + RxBus.INSTANCE.send(evtTreatment); } else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) { // old DB model MainApp.getDbHelper().updateDanaRHistoryRecordId(json); From 1aa8771f4d617869247839cd91d665e04d9db71f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Mon, 14 Oct 2019 23:49:53 +0200 Subject: [PATCH 07/13] Events to RxBus --- .../nightscout/androidaps/MainActivity.java | 8 +---- .../nightscout/androidaps/events/Event.java | 16 --------- .../nightscout/androidaps/events/Event.kt | 18 ++++++++++ .../events/EventAppInitialized.java | 8 ----- .../androidaps/events/EventAppInitialized.kt | 3 ++ .../events/EventBolusRequested.java | 21 ----------- .../androidaps/events/EventBolusRequested.kt | 3 ++ .../EventCustomCalculationFinished.java | 8 ----- .../events/EventCustomCalculationFinished.kt | 3 ++ .../events/EventFeatureRunning.java | 36 ------------------- .../configBuilder/ConfigBuilderPlugin.java | 3 +- .../general/overview/dialogs/WizardDialog.kt | 6 ---- .../plugins/general/wear/WearPlugin.java | 27 +++++++------- .../xdripStatusline/StatuslinePlugin.java | 17 ++++----- .../IobCobCalculatorPlugin.java | 34 +++++++++--------- .../androidaps/queue/CommandQueue.java | 2 +- 16 files changed, 68 insertions(+), 145 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/Event.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/Event.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java create mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index cca6fb3100..f3df901e2e 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -33,7 +33,6 @@ import com.google.android.material.navigation.NavigationView; import com.google.android.material.tabs.TabLayout; import com.joanzapata.iconify.Iconify; import com.joanzapata.iconify.fonts.FontAwesomeModule; -import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,7 +44,6 @@ import info.nightscout.androidaps.activities.PreferencesActivity; import info.nightscout.androidaps.activities.SingleFragmentActivity; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.events.EventAppExit; -import info.nightscout.androidaps.events.EventFeatureRunning; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.interfaces.PluginBase; @@ -192,11 +190,7 @@ public class MainActivity extends NoSplashAppCompatActivity { AndroidPermission.notifyForLocationPermissions(this); AndroidPermission.notifyForSMSPermissions(this); } - - MainApp.bus(). - - post(new EventFeatureRunning(EventFeatureRunning.Feature.MAIN)); - } + } @Override public void onDestroy() { diff --git a/app/src/main/java/info/nightscout/androidaps/events/Event.java b/app/src/main/java/info/nightscout/androidaps/events/Event.java deleted file mode 100644 index 864d55d6f7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/Event.java +++ /dev/null @@ -1,16 +0,0 @@ -package info.nightscout.androidaps.events; - -import org.apache.commons.lang3.builder.ReflectionToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; - -/** Base class for all events posted on the event bus. */ -public abstract class Event { - static { - ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE); - } - - @Override - public String toString() { - return ReflectionToStringBuilder.toString(this); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/Event.kt b/app/src/main/java/info/nightscout/androidaps/events/Event.kt new file mode 100644 index 0000000000..a44f65e836 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/Event.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.events + +import org.apache.commons.lang3.builder.ReflectionToStringBuilder +import org.apache.commons.lang3.builder.ToStringStyle + +/** Base class for all events posted on the event bus. */ +abstract class Event { + + override fun toString(): String { + return ReflectionToStringBuilder.toString(this) + } + + companion object { + init { + ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE) + } + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java b/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java deleted file mode 100644 index 17262cfb85..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 23.01.2018. - */ - -public class EventAppInitialized extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt b/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt new file mode 100644 index 0000000000..293f9698f2 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventAppInitialized : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java deleted file mode 100644 index cb727758bb..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java +++ /dev/null @@ -1,21 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by adrian on 07/02/17. - */ - -public class EventBolusRequested extends Event { - private double amount; - - public EventBolusRequested (double amount){ - this.amount = amount; - } - - public double getAmount() { - return amount; - } - - public void setAmount(double amount) { - this.amount = amount; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt new file mode 100644 index 0000000000..a528ef1656 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventBolusRequested(var amount: Double) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java deleted file mode 100644 index e52761dc58..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 13.02.2018. - */ - -public class EventCustomCalculationFinished extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt new file mode 100644 index 0000000000..f6092b395d --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.events + +class EventCustomCalculationFinished : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java b/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java deleted file mode 100644 index 0d07cd6c61..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by jamorham on 07/02/2018. - * - * Event to indicate that an app feature is being used, for example bolus wizard being opened - * - * The purpose this has been created for is to enable opportunistic connection to the pump - * so that it is already connected before the user wishes to enact a pump function - * - */ - -public class EventFeatureRunning extends Event { - - private Feature feature = Feature.UNKNOWN; - - public EventFeatureRunning() { - } - - public EventFeatureRunning(Feature feature) { - this.feature = feature; - } - - public Feature getFeature() { - return feature; - } - - public enum Feature { - UNKNOWN, - MAIN, - WIZARD, - - JUST_ADD_MORE_HERE - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index b73c535147..32ece49d49 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; @@ -83,7 +84,7 @@ public class ConfigBuilderPlugin extends PluginBase { upgradeSettings(); loadSettings(); setAlwaysEnabledPluginsEnabled(); - MainApp.bus().post(new EventAppInitialized()); + RxBus.INSTANCE.send(new EventAppInitialized()); } private void setAlwaysEnabledPluginsEnabled() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt index 34bbcf6fc3..9471747d7c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt @@ -16,7 +16,6 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.db.DatabaseHelper -import info.nightscout.androidaps.events.EventFeatureRunning import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin @@ -68,11 +67,6 @@ class WizardDialog : DialogFragment() { this.parentContext = null } - override fun onResume() { - super.onResume() - MainApp.bus().post(EventFeatureRunning(EventFeatureRunning.Feature.WIZARD)) - } - override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("treatments_wizard_bginput", treatments_wizard_bginput.value) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java index 8816cf58cd..cf3cc6b783 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java @@ -120,8 +120,7 @@ public class WearPlugin extends PluginBase { resendDataToWatch(); // status may be formated differently sendDataToWatch(true, false, false); - }, - FabricPrivacy::logException + }, FabricPrivacy::logException )); disposable.add(RxBus.INSTANCE .toObservable(EventRefreshOverview.class) @@ -129,8 +128,18 @@ public class WearPlugin extends PluginBase { .subscribe(event -> { if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) sendDataToWatch(true, false, false); - }, - FabricPrivacy::logException + }, FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventBolusRequested.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + String status = String.format(MainApp.gs(R.string.bolusrequested), event.getAmount()); + Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS); + intent.putExtra("progresspercent", 0); + intent.putExtra("progressstatus", status); + ctx.startService(intent); + }, FabricPrivacy::logException )); } @@ -192,16 +201,6 @@ public class WearPlugin extends PluginBase { } } - @Subscribe - public void onStatusEvent(final EventBolusRequested ev) { - String status = String.format(MainApp.gs(R.string.bolusrequested), ev.getAmount()); - Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS); - intent.putExtra("progresspercent", 0); - intent.putExtra("progressstatus", status); - ctx.startService(intent); - - } - @Subscribe public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) { if (ev.result == null) return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java index 2713a0ef08..da61b83b98 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java @@ -8,8 +8,6 @@ import android.preference.PreferenceManager; import androidx.annotation.NonNull; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.IobTotal; @@ -88,7 +86,6 @@ public class StatuslinePlugin extends PluginBase { @Override protected void onStart() { super.onStart(); - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventRefreshOverview.class) .observeOn(Schedulers.io()) @@ -134,12 +131,17 @@ public class StatuslinePlugin extends PluginBase { .subscribe(event -> sendStatus(), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAppInitialized.class) + .observeOn(Schedulers.io()) + .subscribe(event -> sendStatus(), + FabricPrivacy::logException + )); } @Override protected void onStop() { super.onStop(); - MainApp.bus().unregister(this); disposable.clear(); sendStatus(); } @@ -211,11 +213,4 @@ public class StatuslinePlugin extends PluginBase { return status; } - - - @Subscribe - public void onStatusEvent(final EventAppInitialized ev) { - sendStatus(); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index e5aec47b43..16df35c75d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -135,7 +135,7 @@ public class IobCobCalculatorPlugin extends PluginBase { basalDataTable = new LongSparseArray<>(); } runCalculation("onNewProfile", System.currentTimeMillis(), false, true, event); - }, FabricPrivacy::logException) + }, FabricPrivacy::logException) ); // EventNewBG disposable.add(RxBus.INSTANCE @@ -149,9 +149,9 @@ public class IobCobCalculatorPlugin extends PluginBase { } stopCalculation("onEventNewBG"); runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, event); - }, FabricPrivacy::logException) + }, FabricPrivacy::logException) ); - // EventPreferenceChange + // EventPreferenceChange disposable.add(RxBus.INSTANCE .toObservable(EventPreferenceChange.class) .observeOn(Schedulers.io()) @@ -179,7 +179,20 @@ public class IobCobCalculatorPlugin extends PluginBase { } runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, event); } - }, FabricPrivacy::logException) + }, FabricPrivacy::logException) + ); + // EventAppInitialized + disposable.add(RxBus.INSTANCE + .toObservable(EventAppInitialized.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (this != getPlugin()) { + if (L.isEnabled(L.AUTOSENS)) + log.debug("Ignoring event for non default instance"); + return; + } + runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, event); + }, FabricPrivacy::logException) ); } @@ -724,18 +737,7 @@ public class IobCobCalculatorPlugin extends PluginBase { return array; } - @Subscribe - @SuppressWarnings("unused") - public void onEventAppInitialized(EventAppInitialized ev) { - if (this != getPlugin()) { - if (L.isEnabled(L.AUTOSENS)) - log.debug("Ignoring event for non default instance"); - return; - } - runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev); - } - - public void stopCalculation(String from) { + public void stopCalculation(String from) { if (thread != null && thread.getState() != Thread.State.TERMINATED) { stopCalculationTrigger = true; if (L.isEnabled(L.AUTOSENS)) diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index 415af062fd..cd0b666119 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -249,7 +249,7 @@ public class CommandQueue { // not when the Bolus command is starting. The command closes the dialog upon completion). showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context); // Notify Wear about upcoming bolus - MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin)); + RxBus.INSTANCE.send(new EventBolusRequested(detailedBolusInfo.insulin)); } } From 837cb0d4a29866a18b470b322b35faa4ba5fc8ff Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 15 Oct 2019 00:23:56 +0200 Subject: [PATCH 08/13] Events to RxBus --- .../activities/TDDStatsActivity.java | 34 ++--- .../activities/DanaRHistoryActivity.java | 22 ++- .../danaR/activities/DanaRNSHistorySync.java | 45 +++--- .../pump/danaR/comm/MsgHistoryAll.java | 10 +- .../danaR/events/EventDanaRSyncStatus.java | 14 -- .../pump/danaR/events/EventDanaRSyncStatus.kt | 5 + .../plugins/pump/danaRS/DanaRSPlugin.java | 18 +-- .../danaRS/activities/BLEScanActivity.java | 4 +- .../activities/PairingProgressDialog.java | 21 +-- .../danaRS/comm/DanaRS_Packet_History_.java | 6 +- .../events/EventDanaRSDeviceChange.java | 10 -- .../danaRS/events/EventDanaRSDeviceChange.kt | 5 + .../pump/danaRS/events/EventDanaRSPacket.java | 16 --- .../events/EventDanaRSPairingSuccess.java | 10 -- .../events/EventDanaRSPairingSuccess.kt | 5 + .../plugins/pump/danaRS/services/BLEComm.java | 4 +- .../pump/virtual/VirtualPumpFragment.java | 129 +++++++++--------- .../pump/virtual/VirtualPumpPlugin.java | 12 +- .../events/EventVirtualPumpUpdateGui.java | 9 -- .../events/EventVirtualPumpUpdateGui.kt | 5 + 20 files changed, 163 insertions(+), 221 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index 6c2b9417d4..f8005db5ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -1,10 +1,8 @@ package info.nightscout.androidaps.activities; -import android.app.Activity; import android.graphics.Color; import android.graphics.Rect; import android.os.Bundle; -import androidx.recyclerview.widget.LinearLayoutManager; import android.text.TextUtils; import android.view.KeyEvent; import android.view.MotionEvent; @@ -18,7 +16,7 @@ import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.recyclerview.widget.LinearLayoutManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,7 +35,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TDD; -import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.bus.RxBus; @@ -86,6 +83,14 @@ public class TDDStatsActivity extends NoSplashActivity { .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventDanaRSyncStatus.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + log.debug("EventDanaRSyncStatus: " + event.getMessage()); + statusView.setText(event.getMessage()); + }, FabricPrivacy::logException) + ); } @Override @@ -251,7 +256,7 @@ public class TDDStatsActivity extends NoSplashActivity { statsMessage.setText(MainApp.gs(R.string.danar_stats_warning_Message)); } }); - ConfigBuilderPlugin.getPlugin().getCommandQueue().loadTDDs( new Callback() { + ConfigBuilderPlugin.getPlugin().getCommandQueue().loadTDDs(new Callback() { @Override public void run() { loadDataFromDB(); @@ -411,7 +416,7 @@ public class TDDStatsActivity extends NoSplashActivity { //cumulative TDDs for (TDD record : historyList) { - if(!historyList.isEmpty() && df.format(new Date(record.date)).equals(df.format(new Date()))) { + if (!historyList.isEmpty() && df.format(new Date(record.date)).equals(df.format(new Date()))) { //Today should not be included continue; } @@ -460,7 +465,7 @@ public class TDDStatsActivity extends NoSplashActivity { tl.setBackgroundColor(Color.TRANSPARENT); } - if(!historyList.isEmpty() && df.format(new Date(historyList.get(0).date)).equals(df.format(new Date()))) { + if (!historyList.isEmpty() && df.format(new Date(historyList.get(0).date)).equals(df.format(new Date()))) { //Today should not be included historyList.remove(0); } @@ -531,19 +536,6 @@ public class TDDStatsActivity extends NoSplashActivity { } } - @Subscribe - public void onStatusEvent(final EventDanaRSyncStatus s) { - log.debug("EventDanaRSyncStatus: " + s.message); - runOnUiThread( - new Runnable() { - @Override - public void run() { - statusView.setText(s.message); - } - }); - } - - public static boolean isOldData(List historyList) { Object activePump = ConfigBuilderPlugin.getPlugin().getActivePump(); PumpInterface dana = MainApp.getSpecificPlugin(DanaRPlugin.class); @@ -555,6 +547,6 @@ public class TDDStatsActivity extends NoSplashActivity { boolean startsYesterday = activePump == dana || activePump == danaRS || activePump == danaV2 || activePump == danaKorean || activePump == insight; DateFormat df = new SimpleDateFormat("dd.MM."); - return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday?1000 * 60 * 60 * 24:0)))))); + return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday ? 1000 * 60 * 60 * 24 : 0)))))); } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java index a5f99def77..f20a74b024 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java @@ -15,8 +15,6 @@ import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -86,18 +84,25 @@ public class DanaRHistoryActivity extends NoSplashActivity { @Override protected void onResume() { super.onResume(); - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventPumpStatusChanged.class) .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventDanaRSyncStatus.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (L.isEnabled(L.PUMP)) + log.debug("EventDanaRSyncStatus: " + event.getMessage()); + statusView.setText(event.getMessage()); + }, FabricPrivacy::logException) + ); } @Override protected void onPause() { super.onPause(); - MainApp.bus().unregister(this); disposable.clear(); } @@ -327,13 +332,4 @@ public class DanaRHistoryActivity extends NoSplashActivity { historyList = new ArrayList<>(); runOnUiThread(() -> recyclerView.swapAdapter(new RecyclerViewAdapter(historyList), false)); } - - @Subscribe - public void onStatusEvent(final EventDanaRSyncStatus s) { - if (L.isEnabled(L.PUMP)) - log.debug("EventDanaRSyncStatus: " + s.message); - runOnUiThread( - () -> statusView.setText(s.message)); - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java index a15c8d2883..dcb182a0d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java @@ -14,6 +14,7 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus; @@ -28,13 +29,13 @@ public class DanaRNSHistorySync { private static Logger log = LoggerFactory.getLogger(L.PUMP); private List historyRecords; - public final static int SYNC_BOLUS = 0b00000001; - public final static int SYNC_ERROR = 0b00000010; - public final static int SYNC_REFILL = 0b00000100; - public final static int SYNC_GLUCOSE = 0b00001000; - public final static int SYNC_CARBO = 0b00010000; - public final static int SYNC_ALARM = 0b00100000; - public final static int SYNC_BASALHOURS = 0b01000000; + private final static int SYNC_BOLUS = 0b00000001; + private final static int SYNC_ERROR = 0b00000010; + private final static int SYNC_REFILL = 0b00000100; + private final static int SYNC_GLUCOSE = 0b00001000; + private final static int SYNC_CARBO = 0b00010000; + private final static int SYNC_ALARM = 0b00100000; + private final static int SYNC_BASALHOURS = 0b01000000; public final static int SYNC_ALL = 0b11111111; public final static String DANARSIGNATURE = "DANARMESSAGE"; @@ -52,13 +53,13 @@ public class DanaRNSHistorySync { long uploaded = 0; if (L.isEnabled(L.PUMP)) log.debug("Database contains " + records + " records"); - EventDanaRSyncStatus ev = new EventDanaRSyncStatus(); + EventDanaRSyncStatus ev = new EventDanaRSyncStatus(""); for (DanaRHistoryRecord record : historyRecords) { processing++; if (record._id != null) continue; //log.debug(record.bytes); JSONObject nsrec = new JSONObject(); - ev.message = MainApp.gs(R.string.uploading) + " " + processing + "/" + records + " "; // TODO: translations + ev.setMessage(MainApp.gs(R.string.uploading) + " " + processing + "/" + records + " "); // TODO: translations switch (record.recordCode) { case RecordTypes.RECORD_TYPE_BOLUS: if ((what & SYNC_BOLUS) == 0) break; @@ -73,7 +74,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_sbolus); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_sbolus)); break; case "E": if (record.recordDuration > 0) { @@ -92,7 +93,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_ebolus); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_ebolus)); } else { if (L.isEnabled(L.PUMP)) log.debug("NOT Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate) + " zero duration"); @@ -110,7 +111,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_dsbolus); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_dsbolus)); break; case "DE": if (L.isEnabled(L.PUMP)) @@ -127,7 +128,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_debolus); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_debolus)); break; default: log.error("Unknown bolus record"); @@ -145,7 +146,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_error); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_error)); break; case RecordTypes.RECORD_TYPE_REFILL: if ((what & SYNC_REFILL) == 0) break; @@ -158,7 +159,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_refill); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_refill)); break; case RecordTypes.RECORD_TYPE_BASALHOUR: if ((what & SYNC_BASALHOURS) == 0) break; @@ -172,7 +173,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_basalhour); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_basalhour)); break; case RecordTypes.RECORD_TYPE_TB: //log.debug("Ignoring TB record " + record.bytes + " " + DateUtil.toISOString(record.recordDate)); @@ -189,7 +190,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_glucose); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_glucose)); break; case RecordTypes.RECORD_TYPE_CARBO: if ((what & SYNC_CARBO) == 0) break; @@ -202,7 +203,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_carbohydrate); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_carbohydrate)); break; case RecordTypes.RECORD_TYPE_ALARM: if ((what & SYNC_ALARM) == 0) break; @@ -215,7 +216,7 @@ public class DanaRNSHistorySync { nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name)); NSUpload.uploadCareportalEntryToNS(nsrec); uploaded++; - ev.message += MainApp.gs(R.string.danar_alarm); + ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_alarm)); break; case RecordTypes.RECORD_TYPE_SUSPEND: // TODO: this too case RecordTypes.RECORD_TYPE_DAILY: @@ -226,10 +227,10 @@ public class DanaRNSHistorySync { log.error("Unknown record type"); break; } - MainApp.bus().post(ev); + RxBus.INSTANCE.send(ev); } - ev.message = String.format(MainApp.gs(R.string.danar_totaluploaded), uploaded); - MainApp.bus().post(ev); + ev.setMessage(String.format(MainApp.gs(R.string.danar_totaluploaded), uploaded)); + RxBus.INSTANCE.send(ev); } catch (JSONException e) { log.error("Unhandled exception", e); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java index 7de2489c91..955d7fc090 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java @@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.utils.DateUtil; @@ -33,8 +34,6 @@ public class MsgHistoryAll extends MessageBase { byte paramByte8 = (byte) intFromBuff(bytes, 7, 1); double value = (double) intFromBuff(bytes, 8, 2); - EventDanaRSyncStatus ev = new EventDanaRSyncStatus(); - DanaRHistoryRecord danaRHistoryRecord = new DanaRHistoryRecord(); danaRHistoryRecord.recordCode = recordCode; @@ -145,11 +144,6 @@ public class MsgHistoryAll extends MessageBase { } MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord); - - ev.message = DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate); - ev.message += " " + messageType; - MainApp.bus().post(ev); - - return; + RxBus.INSTANCE.send(new EventDanaRSyncStatus(DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java deleted file mode 100644 index 5fc0bd740f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 20.07.2016. - */ -public class EventDanaRSyncStatus extends Event { - public String message; - - public EventDanaRSyncStatus() { - } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt new file mode 100644 index 0000000000..59ad7e2d83 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.danaR.events + +import info.nightscout.androidaps.events.Event + +class EventDanaRSyncStatus(var message: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java index 4dea025521..7b2668d45c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java @@ -9,8 +9,6 @@ import android.os.IBinder; import androidx.annotation.Nullable; import androidx.fragment.app.FragmentActivity; -import com.squareup.otto.Subscribe; - import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; @@ -40,7 +38,6 @@ import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; @@ -48,6 +45,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNo import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; +import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; @@ -118,7 +116,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte Intent intent = new Intent(context, DanaRSService.class); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) @@ -126,7 +123,14 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte MainApp.instance().getApplicationContext().unbindService(mConnection); }, FabricPrivacy::logException) ); - onStatusEvent(new EventDanaRSDeviceChange()); // load device name + disposable.add(RxBus.INSTANCE + .toObservable(EventDanaRSDeviceChange.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + loadAddress(); + }, FabricPrivacy::logException) + ); + loadAddress(); // load device name super.onStart(); } @@ -135,7 +139,6 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte Context context = MainApp.instance().getApplicationContext(); context.unbindService(mConnection); - MainApp.bus().unregister(this); disposable.clear(); super.onStop(); } @@ -161,8 +164,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte } }; - @Subscribe - public void onStatusEvent(final EventDanaRSDeviceChange e) { + private void loadAddress() { mDeviceAddress = SP.getString(R.string.key_danars_address, ""); mDeviceName = SP.getString(R.string.key_danars_name, ""); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java index 7262153d5c..42e910f291 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java @@ -17,9 +17,9 @@ import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange; import info.nightscout.androidaps.utils.SP; @@ -156,7 +156,7 @@ public class BLEScanActivity extends NoSplashAppCompatActivity { SP.putString(R.string.key_danars_address, item.device.getAddress()); SP.putString(R.string.key_danars_name, mName.getText().toString()); item.device.createBond(); - MainApp.bus().post(new EventDanaRSDeviceChange()); + RxBus.INSTANCE.send(new EventDanaRSDeviceChange()); finish(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java index 544b0c862e..afb5e86387 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java @@ -5,7 +5,6 @@ import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; -import androidx.fragment.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -13,14 +12,19 @@ import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.fragment.app.DialogFragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class PairingProgressDialog extends DialogFragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); TextView statusView; ProgressBar progressBar; @@ -101,7 +105,11 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic @Override public void onResume() { super.onResume(); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventDanaRSPairingSuccess.class) + .observeOn(Schedulers.io()) + .subscribe(event -> pairingEnded = true, FabricPrivacy::logException) + ); running = true; if (pairingEnded) dismiss(); } @@ -117,15 +125,10 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic @Override public void onPause() { super.onPause(); - MainApp.bus().unregister(this); + disposable.clear(); running = false; } - @Subscribe - public void onStatusEvent(final EventDanaRSPairingSuccess ev) { - pairingEnded = true; - } - public void setHelperActivity(PairingHelperActivity activity) { this.helperActivity = activity; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java index ceaf49908b..07893346d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java @@ -10,6 +10,7 @@ import java.util.GregorianCalendar; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DanaRHistoryRecord; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.utils.DateUtil; @@ -109,7 +110,6 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { log.debug("History packet: " + recordCode + " Date: " + datetimewihtsec.toLocaleString() + " Code: " + historyCode + " Value: " + value); - EventDanaRSyncStatus ev = new EventDanaRSyncStatus(); DanaRHistoryRecord danaRHistoryRecord = new DanaRHistoryRecord(); danaRHistoryRecord.setBytes(data); @@ -224,9 +224,7 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet { MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord); - ev.message = DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate); - ev.message += " " + messageType; - MainApp.bus().post(ev); + RxBus.INSTANCE.send(new EventDanaRSyncStatus(DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java deleted file mode 100644 index 224f939ad7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java +++ /dev/null @@ -1,10 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 05.09.2017. - */ - -public class EventDanaRSDeviceChange extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt new file mode 100644 index 0000000000..8b87d59ec1 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.danaRS.events + +import info.nightscout.androidaps.events.Event + +class EventDanaRSDeviceChange : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java deleted file mode 100644 index e0c401a27f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java +++ /dev/null @@ -1,16 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.events; - -import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet; - -/** - * Created by mike on 01.09.2017. - */ - -public class EventDanaRSPacket extends Event{ - public EventDanaRSPacket(DanaRS_Packet data) { - this.data = data; - } - - public DanaRS_Packet data; -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java deleted file mode 100644 index e332e9e0b2..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java +++ /dev/null @@ -1,10 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 01.09.2017. - */ - -public class EventDanaRSPairingSuccess extends Event{ -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt new file mode 100644 index 0000000000..6e0379a4d3 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.danaRS.events + +import info.nightscout.androidaps.events.Event + +class EventDanaRSPairingSuccess : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java index 20ce8f485b..8a43d6e35a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java @@ -35,7 +35,6 @@ import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity; import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable; import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPacket; import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess; import info.nightscout.androidaps.utils.SP; @@ -496,7 +495,7 @@ public class BLEComm { if (L.isEnabled(L.PUMPBTCOMM)) log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer)); // Paring is successfull, sending time info - MainApp.bus().post(new EventDanaRSPairingSuccess()); + RxBus.INSTANCE.send(new EventDanaRSPairingSuccess()); SendTimeInfo(); byte[] pairingKey = {inputBuffer[2], inputBuffer[3]}; // store pairing key to preferences @@ -546,7 +545,6 @@ public class BLEComm { // notify to sendMessage message.notify(); } - MainApp.bus().post(new EventDanaRSPacket(message)); } else { log.error("Unknown message received " + DanaRS_Packet.toHexString(inputBuffer)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java index be9bf17c85..35e95d66b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java @@ -4,13 +4,13 @@ package info.nightscout.androidaps.plugins.pump.virtual; import android.app.Activity; import android.os.Bundle; import android.os.Handler; -import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -19,15 +19,18 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; -public class VirtualPumpFragment extends SubscriberFragment { +public class VirtualPumpFragment extends Fragment { private static Logger log = LoggerFactory.getLogger(VirtualPumpFragment.class); + private CompositeDisposable disposable = new CompositeDisposable(); TextView basaBasalRateView; TextView tempBasalView; @@ -45,12 +48,11 @@ public class VirtualPumpFragment extends SubscriberFragment { public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (sRefreshLoop == null) { - sRefreshLoop = new Runnable() { - @Override - public void run() { - updateGUI(); - sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); - } + sRefreshLoop = () -> { + Activity activity = getActivity(); + if (activity != null) + activity.runOnUiThread(this::updateGui); + sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); }; sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); } @@ -59,67 +61,62 @@ public class VirtualPumpFragment extends SubscriberFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.virtualpump_fragment, container, false); - basaBasalRateView = (TextView) view.findViewById(R.id.virtualpump_basabasalrate); - tempBasalView = (TextView) view.findViewById(R.id.virtualpump_tempbasal); - extendedBolusView = (TextView) view.findViewById(R.id.virtualpump_extendedbolus); - batteryView = (TextView) view.findViewById(R.id.virtualpump_battery); - reservoirView = (TextView) view.findViewById(R.id.virtualpump_reservoir); - pumpTypeView = (TextView) view.findViewById(R.id.virtualpump_type); - pumpSettingsView = (TextView) view.findViewById(R.id.virtualpump_type_def); + View view = inflater.inflate(R.layout.virtualpump_fragment, container, false); + basaBasalRateView = (TextView) view.findViewById(R.id.virtualpump_basabasalrate); + tempBasalView = (TextView) view.findViewById(R.id.virtualpump_tempbasal); + extendedBolusView = (TextView) view.findViewById(R.id.virtualpump_extendedbolus); + batteryView = (TextView) view.findViewById(R.id.virtualpump_battery); + reservoirView = (TextView) view.findViewById(R.id.virtualpump_reservoir); + pumpTypeView = (TextView) view.findViewById(R.id.virtualpump_type); + pumpSettingsView = (TextView) view.findViewById(R.id.virtualpump_type_def); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } - - return null; - } - - @Subscribe - public void onStatusEvent(final EventVirtualPumpUpdateGui ev) { - updateGUI(); + return view; } @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null && basaBasalRateView != null) - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - VirtualPumpPlugin virtualPump = VirtualPumpPlugin.getPlugin(); - basaBasalRateView.setText(virtualPump.getBaseBasalRate() + "U"); - TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - tempBasalView.setText(activeTemp.toStringFull()); - } else { - tempBasalView.setText(""); - } - ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); - if (activeExtendedBolus != null) { - extendedBolusView.setText(activeExtendedBolus.toString()); - } else { - extendedBolusView.setText(""); - } - batteryView.setText(virtualPump.batteryPercent + "%"); - reservoirView.setText(virtualPump.reservoirInUnits + "U"); - - virtualPump.refreshConfiguration(); - - PumpType pumpType = virtualPump.getPumpType(); - - pumpTypeView.setText(pumpType.getDescription()); - - String template = MainApp.gs(R.string.virtualpump_pump_def); - - - pumpSettingsView.setText(pumpType.getFullDescription(template, pumpType.hasExtendedBasals())); - - } - }); + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventVirtualPumpUpdateGui.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); } + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + protected void updateGui() { + VirtualPumpPlugin virtualPump = VirtualPumpPlugin.getPlugin(); + basaBasalRateView.setText(virtualPump.getBaseBasalRate() + "U"); + TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()); + if (activeTemp != null) { + tempBasalView.setText(activeTemp.toStringFull()); + } else { + tempBasalView.setText(""); + } + ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()); + if (activeExtendedBolus != null) { + extendedBolusView.setText(activeExtendedBolus.toString()); + } else { + extendedBolusView.setText(""); + } + batteryView.setText(virtualPump.batteryPercent + "%"); + reservoirView.setText(virtualPump.reservoirInUnits + "U"); + + virtualPump.refreshConfiguration(); + + PumpType pumpType = virtualPump.getPumpType(); + + pumpTypeView.setText(pumpType.getDescription()); + + String template = MainApp.gs(R.string.virtualpump_pump_def); + + + pumpSettingsView.setText(pumpType.getFullDescription(template, pumpType.hasExtendedBasals())); + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java index 76dcdc6316..bedd330f51 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java @@ -285,7 +285,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { SystemClock.sleep(1000); if (L.isEnabled(L.PUMPCOMM)) log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result); - MainApp.bus().post(new EventVirtualPumpUpdateGui()); + RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui()); lastDataTime = System.currentTimeMillis(); TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); return result; @@ -313,7 +313,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting temp basal absolute: " + result); - MainApp.bus().post(new EventVirtualPumpUpdateGui()); + RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui()); lastDataTime = System.currentTimeMillis(); return result; } @@ -336,7 +336,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal); if (L.isEnabled(L.PUMPCOMM)) log.debug("Settings temp basal percent: " + result); - MainApp.bus().post(new EventVirtualPumpUpdateGui()); + RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui()); lastDataTime = System.currentTimeMillis(); return result; } @@ -361,7 +361,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); if (L.isEnabled(L.PUMPCOMM)) log.debug("Setting extended bolus: " + result); - MainApp.bus().post(new EventVirtualPumpUpdateGui()); + RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui()); lastDataTime = System.currentTimeMillis(); return result; } @@ -379,7 +379,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { //tempBasal = null; if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling temp basal: " + result); - MainApp.bus().post(new EventVirtualPumpUpdateGui()); + RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui()); } lastDataTime = System.currentTimeMillis(); return result; @@ -399,7 +399,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { result.comment = MainApp.gs(R.string.virtualpump_resultok); if (L.isEnabled(L.PUMPCOMM)) log.debug("Canceling extended bolus: " + result); - MainApp.bus().post(new EventVirtualPumpUpdateGui()); + RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui()); lastDataTime = System.currentTimeMillis(); return result; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java deleted file mode 100644 index 795134997a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.virtual.events; - -import info.nightscout.androidaps.events.EventUpdateGui; - -/** - * Created by mike on 05.08.2016. - */ -public class EventVirtualPumpUpdateGui extends EventUpdateGui { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt new file mode 100644 index 0000000000..a0498aa14d --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.virtual.events + +import info.nightscout.androidaps.events.EventUpdateGui + +class EventVirtualPumpUpdateGui : EventUpdateGui() \ No newline at end of file From 06f8af82d830e5edf0bc437a76f0b2b6e724cc08 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 15 Oct 2019 00:54:30 +0200 Subject: [PATCH 09/13] Events to RxBus --- .../overview/dialogs/BolusProgressDialog.java | 54 +++++++---------- .../EventDismissBolusprogressIfRunning.java | 16 ----- .../EventDismissBolusprogressIfRunning.kt | 6 ++ .../events/EventOverviewBolusProgress.java | 27 --------- .../events/EventOverviewBolusProgress.kt | 12 ++++ .../plugins/general/wear/WearPlugin.java | 60 +++++++++---------- .../plugins/pump/combo/ComboPlugin.java | 28 ++++----- .../pump/common/PumpPluginAbstract.java | 10 ++-- .../pump/danaR/comm/MsgBolusProgress.java | 11 ++-- .../plugins/pump/danaR/comm/MsgBolusStop.java | 11 ++-- .../plugins/pump/danaR/comm/MsgError.java | 7 ++- .../danaR/services/DanaRExecutionService.java | 10 ++-- ...naRS_Packet_Bolus_Set_Step_Bolus_Stop.java | 11 ++-- ...anaRS_Packet_Notify_Delivery_Complete.java | 11 ++-- ...S_Packet_Notify_Delivery_Rate_Display.java | 13 ++-- .../pump/danaRS/services/DanaRSService.java | 12 ++-- .../services/DanaRv2ExecutionService.java | 12 ++-- .../pump/insight/LocalInsightPlugin.java | 26 ++++---- .../pump/virtual/VirtualPumpPlugin.java | 16 ++--- .../androidaps/queue/CommandQueue.java | 2 +- .../androidaps/queue/QueueThread.java | 2 +- .../queue/commands/CommandBolus.java | 3 +- 22 files changed, 166 insertions(+), 194 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java index 35c8edd656..0ac9cbdafd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java @@ -14,8 +14,6 @@ import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.DialogFragment; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -102,7 +100,29 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) ); - MainApp.bus().register(this); + disposable.add(RxBus.INSTANCE + .toObservable(EventDismissBolusprogressIfRunning.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (L.isEnabled(L.UI)) log.debug("EventDismissBolusprogressIfRunning"); + if (BolusProgressDialog.running) dismiss(); + }, FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventOverviewBolusProgress.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (L.isEnabled(L.UI)) + log.debug("Status: " + event.getStatus() + " Percent: " + event.getPercent()); + statusView.setText(event.getStatus()); + progressBar.setProgress(event.getPercent()); + if (event.getPercent() == 100) { + stopButton.setVisibility(View.INVISIBLE); + scheduleDismiss(); + } + state = event.getStatus(); + }, FabricPrivacy::logException) + ); } @Override @@ -128,7 +148,6 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL log.debug("onPause"); running = false; super.onPause(); - MainApp.bus().unregister(this); disposable.clear(); } @@ -153,33 +172,6 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL } } - @Subscribe - public void onStatusEvent(final EventOverviewBolusProgress ev) { - Activity activity = getActivity(); - if (activity != null) { - activity.runOnUiThread(() -> { - if (L.isEnabled(L.UI)) - log.debug("Status: " + ev.status + " Percent: " + ev.percent); - statusView.setText(ev.status); - progressBar.setProgress(ev.percent); - if (ev.percent == 100) { - stopButton.setVisibility(View.INVISIBLE); - scheduleDismiss(); - } - }); - } - state = ev.status; - } - - @Subscribe - public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) { - if (L.isEnabled(L.UI)) - log.debug("EventDismissBolusprogressIfRunning"); - if (BolusProgressDialog.running) { - dismiss(); - } - } - private void scheduleDismiss() { if (L.isEnabled(L.UI)) log.debug("scheduleDismiss"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java deleted file mode 100644 index 2022a4d74b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java +++ /dev/null @@ -1,16 +0,0 @@ -package info.nightscout.androidaps.plugins.general.overview.events; - -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.events.Event; - -/** - * Created by adrian on 20/02/17. - */ - -public class EventDismissBolusprogressIfRunning extends Event { - public final PumpEnactResult result; - - public EventDismissBolusprogressIfRunning(PumpEnactResult result) { - this.result = result; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.kt new file mode 100644 index 0000000000..94482729b6 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.events.Event + +class EventDismissBolusprogressIfRunning(val result: PumpEnactResult) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java deleted file mode 100644 index 3a7c50faac..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java +++ /dev/null @@ -1,27 +0,0 @@ -package info.nightscout.androidaps.plugins.general.overview.events; - -import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.events.Event; - -public class EventOverviewBolusProgress extends Event { - public String status = ""; - public Treatment t = null; - public int percent = 0; - public int bolusId; - private static EventOverviewBolusProgress eventOverviewBolusProgress = null; - - public EventOverviewBolusProgress() { - } - - public boolean isSMB(){ - return (t != null) && t.isSMB; - } - - public static EventOverviewBolusProgress getInstance() { - if(eventOverviewBolusProgress == null) { - eventOverviewBolusProgress = new EventOverviewBolusProgress(); - } - return eventOverviewBolusProgress; - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt new file mode 100644 index 0000000000..52b62790da --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.plugins.general.overview.events + +import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.events.Event + +object EventOverviewBolusProgress : Event() { + var status = "" + var t: Treatment? = null + var percent = 0 + + fun isSMB(): Boolean = t?.isSMB ?: false +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java index cf3cc6b783..f60484cb80 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java @@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.general.wear; import android.content.Context; import android.content.Intent; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.events.EventBolusRequested; @@ -70,7 +68,6 @@ public class WearPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); if (watchUS != null) { watchUS.setSettings(); } @@ -141,12 +138,40 @@ public class WearPlugin extends PluginBase { ctx.startService(intent); }, FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventDismissBolusprogressIfRunning.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (event.getResult() == null) return; + String status; + if (event.getResult().success) { + status = MainApp.gs(R.string.success); + } else { + status = MainApp.gs(R.string.nosuccess); + } + Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS); + intent.putExtra("progresspercent", 100); + intent.putExtra("progressstatus", status); + ctx.startService(intent); + }, FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventOverviewBolusProgress.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + if (!event.isSMB() || SP.getBoolean("wear_notifySMB", true)) { + Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS); + intent.putExtra("progresspercent", event.getPercent()); + intent.putExtra("progressstatus", event.getStatus()); + ctx.startService(intent); + } + }, FabricPrivacy::logException + )); } @Override protected void onStop() { - MainApp.bus().unregister(this); disposable.clear(); super.onStop(); } @@ -190,33 +215,6 @@ public class WearPlugin extends PluginBase { ctx.startService(intent); } - - @Subscribe - public void onStatusEvent(final EventOverviewBolusProgress ev) { - if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) { - Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS); - intent.putExtra("progresspercent", ev.percent); - intent.putExtra("progressstatus", ev.status); - ctx.startService(intent); - } - } - - @Subscribe - public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) { - if (ev.result == null) return; - - String status; - if (ev.result.success) { - status = MainApp.gs(R.string.success); - } else { - status = MainApp.gs(R.string.nosuccess); - } - Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS); - intent.putExtra("progresspercent", 100); - intent.putExtra("progressstatus", status); - ctx.startService(intent); - } - public void requestActionConfirmation(String title, String message, String actionstring) { Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_ACTIONCONFIRMATIONREQUEST); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index e867189a80..aeb5b0224c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -433,26 +433,26 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> { - EventOverviewBolusProgress event = EventOverviewBolusProgress.getInstance(); + EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE; switch (state) { case PROGRAMMING: - event.status = MainApp.gs(R.string.combo_programming_bolus); + event.setStatus(MainApp.gs(R.string.combo_programming_bolus)); break; case DELIVERING: - event.status = MainApp.gs(R.string.bolusdelivering, delivered); + event.setStatus(MainApp.gs(R.string.bolusdelivering, delivered)); break; case DELIVERED: - event.status = MainApp.gs(R.string.bolusdelivered, delivered); + event.setStatus(MainApp.gs(R.string.bolusdelivered, delivered)); break; case STOPPING: - event.status = MainApp.gs(R.string.bolusstopping); + event.setStatus(MainApp.gs(R.string.bolusstopping)); break; case STOPPED: - event.status = MainApp.gs(R.string.bolusstopped); + event.setStatus(MainApp.gs(R.string.bolusstopped)); break; } - event.percent = percent; - MainApp.bus().post(event); + event.setPercent(percent); + RxBus.INSTANCE.send(event); }; /** @@ -474,11 +474,11 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // no bolus required, carb only treatment TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.t = new Treatment(); - bolusingEvent.t.isSMB = detailedBolusInfo.isSMB; - bolusingEvent.percent = 100; - MainApp.bus().post(bolusingEvent); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setT(new Treatment()); + bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB; + bolusingEvent.setPercent(100); + RxBus.INSTANCE.send(bolusingEvent); return new PumpEnactResult().success(true).enacted(true) .bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs) @@ -558,7 +558,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint Treatment treatment = new Treatment(); treatment.isSMB = detailedBolusInfo.isSMB; - EventOverviewBolusProgress.getInstance().t = treatment; + EventOverviewBolusProgress.INSTANCE.setT(treatment); // start bolus delivery scripterIsBolusing = true; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index 496859f38f..6544b1b0b4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -418,11 +418,11 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter // no bolus required, carb only treatment TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true); - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.t = new Treatment(); - bolusingEvent.t.isSMB = detailedBolusInfo.isSMB; - bolusingEvent.percent = 100; - MainApp.bus().post(bolusingEvent); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setT(new Treatment()); + bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB; + bolusingEvent.setPercent(100); + RxBus.INSTANCE.send(bolusingEvent); if (isLoggingEnabled()) LOG.debug("deliverTreatment: Carb only treatment."); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java index 6fb1993237..362b72c929 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java @@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.treatments.Treatment; @@ -37,15 +38,15 @@ public class MsgBolusProgress extends MessageBase { lastReceive = System.currentTimeMillis(); Double done = (amount * 100 - progress) / 100d; t.insulin = done; - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), done); - bolusingEvent.t = t; - bolusingEvent.percent = Math.min((int) (done / amount * 100), 100); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), done)); + bolusingEvent.setT(t); + bolusingEvent.setPercent(Math.min((int) (done / amount * 100), 100)); if (L.isEnabled(L.PUMPCOMM)) { log.debug("Bolus remaining: " + progress + " delivered: " + done); } - MainApp.bus().post(bolusingEvent); + RxBus.INSTANCE.send(bolusingEvent); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java index 39531b8b10..2ea50297fb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java @@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.treatments.Treatment; @@ -35,15 +36,15 @@ public class MsgBolusStop extends MessageBase { public void handleMessage(byte[] bytes) { if (L.isEnabled(L.PUMPCOMM)) log.debug("Messsage received"); - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; stopped = true; if (!forced) { t.insulin = amount; - bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_delivered); - bolusingEvent.percent = 100; + bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_delivered)); + bolusingEvent.setPercent(100); } else { - bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_stoped); + bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_stoped)); } - MainApp.bus().post(bolusingEvent); + RxBus.INSTANCE.send(bolusingEvent); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java index f697894778..a6fdaa8d0d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java @@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -44,10 +45,10 @@ public class MsgError extends MessageBase { } if (errorCode < 8) { // bolus delivering stopped - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; MsgBolusStop.stopped = true; - bolusingEvent.status = errorString; - MainApp.bus().post(bolusingEvent); + bolusingEvent.setStatus(errorString); + RxBus.INSTANCE.send(bolusingEvent); failed=true; } if (L.isEnabled(L.PUMPCOMM)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index f9029ca9aa..cc458eb3f8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -334,9 +334,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { } SystemClock.sleep(300); - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.t = t; - bolusingEvent.percent = 99; + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setT(t); + bolusingEvent.setPercent(99); mBolusingTreatment = null; @@ -360,8 +360,8 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { while (System.currentTimeMillis() < expectedEnd) { long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000); - MainApp.bus().post(bolusingEvent); + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); + RxBus.INSTANCE.send(bolusingEvent); SystemClock.sleep(1000); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java index 5e3fe3fbcd..7cb0a11f9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java @@ -9,6 +9,7 @@ import info.nightscout.androidaps.R; import com.cozmo.danar.util.BleCommandUtil; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; @@ -47,16 +48,16 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop extends DanaRS_Packet { } } - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; stopped = true; if (!forced) { t.insulin = amount; - bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_delivered); - bolusingEvent.percent = 100; + bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_delivered)); + bolusingEvent.setPercent(100); } else { - bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_stoped); + bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_stoped)); } - MainApp.bus().post(bolusingEvent); + RxBus.INSTANCE.send(bolusingEvent); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java index 3c916dc399..00b6483fbb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.treatments.Treatment; @@ -39,12 +40,12 @@ public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet { if (t != null) { t.insulin = deliveredInsulin; - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin); - bolusingEvent.t = t; - bolusingEvent.percent = Math.min((int) (deliveredInsulin / amount * 100), 100); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin)); + bolusingEvent.setT(t); + bolusingEvent.setPercent(Math.min((int) (deliveredInsulin / amount * 100), 100)); done = true; - MainApp.bus().post(bolusingEvent); + RxBus.INSTANCE.send(bolusingEvent); } if (L.isEnabled(L.PUMPCOMM)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java index 290e9743ef..1d650cb779 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.treatments.Treatment; @@ -40,12 +41,12 @@ public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet { if (t != null) { lastReceive = System.currentTimeMillis(); t.insulin = deliveredInsulin; - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin); - bolusingEvent.t = t; - bolusingEvent.percent = Math.min((int) (deliveredInsulin / amount * 100), 100); - failed = bolusingEvent.percent < 100? true: false; - MainApp.bus().post(bolusingEvent); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin)); + bolusingEvent.setT(t); + bolusingEvent.setPercent(Math.min((int) (deliveredInsulin / amount * 100), 100)); + failed = bolusingEvent.getPercent() < 100? true: false; + RxBus.INSTANCE.send(bolusingEvent); } if (L.isEnabled(L.PUMPCOMM)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index 5e6de8f5cf..50dd9fef1b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -335,9 +335,9 @@ public class DanaRSService extends Service { } } - final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.t = t; - bolusingEvent.percent = 99; + final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setT(t); + bolusingEvent.setPercent(99); bolusingTreatment = null; int speed = 12; @@ -356,8 +356,8 @@ public class DanaRSService extends Service { long expectedEnd = bolusStart + bolusDurationInMSec + 2000; while (System.currentTimeMillis() < expectedEnd) { long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000); - MainApp.bus().post(bolusingEvent); + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); + RxBus.INSTANCE.send(bolusingEvent); SystemClock.sleep(1000); } // do not call loadEvents() directly, reconnection may be needed @@ -367,7 +367,7 @@ public class DanaRSService extends Service { // reread bolus status RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // last bolus - bolusingEvent.percent = 100; + bolusingEvent.setPercent(100); RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting))); } }); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 3dd68f1af3..7c2cc7ede5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -403,9 +403,9 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } } - final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.t = t; - bolusingEvent.percent = 99; + final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setT(t); + bolusingEvent.setPercent(99); mBolusingTreatment = null; int speed = 12; @@ -424,8 +424,8 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { long expectedEnd = bolusStart + bolusDurationInMSec + 2000; while (System.currentTimeMillis() < expectedEnd) { long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000); - MainApp.bus().post(bolusingEvent); + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); + RxBus.INSTANCE.send(bolusingEvent); SystemClock.sleep(1000); } // do not call loadEvents() directly, reconnection may be needed @@ -435,7 +435,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { // load last bolus status RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus))); mSerialIOThread.sendMessage(new MsgStatus()); - bolusingEvent.percent = 100; + bolusingEvent.setPercent(100); RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting))); } }); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 99118549a2..de857b77ba 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -555,11 +555,11 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con result.enacted = true; Treatment t = new Treatment(); t.isSMB = detailedBolusInfo.isSMB; - final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.t = t; - bolusingEvent.status = MainApp.gs(R.string.insight_delivered, 0d, insulin); - bolusingEvent.percent = 0; - MainApp.bus().post(bolusingEvent); + final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setT(t); + bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, 0d, insulin)); + bolusingEvent.setPercent(0); + RxBus.INSTANCE.send(bolusingEvent); int trials = 0; InsightBolusID insightBolusID = new InsightBolusID(); insightBolusID.bolusID = bolusID; @@ -586,18 +586,18 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } if (activeBolus != null) { trials = -1; - int percentBefore = bolusingEvent.percent; - bolusingEvent.percent = (int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount())); - bolusingEvent.status = MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount()); - if (percentBefore != bolusingEvent.percent) - MainApp.bus().post(bolusingEvent); + int percentBefore = bolusingEvent.getPercent(); + bolusingEvent.setPercent((int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount()))); + bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount())); + if (percentBefore != bolusingEvent.getPercent()) + RxBus.INSTANCE.send(bolusingEvent); } else { synchronized ($bolusLock) { if (bolusCancelled || trials == -1 || trials++ >= 5) { if (!bolusCancelled) { - bolusingEvent.status = MainApp.gs(R.string.insight_delivered, insulin, insulin); - bolusingEvent.percent = 100; - MainApp.bus().post(bolusingEvent); + bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, insulin, insulin)); + bolusingEvent.setPercent(100); + RxBus.INSTANCE.send(bolusingEvent); } break; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java index bedd330f51..447367c510 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java @@ -271,17 +271,17 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface { while (delivering < detailedBolusInfo.insulin) { SystemClock.sleep(200); - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), delivering); - bolusingEvent.percent = Math.min((int) (delivering / detailedBolusInfo.insulin * 100), 100); - MainApp.bus().post(bolusingEvent); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), delivering)); + bolusingEvent.setPercent(Math.min((int) (delivering / detailedBolusInfo.insulin * 100), 100)); + RxBus.INSTANCE.send(bolusingEvent); delivering += 0.1d; } SystemClock.sleep(200); - EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance(); - bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivered), detailedBolusInfo.insulin); - bolusingEvent.percent = 100; - MainApp.bus().post(bolusingEvent); + EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; + bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivered), detailedBolusInfo.insulin)); + bolusingEvent.setPercent(100); + RxBus.INSTANCE.send(bolusingEvent); SystemClock.sleep(1000); if (L.isEnabled(L.PUMPCOMM)) log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java index cd0b666119..18e98dc4f9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java @@ -275,7 +275,7 @@ public class CommandQueue { public synchronized void cancelAllBoluses() { if (!isRunning(Command.CommandType.BOLUS)) { - MainApp.bus().post(new EventDismissBolusprogressIfRunning(new PumpEnactResult().success(true).enacted(false))); + RxBus.INSTANCE.send(new EventDismissBolusprogressIfRunning(new PumpEnactResult().success(true).enacted(false))); } removeAll(Command.CommandType.BOLUS); removeAll(Command.CommandType.SMB_BOLUS); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index 7016c217dc..2c6bd0f64c 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -68,7 +68,7 @@ public class QueueThread extends Thread { long secondsElapsed = (System.currentTimeMillis() - connectionStartTime) / 1000; if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { - MainApp.bus().post(new EventDismissBolusprogressIfRunning(null)); + RxBus.INSTANCE.send(new EventDismissBolusprogressIfRunning(null)); RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout))); if (L.isEnabled(L.PUMPQUEUE)) log.debug("timed out"); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java index 4dc132e128..f49a37612a 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java @@ -7,6 +7,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning; @@ -33,7 +34,7 @@ public class CommandBolus extends Command { PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().deliverTreatment(detailedBolusInfo); BolusProgressDialog.bolusEnded = true; - MainApp.bus().post(new EventDismissBolusprogressIfRunning(r)); + RxBus.INSTANCE.send(new EventDismissBolusprogressIfRunning(r)); if (L.isEnabled(L.PUMPQUEUE)) log.debug("Result success: " + r.success + " enacted: " + r.enacted); From 6044335b1d754208c24b1a8be3d88c303d8e2bcc Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 15 Oct 2019 09:52:48 +0200 Subject: [PATCH 10/13] Events to RxBus --- .../activities/HistoryBrowseActivity.java | 19 +- .../androidaps/db/DatabaseHelper.java | 4 +- .../general/nsclient/NSClientFragment.java | 131 ++++---- .../general/nsclient/NSClientPlugin.java | 22 +- .../general/nsclient/acks/NSAddAck.java | 3 +- .../nsclient/events/EventNSClientNewLog.java | 33 -- .../nsclient/events/EventNSClientNewLog.kt | 22 ++ .../nsclient/events/EventNSClientRestart.java | 10 - .../nsclient/events/EventNSClientRestart.kt | 5 + .../events/EventNSClientUpdateGUI.java | 10 - .../nsclient/events/EventNSClientUpdateGUI.kt | 5 + .../nsclient/services/NSClientService.java | 108 +++---- .../general/overview/OverviewFragment.java | 19 +- .../SmsCommunicatorPlugin.java | 4 +- .../IobCobCalculatorPlugin.java | 15 +- .../iobCobCalculator/IobCobOref1Thread.java | 4 +- .../iob/iobCobCalculator/IobCobThread.java | 5 +- .../events/EventIobCalculationProgress.java | 11 - .../events/EventIobCalculationProgress.kt | 5 + .../events/EventNewHistoryData.java | 15 - .../events/EventNewHistoryData.kt | 5 + .../plugins/profile/ns/NSProfilePlugin.java | 2 +- .../plugins/pump/combo/ComboFragment.java | 293 +++++++++--------- .../plugins/pump/combo/ComboPlugin.java | 18 +- .../combo/events/EventComboPumpUpdateGUI.java | 8 - .../combo/events/EventComboPumpUpdateGUI.kt | 5 + .../plugins/pump/danaR/DanaRFragment.kt | 11 +- .../pump/medtronic/MedtronicFragment.kt | 12 +- .../plugins/treatments/TreatmentService.java | 26 +- .../fragments/TreatmentsBolusFragment.java | 2 +- .../TreatmentsCareportalFragment.java | 2 +- .../TreatmentsProfileSwitchFragment.java | 2 +- .../TreatmentsTempTargetFragment.java | 2 +- .../androidaps/queue/QueueThread.java | 6 +- 34 files changed, 406 insertions(+), 438 deletions(-) delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java index b16b48b149..79f3fbf4d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java @@ -16,7 +16,6 @@ import androidx.appcompat.widget.PopupMenu; import androidx.core.content.res.ResourcesCompat; import com.jjoe64.graphview.GraphView; -import com.squareup.otto.Subscribe; import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; import org.slf4j.Logger; @@ -169,7 +168,6 @@ public class HistoryBrowseActivity extends NoSplashActivity { @Override public void onPause() { super.onPause(); - MainApp.bus().unregister(this); disposable.clear(); iobCobCalculatorPlugin.stopCalculation("onPause"); } @@ -177,7 +175,6 @@ public class HistoryBrowseActivity extends NoSplashActivity { @Override public void onResume() { super.onResume(); - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventAutosensCalculationFinished.class) .observeOn(AndroidSchedulers.mainThread()) @@ -190,6 +187,14 @@ public class HistoryBrowseActivity extends NoSplashActivity { } }, FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventIobCalculationProgress.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (iobCalculationProgressView != null) + iobCalculationProgressView.setText(event.getProgress()); + }, FabricPrivacy::logException) + ); // set start of current day Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); @@ -210,14 +215,6 @@ public class HistoryBrowseActivity extends NoSplashActivity { iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished); } - @Subscribe - public void onStatusEvent(final EventIobCalculationProgress e) { - runOnUiThread(() -> { - if (iobCalculationProgressView != null) - iobCalculationProgressView.setText(e.progress); - }); - } - void updateGUI(String from) { log.debug("updateGUI from: " + from); diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 338a662201..d8926fc4c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -1037,7 +1037,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { RxBus.INSTANCE.send(new EventReloadTempBasalData()); RxBus.INSTANCE.send(new EventTempBasalChange()); if (earliestDataChange != null) - MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); + RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; scheduledTemBasalsPost = null; } @@ -1372,7 +1372,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { log.debug("Firing EventExtendedBolusChange"); RxBus.INSTANCE.send(new EventReloadTreatmentData(new EventExtendedBolusChange())); if (earliestDataChange != null) - MainApp.bus().post(new EventNewHistoryData(earliestDataChange)); + RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; scheduledExtendedBolusPost = null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java index 50674c5a94..112eb9c951 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.nsclient; -import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; @@ -17,18 +16,22 @@ import android.widget.CompoundButton; import android.widget.ScrollView; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.fragment.app.Fragment; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; + +public class NSClientFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { + private CompositeDisposable disposable = new CompositeDisposable(); -public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener { private TextView logTextView; private TextView queueTextView; private TextView urlTextView; @@ -45,51 +48,61 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - try { - View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false); + View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false); - logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview); - autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll); - autoscrollCheckbox.setChecked(NSClientPlugin.getPlugin().autoscroll); - autoscrollCheckbox.setOnCheckedChangeListener(this); - pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused); - pausedCheckbox.setChecked(NSClientPlugin.getPlugin().paused); - pausedCheckbox.setOnCheckedChangeListener(this); - logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log); - queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue); - urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url); - statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status); + logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview); + autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll); + autoscrollCheckbox.setChecked(NSClientPlugin.getPlugin().autoscroll); + autoscrollCheckbox.setOnCheckedChangeListener(this); + pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused); + pausedCheckbox.setChecked(NSClientPlugin.getPlugin().paused); + pausedCheckbox.setOnCheckedChangeListener(this); + logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log); + queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue); + urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url); + statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status); - clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog); - clearlog.setOnClickListener(this); - clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); - restart = (TextView) view.findViewById(R.id.nsclientinternal_restart); - restart.setOnClickListener(this); - restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); - delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow); - delivernow.setOnClickListener(this); - delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); - clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue); - clearqueue.setOnClickListener(this); - clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); - showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue); - showqueue.setOnClickListener(this); - showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog); + clearlog.setOnClickListener(this); + clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + restart = (TextView) view.findViewById(R.id.nsclientinternal_restart); + restart.setOnClickListener(this); + restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow); + delivernow.setOnClickListener(this); + delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue); + clearqueue.setOnClickListener(this); + clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue); + showqueue.setOnClickListener(this); + showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); - updateGUI(); - return view; - } catch (Exception e) { - FabricPrivacy.logException(e); - } + return view; + } - return null; + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventNSClientUpdateGUI.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.nsclientinternal_restart: - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); FabricPrivacy.getInstance().logCustom("NSClientRestart"); break; case R.id.nsclientinternal_delivernow: @@ -108,7 +121,7 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { UploadQueue.clearQueue(); - updateGUI(); + updateGui(); FabricPrivacy.getInstance().logCustom("NSClientClearQueue"); } }); @@ -116,7 +129,7 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick builder.show(); break; case R.id.nsclientinternal_showqueue: - MainApp.bus().post(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList())); + RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList())); break; } } @@ -126,38 +139,28 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick switch (buttonView.getId()) { case R.id.nsclientinternal_paused: NSClientPlugin.getPlugin().pause(isChecked); - updateGUI(); + updateGui(); FabricPrivacy.getInstance().logCustom("NSClientPause"); break; case R.id.nsclientinternal_autoscroll: SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked); NSClientPlugin.getPlugin().autoscroll = isChecked; - updateGUI(); + updateGui(); break; } } - @Subscribe - public void onStatusEvent(final EventNSClientUpdateGUI ev) { - updateGUI(); - } - - @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - NSClientPlugin.getPlugin().updateLog(); - pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false)); - logTextView.setText(NSClientPlugin.getPlugin().textLog); - if (NSClientPlugin.getPlugin().autoscroll) { - logScrollview.fullScroll(ScrollView.FOCUS_DOWN); - } - urlTextView.setText(NSClientPlugin.getPlugin().url()); - Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " " + UploadQueue.size() + ""); - queueTextView.setText(queuetext); - statusTextView.setText(NSClientPlugin.getPlugin().status); - }); + protected void updateGui() { + NSClientPlugin.getPlugin().updateLog(); + pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false)); + logTextView.setText(NSClientPlugin.getPlugin().textLog); + if (NSClientPlugin.getPlugin().autoscroll) { + logScrollview.fullScroll(ScrollView.FOCUS_DOWN); + } + urlTextView.setText(NSClientPlugin.getPlugin().url()); + Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " " + UploadQueue.size() + ""); + queueTextView.setText(queuetext); + statusTextView.setText(NSClientPlugin.getPlugin().status); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index 150e75a119..b265bab54e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -113,7 +113,7 @@ public class NSClientPlugin extends PluginBase { .observeOn(Schedulers.io()) .subscribe(event -> { status = event.getStatus(); - MainApp.bus().post(new EventNSClientUpdateGUI()); + RxBus.INSTANCE.send(new EventNSClientUpdateGUI()); }, FabricPrivacy::logException) ); disposable.add(RxBus.INSTANCE @@ -136,6 +136,15 @@ public class NSClientPlugin extends PluginBase { } }, FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventNSClientNewLog.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + addToLog(event); + if (L.isEnabled(L.NSCLIENT)) + log.debug(event.getAction() + " " + event.getLogText()); + }, FabricPrivacy::logException) + ); } @Override @@ -171,19 +180,12 @@ public class NSClientPlugin extends PluginBase { } }; - @Subscribe - public void onStatusEvent(final EventNSClientNewLog ev) { - addToLog(ev); - if (L.isEnabled(L.NSCLIENT)) - log.debug(ev.action + " " + ev.logText); - } - synchronized void clearLog() { handler.post(() -> { synchronized (listLog) { listLog.clear(); } - MainApp.bus().post(new EventNSClientUpdateGUI()); + RxBus.INSTANCE.send(new EventNSClientUpdateGUI()); }); } @@ -196,7 +198,7 @@ public class NSClientPlugin extends PluginBase { listLog.remove(0); } } - MainApp.bus().post(new EventNSClientUpdateGUI()); + RxBus.INSTANCE.send(new EventNSClientUpdateGUI()); }); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java index ead373d61d..18c31c80e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java @@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import io.socket.client.Ack; @@ -44,7 +45,7 @@ public class NSAddAck extends Event implements Ack { if (response.has("result")) { _id = null; if (response.getString("result").contains("Not")) { - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); return; } if (L.isEnabled(L.NSCLIENT)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java deleted file mode 100644 index 121085cb94..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.plugins.general.nsclient.events; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 15.02.2017. - */ - -public class EventNSClientNewLog extends Event { - public Date date = new Date(); - public String action; - public String logText; - public EventNSClientNewLog(String action, String logText) { - this.action = action; - this.logText = logText; - } - - SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); - - public StringBuilder toPreparedHtml() { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(timeFormat.format(date)); - stringBuilder.append(" "); - stringBuilder.append(action); - stringBuilder.append(" "); - stringBuilder.append(logText); - stringBuilder.append("
"); - return stringBuilder; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt new file mode 100644 index 0000000000..38d6bcfd0f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.plugins.general.nsclient.events + +import info.nightscout.androidaps.events.Event +import java.text.SimpleDateFormat +import java.util.* + +class EventNSClientNewLog(var action: String, var logText: String) : Event() { + var date = Date() + + private var timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault()) + + fun toPreparedHtml(): StringBuilder { + val stringBuilder = StringBuilder() + stringBuilder.append(timeFormat.format(date)) + stringBuilder.append(" ") + stringBuilder.append(action) + stringBuilder.append(" ") + stringBuilder.append(logText) + stringBuilder.append("
") + return stringBuilder + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java deleted file mode 100644 index b5481ce741..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java +++ /dev/null @@ -1,10 +0,0 @@ -package info.nightscout.androidaps.plugins.general.nsclient.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 15.02.2017. - */ - -public class EventNSClientRestart extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt new file mode 100644 index 0000000000..49333b6840 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.nsclient.events + +import info.nightscout.androidaps.events.Event + +class EventNSClientRestart : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java deleted file mode 100644 index 60d74a249d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java +++ /dev/null @@ -1,10 +0,0 @@ -package info.nightscout.androidaps.plugins.general.nsclient.events; - -import info.nightscout.androidaps.events.EventUpdateGui; - -/** - * Created by mike on 17.02.2017. - */ - -public class EventNSClientUpdateGUI extends EventUpdateGui { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt new file mode 100644 index 0000000000..891e61895c --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.nsclient.events + +import info.nightscout.androidaps.events.EventUpdateGui + +class EventNSClientUpdateGUI : EventUpdateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index ab964ccac6..d1f8bbdead 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -167,6 +167,14 @@ public class NSClientService extends Service { stopSelf(); }, FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventNSClientRestart.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + latestDateInReceivedData = 0; + restart(); + }, FabricPrivacy::logException) + ); } @Override @@ -202,12 +210,6 @@ public class NSClientService extends Service { MainApp.bus().register(this); } - @Subscribe - public void onStatusEvent(final EventNSClientRestart ev) { - latestDateInReceivedData = 0; - restart(); - } - public void initialize() { dataCounter = 0; @@ -218,13 +220,13 @@ public class NSClientService extends Service { RxBus.INSTANCE.send(new EventNSClientStatus("Initializing")); if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) { - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "not allowed")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "not allowed")); RxBus.INSTANCE.send(new EventNSClientStatus("Not allowed")); } else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) { - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "paused")); RxBus.INSTANCE.send(new EventNSClientStatus("Paused")); } else if (!nsEnabled) { - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "disabled")); RxBus.INSTANCE.send(new EventNSClientStatus("Disabled")); } else if (!nsURL.equals("")) { try { @@ -236,7 +238,7 @@ public class NSClientService extends Service { mSocket.on(Socket.EVENT_CONNECT, onConnect); mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect); mSocket.on(Socket.EVENT_PING, onPing); - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "do connect")); mSocket.connect(); mSocket.on("dataUpdate", onDataUpdate); mSocket.on("announcement", onAnnouncement); @@ -244,11 +246,11 @@ public class NSClientService extends Service { mSocket.on("urgent_alarm", onUrgentAlarm); mSocket.on("clear_alarm", onClearAlarm); } catch (URISyntaxException | RuntimeException e) { - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax")); RxBus.INSTANCE.send(new EventNSClientStatus("Wrong URL syntax")); } } else { - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "No NS URL specified")); RxBus.INSTANCE.send(new EventNSClientStatus("Not configured")); } } @@ -258,7 +260,7 @@ public class NSClientService extends Service { public void call(Object... args) { connectCounter++; String socketId = mSocket != null ? mSocket.id() : "NULL"; - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId)); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId)); if (mSocket != null) sendAuthMessage(new NSAuthAck()); watchdog(); @@ -275,16 +277,16 @@ public class NSClientService extends Service { reconnections.remove(r); } } - MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS)); + RxBus.INSTANCE.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)); - MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins")); + RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins")); NSClientPlugin.getPlugin().pause(true); - MainApp.bus().post(new EventNSClientUpdateGUI()); + RxBus.INSTANCE.send(new EventNSClientUpdateGUI()); new Thread(() -> { SystemClock.sleep(T.mins(WATCHDOG_RECONNECT_IN).msecs()); - MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient")); + RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient")); NSClientPlugin.getPlugin().pause(false); }).start(); } @@ -296,7 +298,7 @@ public class NSClientService extends Service { public void call(Object... args) { if (L.isEnabled(L.NSCLIENT)) log.debug("disconnect reason: {}", args); - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } }; @@ -311,7 +313,7 @@ public class NSClientService extends Service { mSocket.off("urgent_alarm"); mSocket.off("clear_alarm"); - MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "destroy")); + RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "destroy")); isConnected = false; hasWriteAuth = false; mSocket.disconnect(); @@ -332,7 +334,7 @@ public class NSClientService extends Service { log.error("Unhandled exception", e); return; } - MainApp.bus().post(new EventNSClientNewLog("AUTH", "requesting auth")); + RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", "requesting auth")); if (mSocket != null) mSocket.emit("authorize", authMessage, ack); } @@ -347,12 +349,12 @@ public class NSClientService extends Service { isConnected = true; hasWriteAuth = ack.write && ack.write_treatment; RxBus.INSTANCE.send(new EventNSClientStatus(connectionStatus)); - MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus)); + RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", connectionStatus)); if (!ack.write) { - MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); + RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); } if (!ack.write_treatment) { - MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!")); + RxBus.INSTANCE.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); @@ -372,7 +374,7 @@ public class NSClientService extends Service { private Emitter.Listener onPing = new Emitter.Listener() { @Override public void call(final Object... args) { - MainApp.bus().post(new EventNSClientNewLog("PING", "received")); + RxBus.INSTANCE.send(new EventNSClientNewLog("PING", "received")); // send data if there is something waiting resend("Ping received"); } @@ -401,7 +403,7 @@ public class NSClientService extends Service { return; } try { - MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); + RxBus.INSTANCE.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received"))); } catch (Exception e) { FabricPrivacy.logException(e); log.error("Unhandled exception", e); @@ -428,7 +430,7 @@ public class NSClientService extends Service { */ @Override public void call(final Object... args) { - MainApp.bus().post(new EventNSClientNewLog("ALARM", "received")); + RxBus.INSTANCE.send(new EventNSClientNewLog("ALARM", "received")); JSONObject data; try { data = (JSONObject) args[0]; @@ -467,7 +469,7 @@ public class NSClientService extends Service { log.error("Unhandled exception", e); return; } - MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received")); + RxBus.INSTANCE.send(new EventNSClientNewLog("URGENTALARM", "received")); BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); @@ -493,7 +495,7 @@ public class NSClientService extends Service { log.error("Unhandled exception", e); return; } - MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received")); + RxBus.INSTANCE.send(new EventNSClientNewLog("CLEARALARM", "received")); BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext()); if (L.isEnabled(L.NSCLIENT)) log.debug(data.toString()); @@ -518,7 +520,7 @@ public class NSClientService extends Service { // delta means only increment/changes are comming boolean isDelta = data.has("delta"); boolean isFull = !isDelta; - MainApp.bus().post(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full"))); + RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full"))); if (data.has("profiles")) { JSONArray profiles = data.getJSONArray("profiles"); @@ -526,7 +528,7 @@ public class NSClientService extends Service { JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1); profileStore = new ProfileStore(profile); broadcastProfile = true; - MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received")); + RxBus.INSTANCE.send(new EventNSClientNewLog("PROFILE", "profile received")); } } @@ -536,7 +538,7 @@ public class NSClientService extends Service { if (!status.has("versionNum")) { if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) { - MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); + RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } } else { nightscoutVersionName = nsSettingsStatus.getVersion(); @@ -561,13 +563,13 @@ public class NSClientService extends Service { } */ } else if (!isDelta) { - MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); + RxBus.INSTANCE.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); - MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting")); + RxBus.INSTANCE.send(new EventNSClientNewLog("PROFILE", "broadcasting")); } if (data.has("treatments")) { @@ -576,7 +578,7 @@ public class NSClientService extends Service { JSONArray updatedTreatments = new JSONArray(); JSONArray addedTreatments = new JSONArray(); if (treatments.length() > 0) - MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments")); + RxBus.INSTANCE.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); @@ -610,7 +612,7 @@ public class NSClientService extends Service { if (data.has("devicestatus")) { JSONArray devicestatuses = data.getJSONArray("devicestatus"); if (devicestatuses.length() > 0) { - MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses")); + RxBus.INSTANCE.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 @@ -625,7 +627,7 @@ public class NSClientService extends Service { JSONArray updatedFoods = new JSONArray(); JSONArray addedFoods = new JSONArray(); if (foods.length() > 0) - MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods")); + RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods")); for (Integer index = 0; index < foods.length(); index++) { JSONObject jsonFood = foods.getJSONObject(index); @@ -655,7 +657,7 @@ public class NSClientService extends Service { if (data.has("mbgs")) { JSONArray mbgs = data.getJSONArray("mbgs"); if (mbgs.length() > 0) - MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs")); + RxBus.INSTANCE.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 @@ -666,7 +668,7 @@ public class NSClientService extends Service { if (data.has("cals")) { JSONArray cals = data.getJSONArray("cals"); if (cals.length() > 0) - MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals")); + RxBus.INSTANCE.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 @@ -677,10 +679,10 @@ public class NSClientService extends Service { if (data.has("sgvs")) { JSONArray sgvs = data.getJSONArray("sgvs"); if (sgvs.length() > 0) - MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs")); + RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs")); for (Integer index = 0; index < sgvs.length(); index++) { JSONObject jsonSgv = sgvs.getJSONObject(index); - // MainApp.bus().post(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString()); + // RxBus.INSTANCE.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 @@ -699,11 +701,11 @@ public class NSClientService extends Service { } BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta); } - MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); + RxBus.INSTANCE.send(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); } catch (JSONException e) { log.error("Unhandled exception", e); } - //MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); + //RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); } finally { if (wakeLock.isHeld()) wakeLock.release(); } @@ -721,7 +723,7 @@ public class NSClientService extends Service { message.put("_id", dbr._id); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbUpdate", message, ack); - MainApp.bus().post(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } @@ -735,7 +737,7 @@ public class NSClientService extends Service { message.put("_id", dbr._id); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbUpdateUnset", message, ack); - MainApp.bus().post(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } @@ -748,7 +750,7 @@ public class NSClientService extends Service { message.put("collection", dbr.collection); message.put("_id", dbr._id); mSocket.emit("dbRemove", message, ack); - MainApp.bus().post(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { log.error("Unhandled exception", e); } @@ -758,9 +760,9 @@ public class NSClientService extends Service { public void onStatusEvent(NSUpdateAck ack) { if (ack.result) { uploadQueue.removeID(ack.action, ack._id); - MainApp.bus().post(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); } else { - MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); + RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); } } @@ -771,7 +773,7 @@ public class NSClientService extends Service { message.put("collection", dbr.collection); message.put("data", new JSONObject(dbr.data)); mSocket.emit("dbAdd", message, ack); - MainApp.bus().post(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); } catch (JSONException e) { log.error("Unhandled exception", e); } @@ -780,16 +782,16 @@ public class NSClientService extends Service { public void sendAlarmAck(AlarmAck alarmAck) { if (!isConnected || !hasWriteAuth) return; mSocket.emit("ack", alarmAck.level, alarmAck.group, alarmAck.silenceTime); - MainApp.bus().post(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime)); + RxBus.INSTANCE.send(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime)); } @Subscribe public void onStatusEvent(NSAddAck ack) { if (ack.nsClientID != null) { uploadQueue.removeID(ack.json); - MainApp.bus().post(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); } else { - MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); + RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); } } @@ -811,7 +813,7 @@ public class NSClientService extends Service { } lastResendTime = System.currentTimeMillis(); - MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason)); + RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", "Resend started: " + reason)); CloseableIterator iterator = null; int maxcount = 30; @@ -842,7 +844,7 @@ public class NSClientService extends Service { log.error("Unhandled exception", e); } - MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); + RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); } }); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index b57ab1d35d..6681f53f40 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -942,6 +942,15 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, .subscribe(event -> updatePumpStatus(event.getStatus()), FabricPrivacy::logException )); + disposable.add(RxBus.INSTANCE + .toObservable(EventIobCalculationProgress.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (iobCalculationProgressView != null) + iobCalculationProgressView.setText(event.getProgress()); + }, + FabricPrivacy::logException + )); sRefreshLoop = () -> { scheduleUpdateGUI("refreshLoop"); sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); @@ -958,16 +967,6 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, scheduleUpdateGUI("EventNewOpenLoopNotification"); } - @Subscribe - public void onStatusEvent(final EventIobCalculationProgress e) { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - if (iobCalculationProgressView != null) - iobCalculationProgressView.setText(e.progress); - }); - } - private void hideTempRecommendation() { Activity activity = getActivity(); if (activity != null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java index e14b3878b1..5b334e2812 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java @@ -411,7 +411,7 @@ public class SmsCommunicatorPlugin extends PluginBase { private void processTREATMENTS(String[] splitted, Sms receivedSms) { if (splitted[1].toUpperCase().equals("REFRESH")) { TreatmentsPlugin.getPlugin().getService().resetTreatments(); - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); sendSMS(new Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT")); receivedSms.processed = true; } else @@ -420,7 +420,7 @@ public class SmsCommunicatorPlugin extends PluginBase { private void processNSCLIENT(String[] splitted, Sms receivedSms) { if (splitted[1].toUpperCase().equals("RESTART")) { - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); sendSMS(new Sms(receivedSms.phoneNumber, "NSCLIENT RESTART SENT")); receivedSms.processed = true; } else diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index 16df35c75d..0cd725b5f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -6,8 +6,6 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.collection.LongSparseArray; -import com.squareup.otto.Subscribe; - import org.json.JSONArray; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -90,7 +88,6 @@ public class IobCobCalculatorPlugin extends PluginBase { @Override protected void onStart() { super.onStart(); - MainApp.bus().register(this); // EventConfigBuilderChange disposable.add(RxBus.INSTANCE .toObservable(EventConfigBuilderChange.class) @@ -194,12 +191,17 @@ public class IobCobCalculatorPlugin extends PluginBase { runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, event); }, FabricPrivacy::logException) ); + // EventNewHistoryData + disposable.add(RxBus.INSTANCE + .toObservable(EventNewHistoryData.class) + .observeOn(Schedulers.io()) + .subscribe(event -> newHistoryData(event), FabricPrivacy::logException) + ); } @Override protected void onStop() { disposable.clear(); - MainApp.bus().unregister(this); super.onStop(); } @@ -763,8 +765,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated - @Subscribe - public void onEventNewHistoryData(EventNewHistoryData ev) { + public void newHistoryData(EventNewHistoryData ev) { if (this != getPlugin()) { if (L.isEnabled(L.AUTOSENS)) log.debug("Ignoring event for non default instance"); @@ -774,7 +775,7 @@ public class IobCobCalculatorPlugin extends PluginBase { stopCalculation("onEventNewHistoryData"); synchronized (dataLock) { // clear up 5 min back for proper COB calculation - long time = ev.time - 5 * 60 * 1000L; + long time = ev.getTime() - 5 * 60 * 1000L; if (L.isEnabled(L.AUTOSENS)) log.debug("Invalidating cached data to: " + DateUtil.dateAndTimeFullString(time)); for (int index = iobTable.size() - 1; index >= 0; index--) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java index 84cca4e90f..07d1b52947 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java @@ -119,7 +119,7 @@ public class IobCobOref1Thread extends Thread { // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { String progress = i + (MainApp.isDev() ? " (" + from + ")" : ""); - MainApp.bus().post(new EventIobCalculationProgress(progress)); + RxBus.INSTANCE.send(new EventIobCalculationProgress(progress)); if (iobCobCalculatorPlugin.stopCalculationTrigger) { iobCobCalculatorPlugin.stopCalculationTrigger = false; @@ -392,7 +392,7 @@ public class IobCobOref1Thread extends Thread { } finally { if (mWakeLock != null) mWakeLock.release(); - MainApp.bus().post(new EventIobCalculationProgress("")); + RxBus.INSTANCE.send(new EventIobCalculationProgress("")); if (L.isEnabled(L.AUTOSENS)) { log.debug("AUTOSENSDATA thread ended: " + from); log.debug("Midnights: " + MidnightTime.log()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java index 65495b1fd2..a8ecc2a06a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java @@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator; import android.content.Context; import android.os.PowerManager; import android.os.SystemClock; + import androidx.collection.LongSparseArray; import org.slf4j.Logger; @@ -117,7 +118,7 @@ public class IobCobThread extends Thread { // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { String progress = i + (MainApp.isDev() ? " (" + from + ")" : ""); - MainApp.bus().post(new EventIobCalculationProgress(progress)); + RxBus.INSTANCE.send(new EventIobCalculationProgress(progress)); if (iobCobCalculatorPlugin.stopCalculationTrigger) { iobCobCalculatorPlugin.stopCalculationTrigger = false; @@ -317,7 +318,7 @@ public class IobCobThread extends Thread { } finally { if (mWakeLock != null) mWakeLock.release(); - MainApp.bus().post(new EventIobCalculationProgress("")); + RxBus.INSTANCE.send(new EventIobCalculationProgress("")); if (L.isEnabled(L.AUTOSENS)) { log.debug("AUTOSENSDATA thread ended: " + from); log.debug("Midnights: " + MidnightTime.log()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java deleted file mode 100644 index 5a4a9a8eae..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events; - -import info.nightscout.androidaps.events.Event; - -public class EventIobCalculationProgress extends Event { - public String progress; - - public EventIobCalculationProgress(String progress) { - this.progress = progress; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt new file mode 100644 index 0000000000..f2e8059b10 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events + +import info.nightscout.androidaps.events.Event + +class EventIobCalculationProgress(var progress: String) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java deleted file mode 100644 index f84fdd1adf..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java +++ /dev/null @@ -1,15 +0,0 @@ -package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 26.04.2017. - */ - -public class EventNewHistoryData extends Event { - public long time = 0; - - public EventNewHistoryData(long time) { - this.time = time; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt new file mode 100644 index 0000000000..c2372aff83 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events + +import info.nightscout.androidaps.events.Event + +class EventNewHistoryData(var time: Long) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java index 0dd48fa0bb..13cb2dc545 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java @@ -111,7 +111,7 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface { if (L.isEnabled(L.PROFILE)) log.debug("Stored profile not found"); // force restart of nsclient to fetch profile - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java index 1a924fa9f5..bfd5c6104e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java @@ -5,28 +5,33 @@ import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; -import androidx.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.annotation.NonNull; +import androidx.fragment.app.Fragment; -import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; -import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.pump.combo.events.EventComboPumpUpdateGUI; +import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState; +import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.events.EventQueueChanged; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; + +public class ComboFragment extends Fragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); -public class ComboFragment extends SubscriberFragment implements View.OnClickListener { private TextView stateView; private TextView activityView; private TextView batteryView; @@ -58,10 +63,31 @@ public class ComboFragment extends SubscriberFragment implements View.OnClickLis refreshButton = view.findViewById(R.id.combo_refresh_button); refreshButton.setOnClickListener(this); - updateGUI(); return view; } + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventComboPumpUpdateGUI.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(EventQueueChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + private void runOnUiThread(Runnable action) { Activity activity = getActivity(); if (activity != null) { @@ -84,148 +110,135 @@ public class ComboFragment extends SubscriberFragment implements View.OnClickLis } } - @Subscribe - public void onStatusEvent(final EventComboPumpUpdateGUI ignored) { - updateGUI(); - } + public void updateGui() { + ComboPlugin plugin = ComboPlugin.getPlugin(); - @Subscribe - public void onStatusEvent(final EventQueueChanged ignored) { - updateGUI(); - } + // state + stateView.setText(plugin.getStateSummary()); + PumpState ps = plugin.getPump().state; + if (ps.insulinState == PumpState.EMPTY || ps.batteryState == PumpState.EMPTY + || ps.activeAlert != null && ps.activeAlert.errorCode != null) { + stateView.setTextColor(Color.RED); + stateView.setTypeface(null, Typeface.BOLD); + } else if (plugin.getPump().state.suspended + || ps.activeAlert != null && ps.activeAlert.warningCode != null) { + stateView.setTextColor(Color.YELLOW); + stateView.setTypeface(null, Typeface.BOLD); + } else { + stateView.setTextColor(Color.WHITE); + stateView.setTypeface(null, Typeface.NORMAL); + } + // activity + String activity = plugin.getPump().activity; + if (activity != null) { + activityView.setTextColor(Color.WHITE); + activityView.setTextSize(14); + activityView.setText(activity); + } else if (ConfigBuilderPlugin.getPlugin().getCommandQueue().size() > 0) { + activityView.setTextColor(Color.WHITE); + activityView.setTextSize(14); + activityView.setText(""); + } else if (plugin.isInitialized()) { + activityView.setTextColor(Color.WHITE); + activityView.setTextSize(20); + activityView.setText("{fa-bed}"); + } else { + activityView.setTextColor(Color.RED); + activityView.setTextSize(14); + activityView.setText(MainApp.gs(R.string.pump_unreachable)); + } - public void updateGUI() { - runOnUiThread(() -> { - ComboPlugin plugin = ComboPlugin.getPlugin(); - - // state - stateView.setText(plugin.getStateSummary()); - PumpState ps = plugin.getPump().state; - if (ps.insulinState == PumpState.EMPTY || ps.batteryState == PumpState.EMPTY - || ps.activeAlert != null && ps.activeAlert.errorCode != null) { - stateView.setTextColor(Color.RED); - stateView.setTypeface(null, Typeface.BOLD); - } else if (plugin.getPump().state.suspended - || ps.activeAlert != null && ps.activeAlert.warningCode != null) { - stateView.setTextColor(Color.YELLOW); - stateView.setTypeface(null, Typeface.BOLD); + if (plugin.isInitialized()) { + // battery + batteryView.setTextSize(20); + if (ps.batteryState == PumpState.EMPTY) { + batteryView.setText("{fa-battery-empty}"); + batteryView.setTextColor(Color.RED); + } else if (ps.batteryState == PumpState.LOW) { + batteryView.setText("{fa-battery-quarter}"); + batteryView.setTextColor(Color.YELLOW); } else { - stateView.setTextColor(Color.WHITE); - stateView.setTypeface(null, Typeface.NORMAL); + batteryView.setText("{fa-battery-full}"); + batteryView.setTextColor(Color.WHITE); } - // activity - String activity = plugin.getPump().activity; - if (activity != null) { - activityView.setTextColor(Color.WHITE); - activityView.setTextSize(14); - activityView.setText(activity); - } else if (ConfigBuilderPlugin.getPlugin().getCommandQueue().size() > 0) { - activityView.setTextColor(Color.WHITE); - activityView.setTextSize(14); - activityView.setText(""); - } else if (plugin.isInitialized()){ - activityView.setTextColor(Color.WHITE); - activityView.setTextSize(20); - activityView.setText("{fa-bed}"); + // reservoir + int reservoirLevel = plugin.getPump().reservoirLevel; + if (reservoirLevel != -1) { + reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname)); + } else if (ps.insulinState == PumpState.LOW) { + reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low)); + } else if (ps.insulinState == PumpState.EMPTY) { + reservoirView.setText(MainApp.gs(R.string.combo_reservoir_empty)); } else { - activityView.setTextColor(Color.RED); - activityView.setTextSize(14); - activityView.setText(MainApp.gs(R.string.pump_unreachable)); + reservoirView.setText(MainApp.gs(R.string.combo_reservoir_normal)); } - if (plugin.isInitialized()) { - // battery - batteryView.setTextSize(20); - if (ps.batteryState == PumpState.EMPTY) { - batteryView.setText("{fa-battery-empty}"); - batteryView.setTextColor(Color.RED); - } else if (ps.batteryState == PumpState.LOW) { - batteryView.setText("{fa-battery-quarter}"); - batteryView.setTextColor(Color.YELLOW); - } else { - batteryView.setText("{fa-battery-full}"); - batteryView.setTextColor(Color.WHITE); - } - - // reservoir - int reservoirLevel = plugin.getPump().reservoirLevel; - if (reservoirLevel != -1) { - reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname)); - } else if (ps.insulinState == PumpState.LOW) { - reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low)); - } else if (ps.insulinState == PumpState.EMPTY) { - reservoirView.setText(MainApp.gs(R.string.combo_reservoir_empty)); - } else { - reservoirView.setText(MainApp.gs(R.string.combo_reservoir_normal)); - } - - if (ps.insulinState == PumpState.UNKNOWN) { - reservoirView.setTextColor(Color.WHITE); - reservoirView.setTypeface(null, Typeface.NORMAL); - } else if (ps.insulinState == PumpState.LOW) { - reservoirView.setTextColor(Color.YELLOW); - reservoirView.setTypeface(null, Typeface.BOLD); - } else if (ps.insulinState == PumpState.EMPTY) { - reservoirView.setTextColor(Color.RED); - reservoirView.setTypeface(null, Typeface.BOLD); - } else { - reservoirView.setTextColor(Color.WHITE); - reservoirView.setTypeface(null, Typeface.NORMAL); - } - - // last connection - String minAgo = DateUtil.minAgo(plugin.getPump().lastSuccessfulCmdTime); - long min = (System.currentTimeMillis() - plugin.getPump().lastSuccessfulCmdTime) / 1000 / 60; - if (plugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) { - lastConnectionView.setText(R.string.combo_pump_connected_now); - lastConnectionView.setTextColor(Color.WHITE); - } else if (plugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) { - lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min)); - lastConnectionView.setTextColor(Color.RED); - } else { - lastConnectionView.setText(minAgo); - lastConnectionView.setTextColor(Color.WHITE); - } - - // last bolus - Bolus bolus = plugin.getPump().lastBolus; - if (bolus != null) { - long agoMsc = System.currentTimeMillis() - bolus.timestamp; - double bolusMinAgo = agoMsc / 60d / 1000d; - String unit = MainApp.gs(R.string.insulin_unit_shortname); - String ago; - if ((agoMsc < 60 * 1000)) { - ago = MainApp.gs(R.string.combo_pump_connected_now); - } else if (bolusMinAgo < 60) { - ago = DateUtil.minAgo(bolus.timestamp); - } else { - ago = DateUtil.hourAgo(bolus.timestamp); - } - lastBolusView.setText(MainApp.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); - } else { - lastBolusView.setText(""); - } - - // base basal rate - baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate())); - - // TBR - String tbrStr = ""; - if (ps.tbrPercent != -1 && ps.tbrPercent != 100) { - long minSinceRead = (System.currentTimeMillis() - plugin.getPump().state.timestamp) / 1000 / 60; - long remaining = ps.tbrRemainingDuration - minSinceRead; - if (remaining >= 0) { - tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining); - } - } - tempBasalText.setText(tbrStr); - - // stats - bolusCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L))); - tbrCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_TBRS_SET, 0L))); + if (ps.insulinState == PumpState.UNKNOWN) { + reservoirView.setTextColor(Color.WHITE); + reservoirView.setTypeface(null, Typeface.NORMAL); + } else if (ps.insulinState == PumpState.LOW) { + reservoirView.setTextColor(Color.YELLOW); + reservoirView.setTypeface(null, Typeface.BOLD); + } else if (ps.insulinState == PumpState.EMPTY) { + reservoirView.setTextColor(Color.RED); + reservoirView.setTypeface(null, Typeface.BOLD); + } else { + reservoirView.setTextColor(Color.WHITE); + reservoirView.setTypeface(null, Typeface.NORMAL); } - }); + + // last connection + String minAgo = DateUtil.minAgo(plugin.getPump().lastSuccessfulCmdTime); + long min = (System.currentTimeMillis() - plugin.getPump().lastSuccessfulCmdTime) / 1000 / 60; + if (plugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) { + lastConnectionView.setText(R.string.combo_pump_connected_now); + lastConnectionView.setTextColor(Color.WHITE); + } else if (plugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) { + lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min)); + lastConnectionView.setTextColor(Color.RED); + } else { + lastConnectionView.setText(minAgo); + lastConnectionView.setTextColor(Color.WHITE); + } + + // last bolus + Bolus bolus = plugin.getPump().lastBolus; + if (bolus != null) { + long agoMsc = System.currentTimeMillis() - bolus.timestamp; + double bolusMinAgo = agoMsc / 60d / 1000d; + String unit = MainApp.gs(R.string.insulin_unit_shortname); + String ago; + if ((agoMsc < 60 * 1000)) { + ago = MainApp.gs(R.string.combo_pump_connected_now); + } else if (bolusMinAgo < 60) { + ago = DateUtil.minAgo(bolus.timestamp); + } else { + ago = DateUtil.hourAgo(bolus.timestamp); + } + lastBolusView.setText(MainApp.gs(R.string.combo_last_bolus, bolus.amount, unit, ago)); + } else { + lastBolusView.setText(""); + } + + // base basal rate + baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate())); + + // TBR + String tbrStr = ""; + if (ps.tbrPercent != -1 && ps.tbrPercent != 100) { + long minSinceRead = (System.currentTimeMillis() - plugin.getPump().state.timestamp) / 1000 / 60; + long remaining = ps.tbrRemainingDuration - minSinceRead; + if (remaining >= 0) { + tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining); + } + } + tempBasalText.setText(tbrStr); + + // stats + bolusCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L))); + tbrCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_TBRS_SET, 0L))); + } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index aeb5b0224c..32a17f8a89 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -390,7 +390,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint // ComboFragment updates state fully only after the pump has initialized, // so force an update after initialization completed - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); } /** @@ -406,7 +406,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (result.state.menu != null) { pump.state = result.state; } - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); } @Override @@ -485,7 +485,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint .comment(MainApp.gs(R.string.virtualpump_resultok)); } } finally { - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); } } @@ -493,7 +493,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) { try { pump.activity = MainApp.gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin); - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); // check pump is ready and all pump bolus records are known CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1)); @@ -628,7 +628,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint .carbsDelivered(detailedBolusInfo.carbs); } finally { pump.activity = null; - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); RxBus.INSTANCE.send(new EventRefreshOverview("Bolus")); cancelBolus = false; } @@ -760,7 +760,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint .source(Source.USER); TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStart); - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); } incrementTbrCount(); @@ -848,7 +848,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (!ruffyScripter.isConnected()) { String originalActivity = pump.activity; pump.activity = MainApp.gs(R.string.combo_activity_checking_pump_state); - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); CommandResult preCheckError = runOnConnectChecks(); pump.activity = originalActivity; if (preCheckError != null) { @@ -859,7 +859,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint if (activity != null) { pump.activity = activity; - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); } commandResult = commandExecution.execute(); @@ -892,7 +892,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint } finally { if (activity != null) { pump.activity = null; - MainApp.bus().post(new EventComboPumpUpdateGUI()); + RxBus.INSTANCE.send(new EventComboPumpUpdateGUI()); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java deleted file mode 100644 index 72359b7db2..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.combo.events; - -/** - * Created by mike on 24.05.2017. - */ - -public class EventComboPumpUpdateGUI { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt new file mode 100644 index 0000000000..604b55cd25 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.combo.events + +import info.nightscout.androidaps.events.EventUpdateGui + +class EventComboPumpUpdateGUI : EventUpdateGui() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt index f6eb1c3069..3f58acf4d2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt @@ -8,7 +8,6 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment -import com.squareup.otto.Subscribe import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.TDDStatsActivity @@ -81,7 +80,6 @@ class DanaRFragment : Fragment() { @Synchronized override fun onResume() { super.onResume() - MainApp.bus().register(this) loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) disposable += RxBus .toObservable(EventDanaRNewStatus::class.java) @@ -95,6 +93,10 @@ class DanaRFragment : Fragment() { .toObservable(EventTempBasalChange::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) }) + disposable += RxBus + .toObservable(EventQueueChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) }) disposable += RxBus .toObservable(EventPumpStatusChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) @@ -118,14 +120,9 @@ class DanaRFragment : Fragment() { override fun onPause() { super.onPause() disposable.clear() - MainApp.bus().unregister(this) loopHandler.removeCallbacks(refreshLoop) } - @Subscribe - fun onStatusEvent(s: EventQueueChanged) = - activity?.runOnUiThread { updateGUI() } - // GUI functions @Synchronized internal fun updateGUI() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 9999bed27f..69e0e0bbe8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -8,7 +8,6 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment -import com.squareup.otto.Subscribe import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventExtendedBolusChange @@ -104,7 +103,6 @@ class MedtronicFragment : Fragment() { @Synchronized override fun onResume() { super.onResume() - MainApp.bus().register(this) loopHandler.postDelayed(refreshLoop, T.mins(1).msecs()) disposable += RxBus .toObservable(EventRefreshButtonState::class.java) @@ -143,6 +141,10 @@ class MedtronicFragment : Fragment() { .toObservable(EventPumpStatusChanged::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) }) + disposable += RxBus + .toObservable(EventQueueChanged::class.java) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) }) updateGUI() } @@ -151,15 +153,9 @@ class MedtronicFragment : Fragment() { override fun onPause() { super.onPause() disposable.clear() - MainApp.bus().unregister(this) loopHandler.removeCallbacks(refreshLoop) } - @Subscribe - fun onStatusEvent(s: EventQueueChanged) { - activity?.runOnUiThread { updateGUI() } - } - @Synchronized private fun setDeviceStatus() { val pumpStatus: MedtronicPumpStatus = MedtronicUtil.getPumpStatus() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 76d55d8ebf..1fab545b0c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.treatments; import android.content.Intent; import android.os.IBinder; + import androidx.annotation.Nullable; import com.j256.ormlite.android.apptools.OpenHelperManager; @@ -13,7 +14,6 @@ import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; -import com.squareup.otto.Subscribe; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; @@ -35,7 +35,6 @@ import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNsTreatment; -import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; import info.nightscout.androidaps.logging.L; @@ -191,7 +190,7 @@ public class TreatmentService extends OrmLiteBaseService { if (DatabaseHelper.earliestDataChange != null) { if (L.isEnabled(L.DATATREATMENTS)) log.debug("Firing EventNewHistoryData"); - MainApp.bus().post(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); + RxBus.INSTANCE.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); } DatabaseHelper.earliestDataChange = null; callback.setPost(null); @@ -199,7 +198,7 @@ public class TreatmentService extends OrmLiteBaseService { } // prepare task for execution in 1 sec // cancel waiting task to prevent sending multiple posts - ScheduledFuture scheduledFuture = callback.getPost(); + ScheduledFuture scheduledFuture = callback.getPost(); if (scheduledFuture != null) scheduledFuture.cancel(false); Runnable task = new PostRunnable(); @@ -256,8 +255,7 @@ public class TreatmentService extends OrmLiteBaseService { createOrUpdate(treatment); else createOrUpdateMedtronic(treatment, false); - } - else + } else log.error("Date is null: " + treatment.toString()); } catch (JSONException e) { log.error("Unhandled exception", e); @@ -401,7 +399,7 @@ public class TreatmentService extends OrmLiteBaseService { Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date); - if (existingTreatment==null) { + if (existingTreatment == null) { getDao().create(treatment); if (L.isEnabled(L.DATATREATMENTS)) log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); @@ -410,7 +408,7 @@ public class TreatmentService extends OrmLiteBaseService { return new UpdateReturn(true, true); } else { - if (existingTreatment.date==treatment.date) { + if (existingTreatment.date == treatment.date) { // we will do update only, if entry changed if (!optionalTreatmentCopy(existingTreatment, treatment, fromNightScout)) { return new UpdateReturn(true, false); @@ -483,15 +481,15 @@ public class TreatmentService extends OrmLiteBaseService { int source = Source.NONE; - if (oldTreatment.pumpId==0) { + if (oldTreatment.pumpId == 0) { if (newTreatment.pumpId > 0) { - oldTreatment.pumpId=newTreatment.pumpId; + oldTreatment.pumpId = newTreatment.pumpId; source = Source.PUMP; changed = true; } } - if (source==Source.NONE) { + if (source == Source.NONE) { if (oldTreatment.source == newTreatment.source) { source = oldTreatment.source; @@ -522,7 +520,6 @@ public class TreatmentService extends OrmLiteBaseService { log.debug("treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); - if (fromNightScout) { long pumpId_old = oldTreatment.pumpId; boolean isSMB = (oldTreatment.isSMB || newTreatment.isSMB); @@ -552,7 +549,7 @@ public class TreatmentService extends OrmLiteBaseService { Treatment record = null; - if (pumpId>0) { + if (pumpId > 0) { record = getPumpRecordById(pumpId); @@ -572,7 +569,6 @@ public class TreatmentService extends OrmLiteBaseService { } - /** * Returns the record for the given id, null if none, throws RuntimeException * if multiple records with the same pump id exist. @@ -693,7 +689,7 @@ public class TreatmentService extends OrmLiteBaseService { return new ArrayList<>(); } - public List getTreatmentDataFromTime(long from, long to, boolean ascending) { + public List getTreatmentDataFromTime(long from, long to, boolean ascending) { try { Dao daoTreatments = getDao(); List treatments; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java index abce919233..d45d52c3a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java @@ -232,7 +232,7 @@ public class TreatmentsBolusFragment extends Fragment implements View.OnClickLis builder.setMessage(MainApp.gs(R.string.refresheventsfromnightscout) + "?"); builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> { TreatmentsPlugin.getPlugin().getService().resetTreatments(); - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); }); builder.setNegativeButton(MainApp.gs(R.string.cancel), null); builder.show(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java index 6dcedd7f3e..4810a1ed8c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java @@ -180,7 +180,7 @@ public class TreatmentsCareportalFragment extends Fragment implements View.OnCli builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MainApp.getDbHelper().resetCareportalEvents(); - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); } }); builder.setNegativeButton(MainApp.gs(R.string.cancel), null); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java index 1c338d54bd..9d699726b9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -231,7 +231,7 @@ public class TreatmentsProfileSwitchFragment extends Fragment implements View.On builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MainApp.getDbHelper().resetProfileSwitch(); - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); } }); builder.setNegativeButton(MainApp.gs(R.string.cancel), null); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java index 9aba0a3c9d..ccd1b327c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java @@ -217,7 +217,7 @@ public class TreatmentsTempTargetFragment extends Fragment implements View.OnCli builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { MainApp.getDbHelper().resetTempTargets(); - MainApp.bus().post(new EventNSClientRestart()); + RxBus.INSTANCE.send(new EventNSClientRestart()); } }); builder.setNegativeButton(MainApp.gs(R.string.cancel), null); diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java index 2c6bd0f64c..9676a04196 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -51,7 +51,7 @@ public class QueueThread extends Thread { public final void run() { if (mWakeLock != null) mWakeLock.acquire(T.mins(10).msecs()); - MainApp.bus().post(new EventQueueChanged()); + RxBus.INSTANCE.send(new EventQueueChanged()); long lastCommandTime; long connectionStartTime = lastCommandTime = System.currentTimeMillis(); @@ -145,10 +145,10 @@ public class QueueThread extends Thread { if (queue.performing() != null) { if (L.isEnabled(L.PUMPQUEUE)) log.debug("performing " + queue.performing().status()); - MainApp.bus().post(new EventQueueChanged()); + RxBus.INSTANCE.send(new EventQueueChanged()); queue.performing().execute(); queue.resetPerforming(); - MainApp.bus().post(new EventQueueChanged()); + RxBus.INSTANCE.send(new EventQueueChanged()); lastCommandTime = System.currentTimeMillis(); SystemClock.sleep(100); continue; From c42ef8e5ffc94bfc2127599ecef2da98c7a46fa6 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 15 Oct 2019 13:31:55 +0200 Subject: [PATCH 11/13] Events to RxBus --- app/build.gradle | 2 - .../java/com/squareup/otto/LoggingBus.java | 96 ------- .../nightscout/androidaps/MainActivity.java | 2 - .../info/nightscout/androidaps/MainApp.java | 10 - .../activities/TDDStatsActivity.java | 2 - .../androidaps/interfaces/PluginBase.java | 15 +- .../plugins/aps/loop/LoopPlugin.java | 6 +- .../events/EventNewOpenLoopNotification.java | 9 - .../events/EventNewOpenLoopNotification.kt | 5 + .../plugins/common/SubscriberFragment.java | 22 -- .../configBuilder/ConfigBuilderPlugin.java | 2 - .../general/nsclient/NSClientPlugin.java | 20 +- .../nsclient/NsClientReceiverDelegate.java | 14 +- .../general/nsclient/acks/NSAddAck.java | 3 +- .../general/nsclient/acks/NSAuthAck.java | 7 +- .../general/nsclient/acks/NSUpdateAck.java | 4 +- .../nsclient/services/NSClientService.java | 113 ++++---- .../general/overview/OverviewFragment.java | 250 +++++++++--------- .../SmsCommunicatorFragment.java | 74 +++--- .../SmsCommunicatorPlugin.java | 9 +- .../events/EventSmsCommunicatorUpdateGui.java | 9 - .../events/EventSmsCommunicatorUpdateGui.kt | 5 + .../plugins/profile/ns/NSProfilePlugin.java | 3 - .../plugins/pump/danaR/DanaRPlugin.java | 2 - .../danaR/services/DanaRExecutionService.java | 3 - .../services/DanaRKoreanExecutionService.java | 2 - .../pump/danaRS/services/DanaRSService.java | 6 - .../insight/EventLocalInsightUpdateGUI.java | 6 - .../pump/insight/LocalInsightFragment.java | 38 ++- .../pump/insight/LocalInsightPlugin.java | 5 +- .../events/EventLocalInsightUpdateGUI.kt | 5 + .../dialog/MedtronicHistoryActivity.java | 3 - .../plugins/treatments/TreatmentService.java | 2 - .../plugins/treatments/TreatmentsPlugin.java | 2 - .../fragments/TreatmentsBolusFragment.java | 3 - .../TreatmentsExtendedBolusesFragment.java | 3 - .../TreatmentsProfileSwitchFragment.java | 4 - .../TreatmentsTemporaryBasalsFragment.java | 3 - .../receivers/ChargingStateReceiver.java | 4 +- .../androidaps/services/DataService.java | 11 - .../androidaps/setupwizard/SWDefinition.java | 9 +- .../setupwizard/SetupWizardActivity.java | 24 +- .../setupwizard/elements/SWEditUrl.java | 3 +- .../setupwizard/elements/SWItem.java | 4 +- .../setupwizard/elements/SWPlugin.java | 2 +- .../setupwizard/events/EventSWUpdate.java | 14 - .../setupwizard/events/EventSWUpdate.kt | 5 + app/src/test/java/info/AAPSMocker.java | 36 +-- .../java/info/nightscout/MainAppTest.java | 8 +- .../androidaps/data/ProfileIntervalsTest.java | 5 +- .../androidaps/data/ProfileTest.java | 4 +- .../interfaces/ConstraintsCheckerTest.java | 22 +- .../plugins/aps/loop/APSResultTest.java | 1 - .../plugins/aps/loop/LoopPluginTest.java | 10 - .../ConfigBuilderPluginTest.java | 5 - .../objectives/ObjectivesPluginTest.java | 3 - .../constraints/safety/SafetyPluginTest.java | 1 - .../storage/StorageConstraintPluginTest.java | 9 +- .../actions/ActionLoopDisableTest.java | 1 - .../actions/ActionLoopEnableTest.java | 1 - .../actions/ActionLoopResumeTest.java | 1 - .../actions/ActionLoopSuspendTest.java | 1 - .../actions/ActionNotificationTest.java | 13 - .../ActionProfileSwitchPercentTest.java | 4 +- .../actions/ActionProfileSwitchTest.java | 1 - .../automation/actions/ActionSendSMSTest.java | 1 - .../actions/ActionStartTempTargetTest.java | 1 - .../automation/elements/InputBgTest.java | 1 - .../elements/InputTempTargetTest.java | 1 - .../triggers/TriggerAutosensValueTest.java | 4 +- .../automation/triggers/TriggerBgTest.java | 4 +- .../triggers/TriggerBolusAgoTest.java | 4 +- .../automation/triggers/TriggerCOBTest.java | 8 +- .../automation/triggers/TriggerDeltaTest.java | 4 +- .../automation/triggers/TriggerIobTest.java | 4 +- .../triggers/TriggerLocationTest.java | 4 +- .../triggers/TriggerProfilePercentTest.java | 4 +- .../TriggerPumpLastConnectionTest.java | 4 +- .../triggers/TriggerRecurringTimeTest.java | 5 +- .../triggers/TriggerTempTargetTest.java | 5 +- .../triggers/TriggerTimeRangeTest.java | 5 +- .../automation/triggers/TriggerTimeTest.java | 4 +- .../triggers/TriggerWifiSsidTest.java | 4 +- .../Dialogs/NewNSTreatmentDialogTest.java | 1 - .../NsClientReceiverDelegateTest.java | 4 +- .../SmsCommunicatorPluginTest.java | 1 - .../VersionCheckerUtilsKtTest.kt | 26 +- .../plugins/pump/combo/ComboPluginTest.java | 1 - .../plugins/pump/danaR/DanaRPluginTest.java | 1 - .../pump/danaR/comm/MsgBolusProgressTest.java | 3 +- .../pump/danaR/comm/MsgBolusStopTest.java | 4 +- .../pump/danaR/comm/MsgCheckValueTest.java | 3 +- .../plugins/pump/danaR/comm/MsgErrorTest.java | 3 +- .../pump/danaR/comm/MsgHistoryAllTest.java | 3 +- .../comm/MsgInitConnStatusBolusTest.java | 1 - .../comm/MsgInitConnStatusOptionTest.java | 1 - .../danaR/comm/MsgInitConnStatusTimeTest.java | 3 +- .../danaR/comm/MsgSetBasalProfileTest.java | 1 - .../comm/MsgSetSingleBasalProfileTest.java | 1 - .../pump/danaR/comm/MsgSettingMealTest.java | 1 - .../plugins/pump/danaRS/DanaRSPluginTest.java | 1 - .../DanaRS_Packet_APS_History_EventsTest.java | 1 - ...anaRS_Packet_Basal_Get_Basal_RateTest.java | 1 - ...cket_Basal_Get_Profile_Basal_RateTest.java | 1 - ...aRS_Packet_Bolus_Get_Bolus_OptionTest.java | 1 - ..._Packet_Bolus_Set_Step_Bolus_StopTest.java | 2 +- ...aRS_Packet_General_Get_Pump_CheckTest.java | 1 - ...S_Packet_Notify_Delivery_CompleteTest.java | 1 - ...cket_Notify_Delivery_Rate_DisplayTest.java | 1 - .../pump/danaRv2/DanaRv2PluginTest.java | 1 - .../comm/MessageHashTable_rv2Test.java | 1 - .../danaRv2/comm/MsgCheckValue_v2Test.java | 1 - .../danaRv2/comm/MsgHistoryEvents_v2Test.java | 1 - .../comm/MsgSetHistoryEntry_v2Test.java | 1 - .../comm/MsgStatusTempBasal_v2Test.java | 1 - .../pump/virtual/VirtualPumpPluginUTest.java | 1 - .../androidaps/queue/CommandQueueTest.java | 8 +- 117 files changed, 368 insertions(+), 753 deletions(-) delete mode 100644 app/src/main/java/com/squareup/otto/LoggingBus.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/common/SubscriberFragment.java delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java create mode 100644 app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt delete mode 100644 app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java create mode 100644 app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt diff --git a/app/build.gradle b/app/build.gradle index 9b76b9fbf0..05021d1790 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -240,8 +240,6 @@ dependencies { implementation 'androidx.percentlayout:percentlayout:1.0.0' implementation "com.wdullaer:materialdatetimepicker:2.3.0" - // Otto bus will be replaced by rx - implementation "com.squareup:otto:1.3.7" implementation "io.reactivex.rxjava2:rxandroid:2.1.1" implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}" diff --git a/app/src/main/java/com/squareup/otto/LoggingBus.java b/app/src/main/java/com/squareup/otto/LoggingBus.java deleted file mode 100644 index d9758a9a24..0000000000 --- a/app/src/main/java/com/squareup/otto/LoggingBus.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.squareup.otto; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.logging.L; - -/** - * Logs events has they're being posted to and dispatched from the event bus. - *

- * A summary of event-receiver calls that occurred so far is logged - * after 10s (after startup) and then again every 60s. - */ -public class LoggingBus extends Bus { - private static Logger log = LoggerFactory.getLogger(L.EVENTS); - - private static long everyMinute = System.currentTimeMillis() + 10 * 1000; - private Map> event2Receiver = new HashMap<>(); - - public LoggingBus(ThreadEnforcer enforcer) { - super(enforcer); - } - - @Override - public void post(Object event) { - if (event instanceof DeadEvent) { - log.debug("Event has no receiver: " + ((DeadEvent) event).event + ", source: " + ((DeadEvent) event).source); - return; - } - - if (!(event instanceof Event)) { - log.error("Posted event not an event class: " + event.getClass()); - } - - log.debug("<<< " + event); - try { - StackTraceElement caller = new Throwable().getStackTrace()[1]; - String className = caller.getClassName(); - className = className.substring(className.lastIndexOf(".") + 1); - log.debug(" source: " + className + "." + caller.getMethodName() + ":" + caller.getLineNumber()); - } catch (RuntimeException e) { - log.debug(" source: "); - } - - try { - super.post(event); - } catch (IllegalStateException ignored) { - } - } - - @Override - protected void dispatch(Object event, EventHandler wrapper) { - try { - log.debug(">>> " + event); - Field methodField = wrapper.getClass().getDeclaredField("method"); - methodField.setAccessible(true); - Method targetMethod = (Method) methodField.get(wrapper); - String className = targetMethod.getDeclaringClass().getSimpleName(); - String methodName = targetMethod.getName(); - String receiverMethod = className + "." + methodName; - log.debug(" receiver: " + receiverMethod); - - String key = event.getClass().getSimpleName(); - if (!event2Receiver.containsKey(key)) event2Receiver.put(key, new HashSet()); - event2Receiver.get(key).add(receiverMethod); - } catch (ReflectiveOperationException e) { - log.debug(" receiver: "); - } - - try { - if (everyMinute < System.currentTimeMillis()) { - log.debug("***************** Event -> receiver pairings seen so far ****************"); - for (Map.Entry> stringSetEntry : event2Receiver.entrySet()) { - log.debug(" " + stringSetEntry.getKey()); - for (String s : stringSetEntry.getValue()) { - log.debug(" -> " + s); - } - } - log.debug("*************************************************************************"); - everyMinute = System.currentTimeMillis() + 60 * 1000; - } - } catch (ConcurrentModificationException ignored) { - } - - super.dispatch(event, wrapper); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index f3df901e2e..a1bf2a7bd9 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -143,7 +143,6 @@ public class MainActivity extends NoSplashAppCompatActivity { @Override protected void onResume() { super.onResume(); - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventRefreshGui.class) .observeOn(AndroidSchedulers.mainThread()) @@ -205,7 +204,6 @@ public class MainActivity extends NoSplashAppCompatActivity { @Override public void onPause() { super.onPause(); - MainApp.bus().unregister(this); disposable.clear(); } diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 4137e2e1b1..a1300f59bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -13,9 +13,6 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.crashlytics.android.Crashlytics; import com.google.firebase.analytics.FirebaseAnalytics; import com.j256.ormlite.android.apptools.OpenHelperManager; -import com.squareup.otto.Bus; -import com.squareup.otto.LoggingBus; -import com.squareup.otto.ThreadEnforcer; import net.danlew.android.joda.JodaTimeAndroid; @@ -101,7 +98,6 @@ public class MainApp extends Application { private static Logger log = LoggerFactory.getLogger(L.CORE); private static KeepAliveReceiver keepAliveReceiver; - private static Bus sBus; private static MainApp sInstance; public static Resources sResources; @@ -157,8 +153,6 @@ public class MainApp extends Application { engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile(); devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(".*[a-zA-Z]+.*"); - sBus = L.isEnabled(L.EVENTS) && devBranch ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY); - registerLocalBroadcastReceiver(); //trigger here to see the new version on app start after an update @@ -285,10 +279,6 @@ public class MainApp extends Application { KeepAliveReceiver.cancelAlarm(this); } - public static Bus bus() { - return sBus; - } - public static String gs(int id) { return sResources.getString(id); } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index f8005db5ee..eed8c697e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -77,7 +77,6 @@ public class TDDStatsActivity extends NoSplashActivity { @Override protected void onResume() { super.onResume(); - MainApp.bus().register(this); disposable.add(RxBus.INSTANCE .toObservable(EventPumpStatusChanged.class) .observeOn(AndroidSchedulers.mainThread()) @@ -96,7 +95,6 @@ public class TDDStatsActivity extends NoSplashActivity { @Override protected void onPause() { super.onPause(); - MainApp.bus().unregister(this); disposable.clear(); } diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java index ef83e535f6..5d6d6a9dc9 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java @@ -5,20 +5,19 @@ import android.os.SystemClock; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.FragmentActivity; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventConfigBuilderChange; -import info.nightscout.androidaps.events.EventRefreshGui; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui; -import info.nightscout.androidaps.utils.SP; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.events.EventConfigBuilderChange; +import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment; +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.queue.CommandQueue; +import info.nightscout.androidaps.utils.SP; /** * Created by mike on 09.06.2016. @@ -82,7 +81,7 @@ public abstract class PluginBase { ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, getType()); ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled"); RxBus.INSTANCE.send(new EventRefreshGui()); - MainApp.bus().post(new EventConfigBuilderChange()); + RxBus.INSTANCE.send(new EventConfigBuilderChange()); RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui()); ConfigBuilderPlugin.getPlugin().logPluginStatus(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index e6767a3067..eefeebd0be 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -14,8 +14,6 @@ import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -119,7 +117,6 @@ public class LoopPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); createNotificationChannel(); super.onStart(); disposable.add(RxBus.INSTANCE @@ -169,7 +166,6 @@ public class LoopPlugin extends PluginBase { @Override protected void onStop() { - MainApp.bus().unregister(this); disposable.clear(); super.onStop(); } @@ -441,7 +437,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()); - MainApp.bus().post(new EventNewOpenLoopNotification()); + RxBus.INSTANCE.send(new EventNewOpenLoopNotification()); // Send to Wear ActionStringHandler.handleInitiate("changeRequest"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.java deleted file mode 100644 index 6a0a4dc0cf..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.java +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.plugins.aps.loop.events; - -import info.nightscout.androidaps.events.Event; - -/** - * Created by mike on 07.08.2016. - */ -public class EventNewOpenLoopNotification extends Event { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt new file mode 100644 index 0000000000..2933318dd6 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.aps.loop.events + +import info.nightscout.androidaps.events.Event + +class EventNewOpenLoopNotification : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/common/SubscriberFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/common/SubscriberFragment.java deleted file mode 100644 index 4e6f07671d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/common/SubscriberFragment.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.common; - -import androidx.fragment.app.Fragment; - -import info.nightscout.androidaps.MainApp; - -abstract public class SubscriberFragment extends Fragment { - @Override - public void onPause() { - super.onPause(); - MainApp.bus().unregister(this); - } - - @Override - public void onResume() { - super.onResume(); - MainApp.bus().register(this); - updateGUI(); - } - - protected abstract void updateGUI(); -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index 32ece49d49..f43513fbf5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -68,14 +68,12 @@ public class ConfigBuilderPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); super.onStart(); } @Override protected void onStop() { super.onStop(); - MainApp.bus().unregister(this); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index b265bab54e..ae5d090211 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -10,8 +10,6 @@ import android.os.IBinder; import android.text.Html; import android.text.Spanned; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -91,7 +89,7 @@ public class NSClientPlugin extends PluginBase { } nsClientReceiverDelegate = - new NsClientReceiverDelegate(MainApp.instance().getApplicationContext(), MainApp.bus()); + new NsClientReceiverDelegate(MainApp.instance().getApplicationContext()); } public boolean isAllowed() { @@ -101,7 +99,6 @@ public class NSClientPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); Context context = MainApp.instance().getApplicationContext(); Intent intent = new Intent(context, NSClientService.class); context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); @@ -145,24 +142,21 @@ public class NSClientPlugin extends PluginBase { log.debug(event.getAction() + " " + event.getLogText()); }, FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(EventChargingState.class) + .observeOn(Schedulers.io()) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException) + ); } @Override protected void onStop() { - MainApp.bus().unregister(this); - Context context = MainApp.instance().getApplicationContext(); - context.unbindService(mConnection); - + MainApp.instance().getApplicationContext().unbindService(mConnection); nsClientReceiverDelegate.unregisterReceivers(); disposable.clear(); super.onStop(); } - @Subscribe - public void onStatusEvent(final EventChargingState ev) { - nsClientReceiverDelegate.onStatusEvent(ev); - } - private ServiceConnection mConnection = new ServiceConnection() { public void onServiceDisconnected(ComponentName name) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java index 31bd7305e6..c68750d828 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java @@ -6,14 +6,12 @@ import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; -import com.squareup.otto.Bus; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.events.EventChargingState; import info.nightscout.androidaps.events.EventNetworkChange; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.receivers.ChargingStateReceiver; import info.nightscout.androidaps.receivers.NetworkChangeReceiver; import info.nightscout.androidaps.utils.SP; @@ -21,7 +19,6 @@ import info.nightscout.androidaps.utils.SP; class NsClientReceiverDelegate { private final Context context; - private final Bus bus; private NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver(); private ChargingStateReceiver chargingStateReceiver = new ChargingStateReceiver(); @@ -30,9 +27,8 @@ class NsClientReceiverDelegate { private boolean allowedNetworkState = true; boolean allowed = true; - NsClientReceiverDelegate(Context context, Bus bus) { + NsClientReceiverDelegate(Context context) { this.context = context; - this.bus = bus; } void registerReceivers() { @@ -53,7 +49,7 @@ class NsClientReceiverDelegate { EventChargingState eventChargingState = chargingStateReceiver.grabChargingState(context); if (eventChargingState != null) - bus.post(eventChargingState); + RxBus.INSTANCE.send(eventChargingState); } @@ -66,14 +62,14 @@ class NsClientReceiverDelegate { if (ev.isChanged(R.string.key_ns_wifionly) || ev.isChanged(R.string.key_ns_wifi_ssids) || ev.isChanged(R.string.key_ns_allowroaming) - ) { + ) { EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext()); if (event != null) RxBus.INSTANCE.send(event); } else if (ev.isChanged(R.string.key_ns_chargingonly)) { EventChargingState event = chargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext()); if (event != null) - bus.post(event); + RxBus.INSTANCE.send(event); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java index 18c31c80e6..01d1f26c33 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java @@ -5,7 +5,6 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; @@ -34,7 +33,7 @@ public class NSAddAck extends Event implements Ack { nsClientID = response.getString("NSCLIENT_ID"); } } - MainApp.bus().post(this); + RxBus.INSTANCE.send(this); return; } catch (Exception e) { log.error("Unhandled exception", e); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java index 62c1cf7f5d..754ff6684b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java @@ -2,13 +2,10 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONObject; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.plugins.bus.RxBus; import io.socket.client.Ack; -/** - * Created by mike on 02.01.2016. - */ public class NSAuthAck extends Event implements Ack{ public boolean read = false; public boolean write = false; @@ -19,6 +16,6 @@ public class NSAuthAck extends Event implements Ack{ read = response.optBoolean("read"); write = response.optBoolean("write"); write_treatment = response.optBoolean("write_treatment"); - MainApp.bus().post(this); + RxBus.INSTANCE.send(this); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java index 68ce3d9a37..2a4022980d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java @@ -5,9 +5,9 @@ import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import io.socket.client.Ack; /** @@ -28,7 +28,7 @@ public class NSUpdateAck extends Event implements Ack { result = true; log.debug("Internal error: Missing _id returned on dbUpdate ack"); } - MainApp.bus().post(this); + RxBus.INSTANCE.send(this); } catch (JSONException e) { log.error("Unhandled exception", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index d1f8bbdead..785fb1361b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -13,7 +13,6 @@ import android.os.SystemClock; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import com.j256.ormlite.dao.CloseableIterator; -import com.squareup.otto.Subscribe; import org.json.JSONArray; import org.json.JSONException; @@ -116,7 +115,6 @@ public class NSClientService extends Service { private int WATCHDOG_MAXCONNECTIONS = 5; public NSClientService() { - registerBus(); if (handler == null) { HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler"); handlerThread.start(); @@ -175,6 +173,21 @@ public class NSClientService extends Service { restart(); }, FabricPrivacy::logException) ); + disposable.add(RxBus.INSTANCE + .toObservable(NSAuthAck.class) + .observeOn(Schedulers.io()) + .subscribe(event -> processAuthAck(event), FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(NSUpdateAck.class) + .observeOn(Schedulers.io()) + .subscribe(event -> processUpdateAck(event), FabricPrivacy::logException) + ); + disposable.add(RxBus.INSTANCE + .toObservable(NSAddAck.class) + .observeOn(Schedulers.io()) + .subscribe(event -> processAddAck(event), FabricPrivacy::logException) + ); } @Override @@ -184,6 +197,48 @@ public class NSClientService extends Service { if (mWakeLock.isHeld()) mWakeLock.release(); } + public void processAddAck(NSAddAck ack) { + if (ack.nsClientID != null) { + uploadQueue.removeID(ack.json); + RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); + } else { + RxBus.INSTANCE.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)); + } else { + RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); + } + } + + public void processAuthAck(NSAuthAck ack) { + String connectionStatus = "Authenticated ("; + if (ack.read) connectionStatus += "R"; + if (ack.write) connectionStatus += "W"; + if (ack.write_treatment) connectionStatus += "T"; + connectionStatus += ')'; + isConnected = true; + hasWriteAuth = ack.write && ack.write_treatment; + RxBus.INSTANCE.send(new EventNSClientStatus(connectionStatus)); + RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", connectionStatus)); + if (!ack.write) { + RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); + } + if (!ack.write_treatment) { + RxBus.INSTANCE.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)); + } else { + RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)); + } + } + public class LocalBinder extends Binder { public NSClientService getServiceInstance() { return NSClientService.this; @@ -201,15 +256,6 @@ public class NSClientService extends Service { return START_STICKY; } - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); - } - public void initialize() { dataCounter = 0; @@ -339,31 +385,6 @@ public class NSClientService extends Service { mSocket.emit("authorize", authMessage, ack); } - @Subscribe - public void onStatusEvent(NSAuthAck ack) { - String connectionStatus = "Authenticated ("; - if (ack.read) connectionStatus += "R"; - if (ack.write) connectionStatus += "W"; - if (ack.write_treatment) connectionStatus += "T"; - connectionStatus += ')'; - isConnected = true; - hasWriteAuth = ack.write && ack.write_treatment; - RxBus.INSTANCE.send(new EventNSClientStatus(connectionStatus)); - RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", connectionStatus)); - if (!ack.write) { - RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!")); - } - if (!ack.write_treatment) { - RxBus.INSTANCE.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)); - } else { - RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION)); - } - } - public void readPreferences() { nsEnabled = MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL); nsURL = SP.getString(R.string.key_nsclientinternal_url, ""); @@ -756,16 +777,6 @@ public class NSClientService extends Service { } } - @Subscribe - public void onStatusEvent(NSUpdateAck ack) { - if (ack.result) { - uploadQueue.removeID(ack.action, ack._id); - RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id)); - } else { - RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response")); - } - } - public void dbAdd(DbRequest dbr, NSAddAck ack) { try { if (!isConnected || !hasWriteAuth) return; @@ -785,16 +796,6 @@ public class NSClientService extends Service { RxBus.INSTANCE.send(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime)); } - @Subscribe - public void onStatusEvent(NSAddAck ack) { - if (ack.nsClientID != null) { - uploadQueue.removeID(ack.json); - RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID)); - } else { - RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBADD Unknown response")); - } - } - public void resend(final String reason) { if (UploadQueue.size() == 0) return; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java index 6681f53f40..bcb8a61ddd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.overview; import android.annotation.SuppressLint; import android.app.Activity; import android.app.NotificationManager; - import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; @@ -12,16 +11,6 @@ import android.graphics.Color; import android.graphics.Paint; import android.os.Bundle; import android.os.Handler; - -import androidx.fragment.app.Fragment; -import androidx.fragment.app.FragmentActivity; -import androidx.fragment.app.FragmentManager; -import androidx.core.content.res.ResourcesCompat; -import androidx.appcompat.app.AlertDialog; -import androidx.recyclerview.widget.LinearLayoutManager; -import androidx.appcompat.widget.PopupMenu; -import androidx.recyclerview.widget.RecyclerView; - import android.text.SpannableString; import android.text.style.ForegroundColorSpan; import android.util.DisplayMetrics; @@ -36,8 +25,16 @@ import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; +import androidx.appcompat.app.AlertDialog; +import androidx.appcompat.widget.PopupMenu; +import androidx.core.content.res.ResourcesCompat; +import androidx.fragment.app.Fragment; +import androidx.fragment.app.FragmentActivity; +import androidx.fragment.app.FragmentManager; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + import com.jjoe64.graphview.GraphView; -import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -83,11 +80,9 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; -import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui; import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment; import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog; import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; @@ -125,7 +120,6 @@ import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.ToastUtils; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.utils.DateUtil.now; @@ -349,6 +343,117 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, return view; } + @Override + public void onPause() { + super.onPause(); + disposable.clear(); + sLoopHandler.removeCallbacksAndMessages(null); + unregisterForContextMenu(apsModeView); + unregisterForContextMenu(activeProfileView); + unregisterForContextMenu(tempTargetView); + } + + @Override + public void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventRefreshOverview.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(eventOpenAPSUpdateGui -> scheduleUpdateGUI(eventOpenAPSUpdateGui.getFrom()), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventExtendedBolusChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventExtendedBolusChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempBasalChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventTempBasalChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTreatmentChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventTreatmentChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventTempTargetChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventTempTargetChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAcceptOpenLoopChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventAcceptOpenLoopChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventCareportalEventChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventCareportalEventChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventInitializationChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventInitializationChanged"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventAutosensCalculationFinished.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventAutosensCalculationFinished"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileNeedsUpdate.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventProfileNeedsUpdate"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPreferenceChange.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventPreferenceChange"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventNewOpenLoopNotification.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> scheduleUpdateGUI("EventNewOpenLoopNotification"), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventPumpStatusChanged.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updatePumpStatus(event.getStatus()), + FabricPrivacy::logException + )); + disposable.add(RxBus.INSTANCE + .toObservable(EventIobCalculationProgress.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (iobCalculationProgressView != null) + iobCalculationProgressView.setText(event.getProgress()); + }, + FabricPrivacy::logException + )); + sRefreshLoop = () -> { + scheduleUpdateGUI("refreshLoop"); + sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); + }; + sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); + registerForContextMenu(apsModeView); + registerForContextMenu(activeProfileView); + registerForContextMenu(tempTargetView); + updateGUI("onResume"); + } + private void setupChartMenu(View view) { chartButton = (ImageButton) view.findViewById(R.id.overview_chartMenuButton); chartButton.setOnClickListener(v -> { @@ -548,8 +653,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } - private void showSuspendtPump(ContextMenu menu, - PumpDescription pumpDescription) { + private void showSuspendtPump(ContextMenu menu, PumpDescription pumpDescription) { if (pumpDescription.tempDurationStep15mAllowed) menu.add(MainApp.gs(R.string.disconnectpumpfor15m)); if (pumpDescription.tempDurationStep30mAllowed) @@ -855,118 +959,6 @@ public class OverviewFragment extends Fragment implements View.OnClickListener, } } - @Override - public void onPause() { - super.onPause(); - MainApp.bus().unregister(this); - disposable.clear(); - sLoopHandler.removeCallbacksAndMessages(null); - unregisterForContextMenu(apsModeView); - unregisterForContextMenu(activeProfileView); - unregisterForContextMenu(tempTargetView); - } - - @Override - public void onResume() { - super.onResume(); - MainApp.bus().register(this); - disposable.add(RxBus.INSTANCE - .toObservable(EventRefreshOverview.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(eventOpenAPSUpdateGui -> scheduleUpdateGUI(eventOpenAPSUpdateGui.getFrom()), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventExtendedBolusChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventExtendedBolusChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventTempBasalChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventTempBasalChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventTreatmentChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventTreatmentChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventTempTargetChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventTempTargetChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventAcceptOpenLoopChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventAcceptOpenLoopChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventCareportalEventChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventCareportalEventChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventInitializationChanged.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventInitializationChanged"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventAutosensCalculationFinished.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventAutosensCalculationFinished"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventProfileNeedsUpdate.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventProfileNeedsUpdate"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventPreferenceChange.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> scheduleUpdateGUI("EventPreferenceChange"), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventPumpStatusChanged.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> updatePumpStatus(event.getStatus()), - FabricPrivacy::logException - )); - disposable.add(RxBus.INSTANCE - .toObservable(EventIobCalculationProgress.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> { - if (iobCalculationProgressView != null) - iobCalculationProgressView.setText(event.getProgress()); - }, - FabricPrivacy::logException - )); - sRefreshLoop = () -> { - scheduleUpdateGUI("refreshLoop"); - sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); - }; - sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); - registerForContextMenu(apsModeView); - registerForContextMenu(activeProfileView); - registerForContextMenu(tempTargetView); - updateGUI("onResume"); - } - - @Subscribe - public void onStatusEvent(final EventNewOpenLoopNotification ev) { - scheduleUpdateGUI("EventNewOpenLoopNotification"); - } - private void hideTempRecommendation() { Activity activity = getActivity(); if (activity != null) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java index d1c4adf5fe..31f335a7cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.smsCommunicator; -import android.app.Activity; import android.os.Bundle; import android.text.Html; import android.view.LayoutInflater; @@ -9,17 +8,21 @@ import android.view.View; import android.view.ViewGroup; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.fragment.app.Fragment; import java.util.Collections; import java.util.Comparator; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; -public class SmsCommunicatorFragment extends SubscriberFragment { +public class SmsCommunicatorFragment extends Fragment { + private CompositeDisposable disposable = new CompositeDisposable(); TextView logView; public SmsCommunicatorFragment() { @@ -36,38 +39,45 @@ public class SmsCommunicatorFragment extends SubscriberFragment { return view; } - @Subscribe - public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) { - updateGUI(); + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventSmsCommunicatorUpdateGui.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGui(), FabricPrivacy::logException) + ); + updateGui(); } @Override - protected void updateGUI() { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(() -> { - class CustomComparator implements Comparator { - public int compare(Sms object1, Sms object2) { - return (int) (object1.date - object2.date); - } - } - Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator()); - int messagesToShow = 40; + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } - int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow); + protected void updateGui() { + class CustomComparator implements Comparator { + public int compare(Sms object1, Sms object2) { + return (int) (object1.date - object2.date); + } + } + Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator()); + int messagesToShow = 40; - String logText = ""; - for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) { - Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x); - if (sms.ignored) { - logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + "
"; - } else if (sms.received) { - logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; - } else if (sms.sent) { - logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; - } - } - logView.setText(Html.fromHtml(logText)); - }); + int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow); + + String logText = ""; + for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) { + Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x); + if (sms.ignored) { + logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + "
"; + } else if (sms.received) { + logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; + } else if (sms.sent) { + logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
"; + } + } + logView.setText(Html.fromHtml(logText)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java index 5b334e2812..b10a0b5ed0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java @@ -5,8 +5,6 @@ import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; -import com.squareup.otto.Subscribe; - import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,7 +23,6 @@ import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.Source; -import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.Constraint; @@ -176,7 +173,7 @@ public class SmsCommunicatorPlugin extends PluginBase { log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed"); receivedSms.ignored = true; messages.add(receivedSms); - MainApp.bus().post(new EventSmsCommunicatorUpdateGui()); + RxBus.INSTANCE.send(new EventSmsCommunicatorUpdateGui()); return; } @@ -268,7 +265,7 @@ public class SmsCommunicatorPlugin extends PluginBase { } } - MainApp.bus().post(new EventSmsCommunicatorUpdateGui()); + RxBus.INSTANCE.send(new EventSmsCommunicatorUpdateGui()); } @SuppressWarnings("unused") @@ -794,7 +791,7 @@ public class SmsCommunicatorPlugin extends PluginBase { RxBus.INSTANCE.send(new EventNewNotification(notification)); return false; } - MainApp.bus().post(new EventSmsCommunicatorUpdateGui()); + RxBus.INSTANCE.send(new EventSmsCommunicatorUpdateGui()); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java deleted file mode 100644 index 7e50671c45..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.plugins.general.smsCommunicator.events; - -import info.nightscout.androidaps.events.EventUpdateGui; - -/** - * Created by mike on 05.08.2016. - */ -public class EventSmsCommunicatorUpdateGui extends EventUpdateGui { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt new file mode 100644 index 0000000000..4a0f95b244 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.general.smsCommunicator.events + +import info.nightscout.androidaps.events.EventUpdateGui + +class EventSmsCommunicatorUpdateGui : EventUpdateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java index 13cb2dc545..38afe62bdf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java @@ -12,7 +12,6 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.events.EventProfileStoreChanged; @@ -58,13 +57,11 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface { @Override protected void onStart() { - MainApp.bus().register(this); super.onStart(); } @Override protected void onStop() { - MainApp.bus().unregister(this); super.onStop(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index 402f2f0ea7..e9293b39a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -6,8 +6,6 @@ import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index cc458eb3f8..0801d8a173 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -5,8 +5,6 @@ import android.content.IntentFilter; import android.os.Binder; import android.os.SystemClock; -import com.squareup.otto.Subscribe; - import java.io.IOException; import java.util.Date; @@ -69,7 +67,6 @@ import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; -import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index dd2547c6eb..bb1f226730 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -5,8 +5,6 @@ import android.content.IntentFilter; import android.os.Binder; import android.os.SystemClock; -import com.squareup.otto.Subscribe; - import java.io.IOException; import java.util.Date; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java index 50dd9fef1b..e7696836ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -99,12 +99,6 @@ public class DanaRSService extends Service { private long lastApproachingDailyLimit = 0; public DanaRSService() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java deleted file mode 100644 index 89b001891c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java +++ /dev/null @@ -1,6 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.insight; - -import info.nightscout.androidaps.events.EventUpdateGui; - -public class EventLocalInsightUpdateGUI extends EventUpdateGui { -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index b973424d71..3464a1803a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.pump.insight; import android.os.Bundle; import android.os.Handler; import android.os.Looper; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -12,14 +10,16 @@ import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; -import com.squareup.otto.Subscribe; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock; import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate; @@ -28,11 +28,16 @@ import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveTBR; import info.nightscout.androidaps.plugins.pump.insight.descriptors.CartridgeStatus; import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState; import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose; +import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.FabricPrivacy; +import io.reactivex.android.schedulers.AndroidSchedulers; +import io.reactivex.disposables.CompositeDisposable; -public class LocalInsightFragment extends SubscriberFragment implements View.OnClickListener { +public class LocalInsightFragment extends Fragment implements View.OnClickListener { + private CompositeDisposable disposable = new CompositeDisposable(); private static final boolean ENABLE_OPERATING_MODE_BUTTON = false; @@ -61,6 +66,23 @@ public class LocalInsightFragment extends SubscriberFragment implements View.OnC return view; } + @Override + public synchronized void onResume() { + super.onResume(); + disposable.add(RxBus.INSTANCE + .toObservable(EventLocalInsightUpdateGUI.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> updateGUI(), FabricPrivacy::logException) + ); + updateGUI(); + } + + @Override + public synchronized void onPause() { + super.onPause(); + disposable.clear(); + } + @Override public synchronized void onDestroyView() { super.onDestroyView(); @@ -121,12 +143,6 @@ public class LocalInsightFragment extends SubscriberFragment implements View.OnC } } - @Subscribe - public void onUpdateGUIEvent(EventLocalInsightUpdateGUI event) { - updateGUI(); - } - - @Override protected void updateGUI() { if (!viewsCreated) return; statusItemContainer.removeAllViews(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index de857b77ba..bdb0c20624 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -118,6 +118,7 @@ import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState; import info.nightscout.androidaps.plugins.pump.insight.descriptors.OperatingMode; import info.nightscout.androidaps.plugins.pump.insight.descriptors.PumpTime; import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose; +import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI; import info.nightscout.androidaps.plugins.pump.insight.exceptions.InsightException; import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.AppLayerErrorException; import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException; @@ -424,7 +425,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con } lastUpdated = System.currentTimeMillis(); new Handler(Looper.getMainLooper()).post(() -> { - MainApp.bus().post(new EventLocalInsightUpdateGUI()); + RxBus.INSTANCE.send(new EventLocalInsightUpdateGUI()); RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::fetchStatus")); }); } @@ -1602,7 +1603,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con tbrOverNotificationBlock = null; new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::onStateChanged"))); } - new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventLocalInsightUpdateGUI())); + new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventLocalInsightUpdateGUI())); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt new file mode 100644 index 0000000000..d89515fe56 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.insight.events + +import info.nightscout.androidaps.events.EventUpdateGui + +class EventLocalInsightUpdateGUI : EventUpdateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java index 9f148ac02e..2d1a3a871e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java @@ -19,7 +19,6 @@ import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.NoSplashActivity; import info.nightscout.androidaps.logging.L; @@ -82,7 +81,6 @@ public class MedtronicHistoryActivity extends NoSplashActivity { @Override protected void onResume() { super.onResume(); - MainApp.bus().register(this); filterHistory(selectedGroup); setHistoryTypeSpinner(); } @@ -106,7 +104,6 @@ public class MedtronicHistoryActivity extends NoSplashActivity { @Override protected void onPause() { super.onPause(); - MainApp.bus().unregister(this); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 1fab545b0c..0af516678a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -29,7 +29,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.Source; @@ -185,7 +184,6 @@ public class TreatmentService extends OrmLiteBaseService { public void run() { if (L.isEnabled(L.DATATREATMENTS)) log.debug("Firing EventReloadTreatmentData"); - MainApp.bus().post(event); RxBus.INSTANCE.send(event); if (DatabaseHelper.earliestDataChange != null) { if (L.isEnabled(L.DATATREATMENTS)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index faa32b0638..881d14b9cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -102,7 +102,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override protected void onStart() { - MainApp.bus().register(this); initializeTempBasalData(); initializeTreatmentData(); initializeExtendedBolusData(); @@ -149,7 +148,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override protected void onStop() { - MainApp.bus().register(this); disposable.clear(); super.onStop(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java index d45d52c3a0..ee78c6748b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.treatments.fragments; -import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; @@ -19,8 +18,6 @@ import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import java.util.List; import info.nightscout.androidaps.MainApp; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java index 297146d999..5ce7b57564 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.treatments.fragments; -import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; @@ -17,8 +16,6 @@ import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Intervals; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java index 9d699726b9..2d06b2824f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.treatments.fragments; -import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.graphics.Paint; @@ -19,8 +18,6 @@ import androidx.fragment.app.FragmentManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,7 +31,6 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.common.SubscriberFragment; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java index 35fb692c64..45f930410e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.treatments.fragments; -import android.app.Activity; import android.content.Context; import android.graphics.Paint; import android.os.Bundle; @@ -17,8 +16,6 @@ import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; -import com.squareup.otto.Subscribe; - import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Intervals; diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java index d325ee9506..9af15e9ddc 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java @@ -5,8 +5,8 @@ import android.content.Context; import android.content.Intent; import android.os.BatteryManager; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.events.EventChargingState; +import info.nightscout.androidaps.plugins.bus.RxBus; public class ChargingStateReceiver extends BroadcastReceiver { @@ -17,7 +17,7 @@ public class ChargingStateReceiver extends BroadcastReceiver { EventChargingState event = grabChargingState(context); if (event != null) - MainApp.bus().post(event); + RxBus.INSTANCE.send(event); lastEvent = event; } diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java index 6a4dfe12ff..80a42e145a 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -45,7 +45,6 @@ public class DataService extends IntentService { public DataService() { super("DataService"); - registerBus(); } @Override @@ -115,16 +114,6 @@ public class DataService extends IntentService { @Override public void onDestroy() { super.onDestroy(); - MainApp.bus().unregister(this); - } - - private void registerBus() { - try { - MainApp.bus().unregister(this); - } catch (RuntimeException x) { - // Ignore - } - MainApp.bus().register(this); } private void handleNewDataFromNSClient(Intent intent) { diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java index 718e21b099..a8b09e7428 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java @@ -5,8 +5,6 @@ import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; -import com.squareup.otto.Subscribe; - import java.util.ArrayList; import java.util.List; @@ -46,7 +44,6 @@ import info.nightscout.androidaps.setupwizard.elements.SWHtmlLink; import info.nightscout.androidaps.setupwizard.elements.SWInfotext; import info.nightscout.androidaps.setupwizard.elements.SWPlugin; import info.nightscout.androidaps.setupwizard.elements.SWRadioButton; -import info.nightscout.androidaps.setupwizard.events.EventSWLabel; import info.nightscout.androidaps.setupwizard.events.EventSWUpdate; import info.nightscout.androidaps.utils.AndroidPermission; import info.nightscout.androidaps.utils.LocaleHelper; @@ -109,7 +106,7 @@ public class SWDefinition { .visibility(() -> !SP.getBoolean(R.string.key_i_understand, false)) .action(() -> { SP.putBoolean(R.string.key_i_understand, true); - MainApp.bus().post(new EventSWUpdate(false)); + RxBus.INSTANCE.send(new EventSWUpdate(false)); })) .visibility(() -> !SP.getBoolean(R.string.key_i_understand, false)) .validator(() -> SP.getBoolean(R.string.key_i_understand, false)); @@ -172,7 +169,7 @@ public class SWDefinition { ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(NSClientPlugin.getPlugin(), PluginType.GENERAL); ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard"); RxBus.INSTANCE.send(new EventConfigBuilderChange()); - MainApp.bus().post(new EventSWUpdate(true)); + RxBus.INSTANCE.send(new EventSWUpdate(true)); }) .visibility(() -> !NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL))) .add(new SWEditUrl() @@ -374,7 +371,7 @@ public class SWDefinition { ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(LoopPlugin.getPlugin(), PluginType.LOOP); ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard"); RxBus.INSTANCE.send(new EventConfigBuilderChange()); - MainApp.bus().post(new EventSWUpdate(true)); + RxBus.INSTANCE.send(new EventSWUpdate(true)); }) .visibility(() -> !LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) .validator(() -> LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)) diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java index cb68ce51a2..721978b291 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java @@ -12,8 +12,6 @@ import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,7 +74,8 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { @Override public void onBackPressed() { - if (currentWizardPage == 0) OKDialog.showConfirmation(this, MainApp.gs(R.string.exitwizard), this::finish); + if (currentWizardPage == 0) + OKDialog.showConfirmation(this, MainApp.gs(R.string.exitwizard), this::finish); else showPreviousPage(null); } @@ -88,14 +87,12 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { @Override public void onPause() { super.onPause(); - MainApp.bus().unregister(this); disposable.clear(); } @Override protected void onResume() { super.onResume(); - MainApp.bus().register(this); swDefinition.setActivity(this); disposable.add(RxBus.INSTANCE .toObservable(EventPumpStatusChanged.class) @@ -117,13 +114,14 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> updateButtons(), FabricPrivacy::logException) ); - } - - @Subscribe - public void onContentUpdate(EventSWUpdate ev) { - if (ev.redraw) - generateLayout(); - updateButtons(); + disposable.add(RxBus.INSTANCE + .toObservable(EventSWUpdate.class) + .observeOn(AndroidSchedulers.mainThread()) + .subscribe(event -> { + if (event.getRedraw()) generateLayout(); + updateButtons(); + }, FabricPrivacy::logException) + ); } private void generateLayout() { @@ -133,7 +131,7 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity { SWItem currentItem = currentScreen.items.get(i); currentItem.generateDialog(layout); } - scrollView.smoothScrollTo(0,0); + scrollView.smoothScrollTo(0, 0); } private void updateButtons() { diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java index 7e6ead7d72..f35decbf53 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java @@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.setupwizard.events.EventSWLabel; import info.nightscout.androidaps.utils.SP; @@ -62,7 +63,7 @@ public class SWEditUrl extends SWItem { if (Patterns.WEB_URL.matcher(s).matches()) save(s.toString(), updateDelay); else - MainApp.bus().post(new EventSWLabel(MainApp.gs(R.string.error_url_not_valid))); + RxBus.INSTANCE.send(new EventSWLabel(MainApp.gs(R.string.error_url_not_valid))); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java index 33e8e5ca85..6931344acf 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java @@ -12,9 +12,9 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.setupwizard.events.EventSWUpdate; import info.nightscout.androidaps.utils.SP; @@ -99,7 +99,7 @@ public class SWItem { if (L.isEnabled(L.CORE)) log.debug("Firing EventPreferenceChange"); RxBus.INSTANCE.send(new EventPreferenceChange(preferenceId)); - MainApp.bus().post(new EventSWUpdate()); + RxBus.INSTANCE.send(new EventSWUpdate(false)); scheduledEventPost = null; } } diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java index e09cbb6e17..e5dde501bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java @@ -89,7 +89,7 @@ public class SWPlugin extends SWItem { ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(plugin, pType); ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard"); RxBus.INSTANCE.send(new EventConfigBuilderChange()); - MainApp.bus().post(new EventSWUpdate()); + RxBus.INSTANCE.send(new EventSWUpdate(false)); }); layout.addView(radioGroup); super.generateDialog(layout); diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java deleted file mode 100644 index 181960ac40..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.setupwizard.events; - -import info.nightscout.androidaps.events.Event; - -public class EventSWUpdate extends Event { - public boolean redraw = false; - - public EventSWUpdate() { - } - - public EventSWUpdate(boolean redraw) { - this.redraw = redraw; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt new file mode 100644 index 0000000000..3c700cda41 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.setupwizard.events + +import info.nightscout.androidaps.events.Event + +class EventSWUpdate(var redraw: Boolean) : Event() \ No newline at end of file diff --git a/app/src/test/java/info/AAPSMocker.java b/app/src/test/java/info/AAPSMocker.java index 4847e3be4a..304c84ea45 100644 --- a/app/src/test/java/info/AAPSMocker.java +++ b/app/src/test/java/info/AAPSMocker.java @@ -5,8 +5,6 @@ import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Resources; -import com.squareup.otto.Bus; - import org.json.JSONException; import org.json.JSONObject; import org.junit.Assert; @@ -52,8 +50,6 @@ public class AAPSMocker { private static ProfileStore profileStore; public static final String TESTPROFILENAME = "someProfile"; - public static Intent intentSent = null; - public static CommandQueue queue; public static ConfigBuilderPlugin configBuilderPlugin; public static ProfileFunctions profileFunctions; @@ -157,6 +153,7 @@ public class AAPSMocker { when(MainApp.gs(R.string.suspendloop)).thenReturn("Suspend loop"); when(MainApp.gs(R.string.pumpNotInitialized)).thenReturn("Pump not initialized!"); when(MainApp.gs(R.string.increasingmaxbasal)).thenReturn("Increasing max basal value because setting is lower than your max basal in profile"); + when(MainApp.gs(R.string.overview_bolusprogress_delivered)).thenReturn("Delivered"); } public static MainApp mockMainApp() { @@ -180,11 +177,6 @@ public class AAPSMocker { return constraintChecker; } - public static void mockBus() { - Bus bus = PowerMockito.mock(Bus.class); - when(MainApp.bus()).thenReturn(bus); - } - public static void mockSP() { PowerMockito.mockStatic(SP.class); when(SP.getLong(anyInt(), anyLong())).thenReturn(0L); @@ -299,30 +291,4 @@ public class AAPSMocker { return iobCobCalculatorPlugin; } - private static MockedBus bus = new MockedBus(); - - public static void prepareMockedBus() { - when(MainApp.bus()).thenReturn(bus); - } - - public static class MockedBus extends Bus { - public boolean registered = false; - public boolean notificationSent = false; - - @Override - public void register(Object event) { - registered = true; - } - - @Override - public void unregister(Object event) { - registered = false; - } - - @Override - public void post(Object event) { - notificationSent = true; - } - } - } diff --git a/app/src/test/java/info/nightscout/MainAppTest.java b/app/src/test/java/info/nightscout/MainAppTest.java index 3120236b59..feecaae779 100644 --- a/app/src/test/java/info/nightscout/MainAppTest.java +++ b/app/src/test/java/info/nightscout/MainAppTest.java @@ -20,13 +20,9 @@ import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; @RunWith(RobolectricTestRunner.class) public class MainAppTest { + /* MainApp mainApp = new MainApp(); - @Test - public void busTest() { - Assert.assertNotNull(mainApp.bus()); - } - @Test public void gsTest() { Assert.assertNotNull(mainApp.gs(R.string.app_name)); @@ -125,5 +121,5 @@ public class MainAppTest { // logger not initialized in Roboelectric Assert.assertNull(LoggerUtils.getLogDirectory()); } - +*/ } diff --git a/app/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.java b/app/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.java index 71cf0a9720..121af322f7 100644 --- a/app/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.java +++ b/app/src/test/java/info/nightscout/androidaps/data/ProfileIntervalsTest.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.data; -import com.squareup.otto.Bus; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -26,7 +24,7 @@ import info.nightscout.androidaps.utils.T; */ @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ConfigBuilderPlugin.class, TreatmentsPlugin.class, TreatmentService.class}) +@PrepareForTest({MainApp.class, ConfigBuilderPlugin.class, TreatmentsPlugin.class, TreatmentService.class}) public class ProfileIntervalsTest { private final long startDate = DateUtil.now(); ProfileIntervals list = new ProfileIntervals<>(); @@ -91,7 +89,6 @@ public class ProfileIntervalsTest { public void prepareMock() { AAPSMocker.mockMainApp(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockTreatmentPlugin(); } diff --git a/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java b/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java index 2e98640325..08f0aab20c 100644 --- a/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java +++ b/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java @@ -22,7 +22,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.utils.FabricPrivacy; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** @@ -134,7 +133,7 @@ public class ProfileTest { // Test hour alignment ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().is30minBasalRatesCapable = false; - ((AAPSMocker.MockedBus) MainApp.bus()).notificationSent = false; + //((AAPSMocker.MockedBus) MainApp.bus()).notificationSent = false; p = new Profile(new JSONObject(notAllignedBasalValidProfile), 100, 0); p.isValid("Test"); //Assert.assertEquals(true, ((AAPSMocker.MockedBus) MainApp.bus()).notificationSent); @@ -145,7 +144,6 @@ public class ProfileTest { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockStrings(); - AAPSMocker.prepareMockedBus(); when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump); diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java index 52de2d12c5..f3577e35c8 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java @@ -2,11 +2,8 @@ package info.nightscout.androidaps.interfaces; import android.content.Context; -import com.squareup.otto.Bus; - import junit.framework.Assert; -import org.json.JSONException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -20,12 +17,12 @@ import info.AAPSMocker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; -import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin; +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; +import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; +import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin; import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; @@ -73,7 +70,7 @@ public class ConstraintsCheckerTest { } @Test - public void isClosedLoopAllowedTest() { + public void isClosedLoopAllowedTest() { when(SP.getString(R.string.key_aps_mode, "open")).thenReturn("closed"); objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getMAXIOB_ZERO_CL_OBJECTIVE()).setStartedOn(0); @@ -247,7 +244,7 @@ public class ConstraintsCheckerTest { // Apply all limits Constraint d = constraintChecker.getMaxIOBAllowed(); Assert.assertEquals(1.5d, d.value()); - Assert.assertEquals(d.getReasonList().toString(),2, d.getReasonList().size()); + Assert.assertEquals(d.getReasonList().toString(), 2, d.getReasonList().size()); Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons()); } @@ -278,7 +275,6 @@ public class ConstraintsCheckerTest { AAPSMocker.mockConfigBuilder(); AAPSMocker.mockConstraintsChecker(); AAPSMocker.mockApplicationContext(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockSP(); AAPSMocker.mockCommandQueue(); @@ -311,12 +307,4 @@ public class ConstraintsCheckerTest { when(mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class)).thenReturn(constraintsPluginsList); } - - class MockedBus extends Bus { - @Override - public void post(Object event) { - notificationSent = true; - } - } - } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java index 0041f6f33a..1db142af2c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java @@ -179,7 +179,6 @@ public class APSResultTest { AAPSMocker.mockConfigBuilder(); AAPSMocker.mockSP(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockProfileFunctions(); AAPSMocker.mockTreatmentService(); AAPSMocker.mockL(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java index 49a68cea4f..ecbc9d55c3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java @@ -2,8 +2,6 @@ package info.nightscout.androidaps.plugins.aps.loop; import android.content.Context; -import com.squareup.otto.Bus; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -31,7 +29,6 @@ public class LoopPluginTest { VirtualPumpPlugin virtualPumpPlugin; LoopPlugin loopPlugin; - MockedBus bus; @Test public void testPluginInterface() { @@ -91,17 +88,10 @@ public class LoopPluginTest { AAPSMocker.mockSP(); AAPSMocker.mockStrings(); - bus = new MockedBus(); - when(MainApp.bus()).thenReturn(bus); - loopPlugin = LoopPlugin.getPlugin(); virtualPumpPlugin = VirtualPumpPlugin.getPlugin(); when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(virtualPumpPlugin); } - class MockedBus extends Bus { - } - - } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java index f54105d994..39c5f3279e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java @@ -13,8 +13,6 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.utils.SP; -import static org.powermock.api.mockito.PowerMockito.mock; - @RunWith(PowerMockRunner.class) @PrepareForTest({MainApp.class, SP.class}) public class ConfigBuilderPluginTest { @@ -29,7 +27,6 @@ public class ConfigBuilderPluginTest { public void onStartTest() { ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin(); configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, true); - Assert.assertEquals(true, ((AAPSMocker.MockedBus) MainApp.bus()).registered); } @Test @@ -37,7 +34,6 @@ public class ConfigBuilderPluginTest { ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin(); configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, true); configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, false); - Assert.assertEquals(false, ((AAPSMocker.MockedBus) MainApp.bus()).registered); } @Before @@ -45,7 +41,6 @@ public class ConfigBuilderPluginTest { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); - AAPSMocker.prepareMockedBus(); } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java index 7c9514629d..371e970d23 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java @@ -8,8 +8,6 @@ import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.util.Date; - import info.AAPSMocker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.interfaces.Constraint; @@ -82,7 +80,6 @@ public class ObjectivesPluginTest { public void prepareMock() { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); AAPSMocker.mockSP(); AAPSMocker.mockStrings(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java index 938baf0611..1dabf0ff30 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java @@ -229,7 +229,6 @@ public class SafetyPluginTest { AAPSMocker.mockConstraintsChecker(); AAPSMocker.mockSP(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java index 34c064a214..bd118d1391 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java @@ -1,4 +1,5 @@ package info.nightscout.androidaps.plugins.constraints.storage; + import android.os.Environment; import android.os.StatFs; @@ -15,13 +16,12 @@ import java.io.File; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.Constraint; -import static org.mockito.Mockito.when; -import static org.mockito.Mockito.mock; -import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.powermock.api.mockito.PowerMockito.whenNew; /** * Created by Rumen on 06.03.2019. @@ -72,7 +72,6 @@ public class StorageConstraintPluginTest extends StorageConstraintPlugin{ public void prepareMock() { AAPSMocker.mockMainApp(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); mockedFile = mock(File.class); mockedStatFs = mock(StatFs.class); storageConstraintPlugin = StorageConstraintPlugin.getPlugin(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java index 257392ca6e..c0cb9b70a2 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java @@ -65,7 +65,6 @@ public class ActionLoopDisableTest { public void prepareTest() { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); - AAPSMocker.mockBus(); AAPSMocker.mockSP(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockCommandQueue(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java index c5d9b81f56..d42549d222 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java @@ -65,7 +65,6 @@ public class ActionLoopEnableTest { public void prepareTest() { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); - AAPSMocker.mockBus(); AAPSMocker.mockSP(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockCommandQueue(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java index 755c56024d..c690681513 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java @@ -63,7 +63,6 @@ public class ActionLoopResumeTest { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockSP(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockNSUpload(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java index 6b7c7f781f..67e22b0d5b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java @@ -80,7 +80,6 @@ public class ActionLoopSuspendTest { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockSP(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockNSUpload(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java index 62447ac717..d1393c6824 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java @@ -6,29 +6,17 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import info.AAPSMocker; -import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.db.TempTarget; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; -import info.nightscout.androidaps.plugins.general.automation.elements.InputBg; -import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration; import info.nightscout.androidaps.plugins.general.automation.elements.InputString; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.SP; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - @RunWith(PowerMockRunner.class) @PrepareForTest({MainApp.class, SP.class, NSUpload.class}) public class ActionNotificationTest { @@ -85,7 +73,6 @@ public class ActionNotificationTest { AAPSMocker.mockMainApp(); AAPSMocker.mockSP(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockNSUpload(); actionNotification = new ActionNotification(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java index 78a603701e..da1ce78cc7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.actions; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.junit.Assert; import org.junit.Before; @@ -20,7 +19,7 @@ import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.SP; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, SP.class, Bus.class, ProfileFunctions.class}) +@PrepareForTest({MainApp.class, SP.class, ProfileFunctions.class}) public class ActionProfileSwitchPercentTest { private ActionProfileSwitchPercent actionProfileSwitchPercent; @@ -77,7 +76,6 @@ public class ActionProfileSwitchPercentTest { public void prepareTest() { AAPSMocker.mockMainApp(); AAPSMocker.mockSP(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockProfileFunctions(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java index e62f573c2b..28f0278887 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java @@ -45,7 +45,6 @@ public class ActionProfileSwitchTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockStrings(); AAPSMocker.mockTreatmentService(); - AAPSMocker.mockBus(); AAPSMocker.mockDatabaseHelper(); AAPSMocker.mockProfileFunctions(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java index 4db3d79dc5..7254d85192 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java @@ -76,7 +76,6 @@ public class ActionSendSMSTest { @Before public void prepareTest() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockSP(); mockStatic(SmsManager.class); SmsManager smsManager = mock(SmsManager.class); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java index ff2baf6198..ed1141f0a4 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java @@ -90,7 +90,6 @@ public class ActionStartTempTargetTest { AAPSMocker.mockMainApp(); AAPSMocker.mockSP(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockProfileFunctions(); treatmentsPlugin = AAPSMocker.mockTreatmentPlugin(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java index 8a56a65459..dd2e335e86 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java @@ -31,7 +31,6 @@ public class InputBgTest { @Before public void prepare() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockProfileFunctions(); } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java index a9a0a4c91f..008b7a6743 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java @@ -31,7 +31,6 @@ public class InputTempTargetTest { @Before public void prepare() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockProfileFunctions(); } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java index ab1851aefc..dd2a4a533e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -28,7 +27,7 @@ import static org.mockito.ArgumentMatchers.anyDouble; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class}) public class TriggerAutosensValueTest { long now = 1514766900000L; @@ -115,7 +114,6 @@ public class TriggerAutosensValueTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockIobCobCalculatorPlugin(); AAPSMocker.mockProfileFunctions(); AAPSMocker.mockSP(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java index 002ac70488..a090058cd3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -30,7 +29,7 @@ import info.nightscout.androidaps.utils.DateUtil; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class}) public class TriggerBgTest { long now = 1514766900000L; @@ -112,7 +111,6 @@ public class TriggerBgTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockIobCobCalculatorPlugin(); AAPSMocker.mockProfileFunctions(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java index b4965eb1d1..1d3a45a05e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -25,7 +24,7 @@ import static org.mockito.ArgumentMatchers.anyDouble; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class}) public class TriggerBolusAgoTest { long now = 1514766900000L; @@ -109,7 +108,6 @@ public class TriggerBolusAgoTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockProfileFunctions(); PowerMockito.mockStatic(DateUtil.class); AAPSMocker.mockTreatmentPlugin(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java index 1681f00356..725cc6cfd5 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -16,8 +15,6 @@ import org.powermock.modules.junit4.PowerMockRunner; import info.AAPSMocker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.automation.elements.Comparator; @@ -27,12 +24,10 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.SP; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.powermock.api.mockito.PowerMockito.verifyNew; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class, L.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class, L.class}) public class TriggerCOBTest { long now = 1514766900000L; @@ -104,7 +99,6 @@ public class TriggerCOBTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); iobCobCalculatorPlugin = AAPSMocker.mockIobCobCalculatorPlugin(); AAPSMocker.mockProfileFunctions(); AAPSMocker.mockSP(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java index 722b6f1643..c09af0f5b1 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -32,7 +31,7 @@ import info.nightscout.androidaps.utils.DateUtil; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, GlucoseStatus.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, GlucoseStatus.class}) public class TriggerDeltaTest { long now = 1514766900000L; @@ -122,7 +121,6 @@ public class TriggerDeltaTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockIobCobCalculatorPlugin(); AAPSMocker.mockProfileFunctions(); AAPSMocker.mockApplicationContext(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java index f2deee54a3..db39c05d2c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -28,7 +27,7 @@ import static org.mockito.ArgumentMatchers.anyLong; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class}) public class TriggerIobTest { long now = 1514766900000L; @@ -103,7 +102,6 @@ public class TriggerIobTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); iobCobCalculatorPlugin = AAPSMocker.mockIobCobCalculatorPlugin(); AAPSMocker.mockProfileFunctions(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java index 3e9a566615..9e1f713339 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import android.location.Location; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -26,7 +25,7 @@ import info.nightscout.androidaps.utils.DateUtil; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, LocationService.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, LocationService.class}) public class TriggerLocationTest { @@ -35,7 +34,6 @@ public class TriggerLocationTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockApplicationContext(); PowerMockito.mockStatic(DateUtil.class); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java index 9aea88e141..4b83495937 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -24,7 +23,7 @@ import info.nightscout.androidaps.utils.DateUtil; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, L.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, L.class}) public class TriggerProfilePercentTest { private long now = 1514766900000L; @@ -102,7 +101,6 @@ public class TriggerProfilePercentTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); AAPSMocker.mockProfileFunctions(); AAPSMocker.mockL(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java index 6b6f27dd6c..9ba61af960 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -26,7 +25,7 @@ import info.nightscout.androidaps.utils.DateUtil; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class, ConfigBuilderPlugin.class, System.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class, ConfigBuilderPlugin.class, System.class}) public class TriggerPumpLastConnectionTest { long now = 1514766900000L; @@ -103,7 +102,6 @@ public class TriggerPumpLastConnectionTest { public void mock() { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); PowerMockito.mockStatic(DateUtil.class); when(DateUtil.now()).thenReturn(now); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java index 21c69da80c..c9b463dfd0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; -import com.squareup.otto.Bus; - import org.json.JSONException; import org.json.JSONObject; import org.junit.Assert; @@ -22,7 +20,7 @@ import info.nightscout.androidaps.utils.T; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, DateUtil.class, GregorianCalendar.class}) +@PrepareForTest({MainApp.class, DateUtil.class, GregorianCalendar.class}) public class TriggerRecurringTimeTest { long now = 1514766900000L; @@ -65,7 +63,6 @@ public class TriggerRecurringTimeTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); PowerMockito.mockStatic(DateUtil.class); when(DateUtil.now()).thenReturn(now); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java index 7e42d6ba48..03c7e5cda2 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -22,11 +21,10 @@ import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; -import static org.mockito.ArgumentMatchers.any; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class}) +@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class}) public class TriggerTempTargetTest { TreatmentsPlugin treatmentsPlugin; @@ -86,7 +84,6 @@ public class TriggerTempTargetTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); treatmentsPlugin = AAPSMocker.mockTreatmentPlugin(); PowerMockito.mockStatic(DateUtil.class); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java index 6e411fb2a5..6b36cc1fd3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -19,12 +18,11 @@ import info.AAPSMocker; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.T; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, DateUtil.class, GregorianCalendar.class}) +@PrepareForTest({MainApp.class, DateUtil.class, GregorianCalendar.class}) public class TriggerTimeRangeTest { int now = 754; @@ -98,7 +96,6 @@ public class TriggerTimeRangeTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); PowerMockito.mockStatic(DateUtil.class); when(DateUtil.now()).thenReturn((long) now * 60000); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java index cf8cfd7b75..b4b1794481 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -24,7 +23,7 @@ import info.nightscout.androidaps.utils.T; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, DateUtil.class, GregorianCalendar.class}) +@PrepareForTest({MainApp.class, DateUtil.class, GregorianCalendar.class}) public class TriggerTimeTest { long now = 1514766900000L; @@ -90,7 +89,6 @@ public class TriggerTimeTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); PowerMockito.mockStatic(DateUtil.class); when(DateUtil.now()).thenReturn(now); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java index 6c5a359ec7..d6eef521ed 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers; import com.google.common.base.Optional; -import com.squareup.otto.Bus; import org.json.JSONException; import org.json.JSONObject; @@ -24,7 +23,7 @@ import info.nightscout.androidaps.utils.DateUtil; import static org.powermock.api.mockito.PowerMockito.when; @RunWith(PowerMockRunner.class) -@PrepareForTest({MainApp.class, Bus.class, NetworkChangeReceiver.class, DateUtil.class}) +@PrepareForTest({MainApp.class, NetworkChangeReceiver.class, DateUtil.class}) public class TriggerWifiSsidTest { long now = 1514766900000L; @@ -102,7 +101,6 @@ public class TriggerWifiSsidTest { @Before public void mock() { AAPSMocker.mockMainApp(); - AAPSMocker.mockBus(); PowerMockito.mockStatic(NetworkChangeReceiver.class); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java index a1b21fe9a2..f8496a71b2 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java @@ -68,7 +68,6 @@ public class NewNSTreatmentDialogTest { AAPSMocker.mockStrings(); PowerMockito.mockStatic(NSUpload.class); AAPSMocker.mockTreatmentService(); - AAPSMocker.mockBus(); AAPSMocker.mockDatabaseHelper(); NSProfilePlugin profilePlugin = NSProfilePlugin.getPlugin(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java index 0abbf50399..ad172f13e9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.general.nsclient; import android.content.Context; -import com.squareup.otto.Bus; import org.junit.Before; import org.junit.Test; @@ -34,10 +33,9 @@ public class NsClientReceiverDelegateTest { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); - Bus bus = MainApp.bus(); Context context = MainApp.instance().getApplicationContext(); - sut = new NsClientReceiverDelegate(context, bus); + sut = new NsClientReceiverDelegate(context); } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java index abc29216b0..f97a397e32 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java @@ -718,7 +718,6 @@ public class SmsCommunicatorPluginTest { AAPSMocker.mockSP(); AAPSMocker.mockL(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); AAPSMocker.mockProfileFunctions(); AAPSMocker.mockTreatmentPlugin(); AAPSMocker.mockTreatmentService(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt index 9a60941f36..1b9c937c24 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.general.versionChecker -import com.squareup.otto.Bus import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L @@ -63,7 +62,7 @@ class VersionCheckerUtilsKtTest { @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update1`() { - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1") @@ -80,7 +79,7 @@ class VersionCheckerUtilsKtTest { @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update2`() { - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1-dev") @@ -96,7 +95,7 @@ class VersionCheckerUtilsKtTest { @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update3`() { - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.1") @@ -112,7 +111,7 @@ class VersionCheckerUtilsKtTest { @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update4`() { - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(newVersion = "2.2", currentVersion = "2.1.1") @@ -128,7 +127,7 @@ class VersionCheckerUtilsKtTest { @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update5`() { - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2-dev") //verify(bus, times(1)).post(any()) @@ -143,7 +142,7 @@ class VersionCheckerUtilsKtTest { @Test @PrepareForTest(MainApp::class, L::class, SP::class) fun `should find update6`() { - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2dev") //verify(bus, times(1)).post(any()) @@ -165,10 +164,10 @@ class VersionCheckerUtilsKtTest { | version = "2.2.2" | appName = "Aaoeu" """.trimMargin() - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2") - verify(bus, times(0)).post(any()) + //verify(bus, times(0)).post(any()) PowerMockito.verifyStatic(SP::class.java, times(1)) SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong()) @@ -185,11 +184,9 @@ class VersionCheckerUtilsKtTest { | version = "3.0" | appName = "Aaoeu" """.trimMargin() - val bus = prepareBus() + prepareMainApp() compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2") - //verify(bus, times(1)).post(any()) - PowerMockito.verifyStatic(SP::class.java, times(1)) SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong()) PowerMockito.verifyStatic(SP::class.java, times(1)) @@ -207,15 +204,12 @@ class VersionCheckerUtilsKtTest { assertEquals(100L, System.currentTimeMillis()) } - private fun prepareBus(): Bus { + private fun prepareMainApp() { PowerMockito.mockStatic(MainApp::class.java) val mainApp = mock(MainApp::class.java) `when`(MainApp.instance()).thenReturn(mainApp) - val bus = mock(Bus::class.java) - `when`(MainApp.bus()).thenReturn(bus) `when`(MainApp.gs(ArgumentMatchers.anyInt())).thenReturn("some dummy string") prepareSP() - return bus } private fun prepareSP() { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java index 1ea781941f..8e7784f5b8 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java @@ -62,7 +62,6 @@ public class ComboPluginTest { public void prepareMocks() throws Exception { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockCommandQueue(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java index c7407e7af5..322655caaa 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java @@ -62,7 +62,6 @@ public class DanaRPluginTest { public void prepareMocks() throws Exception { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java index 0ed6c5f7cd..289df3d186 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java @@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.utils.SP; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Created by Rumen Georgiev on 8/28/2018. @@ -27,7 +27,6 @@ public class MsgBolusProgressTest { AAPSMocker.mockSP(); AAPSMocker.mockL(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); Treatment t = new Treatment(); MsgBolusProgress packet = new MsgBolusProgress(3D, t); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java index 5dc65b7228..4032ef7dad 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java @@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.utils.SP; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Created by Rumen Georgiev on 8/28/2018. @@ -26,7 +26,7 @@ public class MsgBolusStopTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); + AAPSMocker.mockStrings(); Treatment t = new Treatment(); MsgBolusStop packet = new MsgBolusStop(1d,t); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java index 32b82270ab..83dbdcd12c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.utils.SP; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Created by Rumen Georgiev on 8/28/2018. @@ -28,7 +28,6 @@ public class MsgCheckValueTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); Treatment t = new Treatment(); MsgCheckValue packet = new MsgCheckValue(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java index b597c69062..45664cdfb7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java @@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.utils.SP; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Created by Rumen Georgiev on 8/28/2018. @@ -26,7 +26,6 @@ public class MsgErrorTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockNSUpload(); MsgError packet = new MsgError(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java index c4d40abcc7..2bfec9baee 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java @@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.utils.SP; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Created by Rumen Georgiev on 8/30/2018. @@ -26,7 +26,6 @@ public class MsgHistoryAllTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockDatabaseHelper(); MsgHistoryAll packet = new MsgHistoryAll(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java index 11aa667f1e..f7860fbaa2 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java @@ -26,7 +26,6 @@ public class MsgInitConnStatusBolusTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); MsgInitConnStatusBolus packet = new MsgInitConnStatusBolus(); // test message decoding diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java index 467ccc2f9b..0b1d956ded 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java @@ -27,7 +27,6 @@ public class MsgInitConnStatusOptionTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockConfigBuilder(); MsgInitConnStatusOption packet = new MsgInitConnStatusOption(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java index 1da818b5bc..486a98524d 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java @@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.utils.SP; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * Created by Rumen Georgiev on 8/30/2018. @@ -26,7 +26,6 @@ public class MsgInitConnStatusTimeTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockCommandQueue(); AAPSMocker.mockDanaRPlugin(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java index f49cb5eace..ed4fb83a10 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java @@ -25,7 +25,6 @@ public class MsgSetBasalProfileTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); MsgSetBasalProfile packet = new MsgSetBasalProfile((byte) 1, createArray(24,1)); // test message decoding diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java index 5a272c8cf6..cfb17d9ab5 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java @@ -25,7 +25,6 @@ public class MsgSetSingleBasalProfileTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); MsgSetSingleBasalProfile packet = new MsgSetSingleBasalProfile(createArray(24, 2)); // test message decoding diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java index 7680e6c5a9..2ba1be66a7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java @@ -26,7 +26,6 @@ public class MsgSettingMealTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); MsgSettingMeal packet = new MsgSettingMeal(); // test message decoding diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java index ca249e016c..269a6a0304 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java @@ -62,7 +62,6 @@ public class DanaRSPluginTest { public void prepareMocks() throws Exception { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java index 309644d7f0..a866ce73a7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java @@ -93,7 +93,6 @@ public class DanaRS_Packet_APS_History_EventsTest extends DanaRS_Packet_APS_Hist AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); - AAPSMocker.mockBus(); SPMocker.prepareMock(); SP.putString("profile", AAPSMocker.getValidProfileStore().getData().toString()); AAPSMocker.mockConfigBuilder(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java index a530749e27..762403142f 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java @@ -26,7 +26,6 @@ public class DanaRS_Packet_Basal_Get_Basal_RateTest { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); - AAPSMocker.mockBus(); AAPSMocker.mockL(); DanaRS_Packet_Basal_Get_Basal_Rate packet = new DanaRS_Packet_Basal_Get_Basal_Rate(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java index da023edd1a..8feee88e7a 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java @@ -26,7 +26,6 @@ public class DanaRS_Packet_Basal_Get_Profile_Basal_RateTest extends DanaRS_Packe AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); - AAPSMocker.mockBus(); AAPSMocker.mockL(); // test if pumpRofile array is set right diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java index 9931e02bd6..73e67f6830 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java @@ -28,7 +28,6 @@ public class DanaRS_Packet_Bolus_Get_Bolus_OptionTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); DanaRS_Packet_Bolus_Get_Bolus_Option packet = new DanaRS_Packet_Bolus_Get_Bolus_Option(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java index c04ccd2767..f41a686201 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java @@ -25,8 +25,8 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest extends DanaRS_Packet_B public void runTest() { AAPSMocker.mockMainApp(); AAPSMocker.mockApplicationContext(); + AAPSMocker.mockStrings(); AAPSMocker.mockSP(); - AAPSMocker.mockBus(); AAPSMocker.mockL(); DanaRS_Packet_Bolus_Set_Step_Bolus_Stop testPacket = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(1d , new Treatment()); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java index 858abdbfd7..b3dde0b102 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java @@ -27,7 +27,6 @@ public class DanaRS_Packet_General_Get_Pump_CheckTest { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); DanaRS_Packet_General_Get_Pump_Check packet = new DanaRS_Packet_General_Get_Pump_Check(); // test params diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java index bf83dcee13..0d209edb33 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java @@ -30,7 +30,6 @@ public class DanaRS_Packet_Notify_Delivery_CompleteTest { AAPSMocker.mockSP(); AAPSMocker.mockL(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); DanaRS_Packet_Notify_Delivery_Complete packet = new DanaRS_Packet_Notify_Delivery_Complete(0.5d,new Treatment()); // test params diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java index 7d2603991b..ce3554cf74 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java @@ -30,7 +30,6 @@ public class DanaRS_Packet_Notify_Delivery_Rate_DisplayTest { AAPSMocker.mockSP(); AAPSMocker.mockL(); AAPSMocker.mockStrings(); - AAPSMocker.mockBus(); DanaRS_Packet_Notify_Delivery_Rate_Display packet = new DanaRS_Packet_Notify_Delivery_Rate_Display(1, new Treatment()); // test params diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java index 288df852f9..71ae9b1d51 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java @@ -66,7 +66,6 @@ public class DanaRv2PluginTest { public void prepareMocks() throws Exception { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java index 33c64510cd..0dc1f174c9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java @@ -25,7 +25,6 @@ public class MessageHashTable_rv2Test { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); MessageHashTableRv2 hashTableRv2 = MessageHashTableRv2.INSTANCE; diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java index acc2675c92..e81c5416f1 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java @@ -28,7 +28,6 @@ public class MsgCheckValue_v2Test { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockDanaRPlugin(); AAPSMocker.mockConfigBuilder(); AAPSMocker.mockCommandQueue(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java index 334c556ccb..fc70670e31 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java @@ -28,7 +28,6 @@ public class MsgHistoryEvents_v2Test { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockDatabaseHelper(); AAPSMocker.mockTreatmentPlugin(); AAPSMocker.mockTreatmentService(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java index 50f80550b5..8413f296e1 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java @@ -26,7 +26,6 @@ public class MsgSetHistoryEntry_v2Test { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockDanaRPlugin(); MsgSetHistoryEntry_v2 initializerTest = new MsgSetHistoryEntry_v2((byte) 1, System.currentTimeMillis(), 1, 0); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java index 70a7a36f0e..b354fe6d49 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java @@ -27,7 +27,6 @@ public class MsgStatusTempBasal_v2Test { AAPSMocker.mockApplicationContext(); AAPSMocker.mockSP(); AAPSMocker.mockL(); - AAPSMocker.mockBus(); AAPSMocker.mockDanaRPlugin(); MsgStatusTempBasal_v2 packet = new MsgStatusTempBasal_v2(); diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java index 9ef75ef597..0a9d68c1ad 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java @@ -35,7 +35,6 @@ public class VirtualPumpPluginUTest { public void prepareMocks() throws Exception { AAPSMocker.mockMainApp(); AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockBus(); AAPSMocker.mockStrings(); AAPSMocker.mockCommandQueue(); AAPSMocker.mockSP(); diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java index 63a626d8f7..baaccd95b3 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java @@ -2,9 +2,6 @@ package info.nightscout.androidaps.queue; import android.content.Context; -import com.squareup.otto.Bus; -import com.squareup.otto.ThreadEnforcer; - import junit.framework.Assert; import org.json.JSONException; @@ -26,8 +23,8 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.ToastUtils; @@ -140,9 +137,6 @@ public class CommandQueueTest extends CommandQueue { String message = null; PowerMockito.doNothing().when(ToastUtils.class, "showToastInUiThread", context, message); - Bus bus = new Bus(ThreadEnforcer.ANY); - - when(MainApp.bus()).thenReturn(bus); when(MainApp.gs(0)).thenReturn(""); PowerMockito.mockStatic(TreatmentsPlugin.class); From 3040ef6b7b8d8a5561a0d85c5f2b2cb11131618c Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 15 Oct 2019 13:35:37 +0200 Subject: [PATCH 12/13] 2.4-dev-i --- app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle b/app/build.gradle index 05021d1790..74aefc612d 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -109,7 +109,7 @@ android { targetSdkVersion 28 multiDexEnabled true versionCode 1500 - version "2.4-dev-h" + version "2.4-dev-i" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' From 1c5b2c9858d316443c98935ee0cc402fabdbaf8b Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Tue, 15 Oct 2019 16:05:04 +0200 Subject: [PATCH 13/13] remove failing test --- app/build.gradle | 3 - .../java/info/nightscout/MainAppTest.java | 125 ------------------ 2 files changed, 128 deletions(-) delete mode 100644 app/src/test/java/info/nightscout/MainAppTest.java diff --git a/app/build.gradle b/app/build.gradle index 74aefc612d..06c13ce5bd 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -284,9 +284,6 @@ dependencies { testImplementation("com.google.truth:truth:0.39") { exclude group: "com.google.guava", module: "guava" } - testImplementation("org.robolectric:robolectric:4.2.1") { - exclude group: "com.google.guava", module: "guava" - } testImplementation "org.skyscreamer:jsonassert:1.5.0" testImplementation "org.hamcrest:hamcrest-all:1.3" /* diff --git a/app/src/test/java/info/nightscout/MainAppTest.java b/app/src/test/java/info/nightscout/MainAppTest.java deleted file mode 100644 index feecaae779..0000000000 --- a/app/src/test/java/info/nightscout/MainAppTest.java +++ /dev/null @@ -1,125 +0,0 @@ -package info.nightscout; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.robolectric.RobolectricTestRunner; - -import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils; -import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin; - - -/** - * Created by mike on 28.03.2018. - */ - -@RunWith(RobolectricTestRunner.class) -public class MainAppTest { - /* - MainApp mainApp = new MainApp(); - - @Test - public void gsTest() { - Assert.assertNotNull(mainApp.gs(R.string.app_name)); - Assert.assertNotNull(mainApp.gs(R.string.app_name, "")); - } - - @Test - public void gcTest() { - Assert.assertEquals(-16711681, mainApp.gc(R.color.basal)); - } - - @Test - public void instanceTest() { - Assert.assertNotNull(mainApp.instance()); - } - - @Test - public void getDbHelperTest() { - Assert.assertNotNull(mainApp.getDbHelper()); - } - - @Test - public void closeDbHelperTest() { - mainApp.closeDbHelper(); - Assert.assertNull(mainApp.getDbHelper()); - } - - @Test - public void getConstraintCheckerTest() { - Assert.assertNotNull(mainApp.getConstraintChecker()); - } - - @Test - public void getPluginsListTest() { - Assert.assertNotNull(mainApp.getPluginsList()); - } - - @Test - public void getSpecificPluginsListTest() { - // currently MDI, VP, R, Rv2, KoreanR, RS - int expected; - if (Config.NSCLIENT) - expected = 1; // VirtualPump only - else - expected = 8; - Assert.assertEquals(expected, mainApp.getSpecificPluginsList(PluginType.PUMP).size()); - } - - @Test - public void getSpecificPluginsVisibleInListTest() { - // currently MDI, VP, R, Rv2, KoreanR, RS - int expected; - if (Config.NSCLIENT) - expected = 1; // VirtualPump only - else - expected = 8; - Assert.assertEquals(expected, mainApp.getSpecificPluginsVisibleInList(PluginType.PUMP).size()); - } - - @Test - public void getSpecificPluginsListByInterfaceTest() { - // currently MDI, VP, R, Rv2, KoreanR, RS - int expected; - if (Config.NSCLIENT) - expected = 1; // VirtualPump only - else - expected = 8; - Assert.assertEquals(expected, mainApp.getSpecificPluginsListByInterface(PumpInterface.class).size()); - } - - @Test - public void getSpecificPluginsVisibleInListByInterfaceTest() { - // currently MDI, VP, R, Rv2, KoreanR, RS - int expected; - if (Config.NSCLIENT) - expected = 1; // VirtualPump only - else - expected = 8; - Assert.assertEquals(expected, mainApp.getSpecificPluginsVisibleInListByInterface(PumpInterface.class, PluginType.PUMP).size()); - } - - @Test - public void getSpecificPluginTest() { - // currently MDI, VP, R, Rv2, KoreanR, RS - Assert.assertEquals("Overview", mainApp.getSpecificPlugin(OverviewPlugin.class).getName()); - } - - @Test - public void isEngineeringModeOrReleaseTest() { - mainApp.devBranch = true; - Assert.assertEquals(!Config.APS, mainApp.isEngineeringModeOrRelease()); - } - - @Test - public void getLogDirectoryTest() { - // logger not initialized in Roboelectric - Assert.assertNull(LoggerUtils.getLogDirectory()); - } -*/ -}