From acf9f05928cbf808ed9c3ed986c02dd9973a57bb Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Wed, 29 Apr 2020 00:39:20 +0200 Subject: [PATCH 01/16] Removed internal function TypedArrayUtils is marked as `@RestrictTo(LIBRARY_GROUP_PREFIX)`. getAttr() will chose between the two parameters, so if both are the same has no functionality anyway. --- .../utils/textValidator/ValidatingEditTextPreference.kt | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/textValidator/ValidatingEditTextPreference.kt b/app/src/main/java/info/nightscout/androidaps/utils/textValidator/ValidatingEditTextPreference.kt index 190a3bea73..b4a49c42de 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/textValidator/ValidatingEditTextPreference.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/textValidator/ValidatingEditTextPreference.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.utils.textValidator import android.content.Context import android.util.AttributeSet -import androidx.core.content.res.TypedArrayUtils import androidx.preference.EditTextPreference import androidx.preference.EditTextPreference.OnBindEditTextListener import androidx.preference.PreferenceViewHolder @@ -23,8 +22,7 @@ class ValidatingEditTextPreference(ctx: Context, attrs: AttributeSet, defStyleAt : this(ctx, attrs, defStyle, 0) constructor(ctx: Context, attrs: AttributeSet) - : this(ctx, attrs, TypedArrayUtils.getAttr(ctx, R.attr.editTextPreferenceStyle, - R.attr.editTextPreferenceStyle)) + : this(ctx, attrs, R.attr.editTextPreferenceStyle) private lateinit var editTextValidator: EditTextValidator @@ -33,4 +31,4 @@ class ValidatingEditTextPreference(ctx: Context, attrs: AttributeSet, defStyleAt holder?.isDividerAllowedAbove = false holder?.isDividerAllowedBelow = false } -} \ No newline at end of file +} From 42cfd87a2b8f3e55a9de209a21264ce5e27fdb8c Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 30 Apr 2020 00:37:58 +0200 Subject: [PATCH 02/16] injection cleanup --- .../dependencyInjection/APSModule.kt | 28 +++ .../dependencyInjection/AppComponent.kt | 162 ++--------------- .../dependencyInjection/AppModule.kt | 171 ------------------ .../dependencyInjection/AutomationModule.kt | 71 ++++++++ .../dependencyInjection/CommandQueueModule.kt | 32 ++++ .../dependencyInjection/DataClassesModule.kt | 32 ++++ .../dependencyInjection/MedtronicModule.kt | 40 ++++ .../dependencyInjection/ObjectivesModule.kt | 24 +++ .../dependencyInjection/OverviewModule.kt | 22 +++ .../dependencyInjection/PreferencesModule.kt | 18 ++ .../dependencyInjection/SMSModule.kt | 12 ++ .../dependencyInjection/WizardModule.kt | 27 +++ 12 files changed, 317 insertions(+), 322 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/AutomationModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/ObjectivesModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/SMSModule.kt create mode 100644 app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt new file mode 100644 index 0000000000..d3fef14166 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback +import info.nightscout.androidaps.plugins.aps.loop.APSResult +import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalAdapterAMAJS +import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread + +@Module +@Suppress("unused") +abstract class APSModule { + + @ContributesAndroidInjector abstract fun loggerCallbackInjector(): LoggerCallback + @ContributesAndroidInjector abstract fun apsResultInjector(): APSResult + @ContributesAndroidInjector abstract fun determineBasalResultSMBInjector(): DetermineBasalResultSMB + @ContributesAndroidInjector abstract fun determineBasalResultAMAInjector(): DetermineBasalResultAMA + @ContributesAndroidInjector abstract fun determineBasalAdapterAMAJSInjector(): DetermineBasalAdapterAMAJS + @ContributesAndroidInjector abstract fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS + @ContributesAndroidInjector abstract fun autosensDataInjector(): AutosensData + @ContributesAndroidInjector abstract fun iobCobThreadInjector(): IobCobThread + @ContributesAndroidInjector abstract fun iobCobOref1ThreadInjector(): IobCobOref1Thread +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 7d9dcac987..91153bd867 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -57,161 +57,21 @@ import javax.inject.Singleton FragmentsModule::class, AppModule::class, ReceiversModule::class, - ServicesModule::class + ServicesModule::class, + AutomationModule::class, + CommandQueueModule::class, + ObjectivesModule::class, + WizardModule::class, + MedtronicModule::class, + APSModule::class, + PreferencesModule::class, + OverviewModule::class, + DataClassesModule::class, + SMSModule::class ] ) interface AppComponent : AndroidInjector { - fun injectProfileStore(profileStore: ProfileStore) - fun injectPumpEnactResult(pumpEnactResult: PumpEnactResult) - fun injectAPSResult(apsResult: APSResult) - fun injectDetermineBasalResultSMB(determineBasalResultSMB: DetermineBasalResultSMB) - fun injectDetermineBasalResultAMA(determineBasalResultAMA: DetermineBasalResultAMA) - fun injectDetermineBasalAdapterSMBJS(determineBasalAdapterSMBJS: DetermineBasalAdapterSMBJS) - - fun injectCommandQueue(commandQueue: CommandQueue) - fun injectCommandBolus(commandBolus: CommandBolus) - fun injectCommandCancelExtendedBolus(commandCancelExtendedBolus: CommandCancelExtendedBolus) - fun injectCommandCancelTempBasal(commandCancelTempBasal: CommandCancelTempBasal) - fun injectCommandExtendedBolus(commandExtendedBolus: CommandExtendedBolus) - fun injectCommandInsightSetTBROverNotification(commandInsightSetTBROverNotification: CommandInsightSetTBROverNotification) - fun injectCommandLoadEvents(commandLoadEvents: CommandLoadEvents) - fun injectCommandLoadHistory(commandLoadHistory: CommandLoadHistory) - fun injectCommandLoadTDDs(commandLoadTDDs: CommandLoadTDDs) - fun injectCommandReadStatus(commandReadStatus: CommandReadStatus) - fun injectCommandSetProfile(commandSetProfile: CommandSetProfile) - fun injectCommandCommandSMBBolus(commandSMBBolus: CommandSMBBolus) - fun injectCommandStartPump(commandStartPump: CommandStartPump) - fun injectCommandStopPump(commandStopPump: CommandStopPump) - fun injectCommandTempBasalAbsolute(commandTempBasalAbsolute: CommandTempBasalAbsolute) - fun injectCommandTempBasalPercent(commandTempBasalPercent: CommandTempBasalPercent) - fun injectCommandSetUserSettings(commandSetUserSettings: CommandSetUserSettings) - - fun injectObjective(objective: Objective) - fun injectObjective0(objective0: Objective0) - fun injectObjective1(objective1: Objective1) - fun injectObjective2(objective2: Objective2) - fun injectObjective3(objective3: Objective3) - fun injectObjective4(objective4: Objective4) - fun injectObjective5(objective5: Objective5) - fun injectObjective6(objective6: Objective6) - fun injectObjective7(objective7: Objective7) - fun injectObjective8(objective8: Objective8) - fun injectObjective9(objective9: Objective9) - fun injectObjective10(objective10: Objective10) - - fun injectAutomationEvent(automationEvent: AutomationEvent) - - fun injectTrigger(trigger: Trigger) - fun injectTrigger(triggerAutosensValue: TriggerAutosensValue) - fun injectTrigger(triggerBg: TriggerBg) - fun injectTrigger(triggerBolusAgo: TriggerBolusAgo) - fun injectTrigger(triggerBTDevice: TriggerBTDevice) - fun injectTrigger(triggerCOB: TriggerCOB) - fun injectTrigger(triggerConnector: TriggerConnector) - fun injectTrigger(triggerDelta: TriggerDelta) - fun injectTrigger(triggerDummy: TriggerDummy) - fun injectTrigger(triggerIob: TriggerIob) - fun injectTrigger(triggerLocation: TriggerLocation) - fun injectTrigger(triggerProfilePercent: TriggerProfilePercent) - fun injectTrigger(triggerPumpLastConnection: TriggerPumpLastConnection) - fun injectTrigger(triggerRecurringTime: TriggerRecurringTime) - fun injectTrigger(triggerTempTarget: TriggerTempTarget) - fun injectTrigger(triggerTime: TriggerTime) - fun injectTrigger(triggerTimeRange: TriggerTimeRange) - fun injectTrigger(triggerWifiSsid: TriggerWifiSsid) - - fun injectAction(action: Action) - fun injectActionDummy(action: ActionDummy) - fun injectActionLoopDisable(action: ActionLoopDisable) - fun injectActionLoopEnable(action: ActionLoopEnable) - fun injectActionLoopResume(action: ActionLoopResume) - fun injectAction(action: ActionLoopSuspend) - fun injectActionLoopSuspend(action: ActionNotification) - fun injectActionProfileSwitch(action: ActionProfileSwitch) - fun injectAction(action: ActionProfileSwitchPercent) - fun injectActionProfileSwitchPercent(action: ActionSendSMS) - fun injectActionStartTempTarget(action: ActionStartTempTarget) - fun injectActionStopTempTarget(action: ActionStopTempTarget) - - fun injectElement(element: Element) - fun injectElement(inputBg: InputBg) - fun injectElement(inputButton: InputButton) - fun injectElement(comparator: Comparator) - fun injectElement(comparatorExists: ComparatorExists) - fun injectElement(comparatorConnect: ComparatorConnect) - fun injectElement(inputDateTime: InputDateTime) - fun injectElement(inputDelta: InputDelta) - fun injectElement(inputDropdownMenu: InputDropdownMenu) - fun injectElement(inputDouble: InputDouble) - fun injectElement(inputDuration: InputDuration) - fun injectElement(inputInsulin: InputInsulin) - fun injectElement(inputLocationMode: InputLocationMode) - fun injectElement(inputPercent: InputPercent) - fun injectElement(inputProfileName: InputProfileName) - fun injectElement(inputString: InputString) - fun injectElement(inputTempTarget: InputTempTarget) - fun injectElement(inputTimeRange: InputTimeRange) - fun injectElement(inputTime: InputTime) - fun injectElement(inputWeekDay: InputWeekDay) - fun injectElement(labelWithElement: LabelWithElement) - fun injectElement(staticLabel: StaticLabel) - - fun injectAutosensDate(autosensData: AutosensData) - fun injectIobCobThread(iobCobThread: IobCobThread) - fun injectIobCobOref1Thread(iobCobOref1Thread: IobCobOref1Thread) - - fun injectTreatment(treatment: Treatment) - fun injectBgReading(bgReading: BgReading) - fun injectProfileSwitch(profileSwitch: ProfileSwitch) - fun injectTemporaryBasal(temporaryBasal: TemporaryBasal) - fun injectCareportalEvent(careportalEvent: CareportalEvent) - - fun injectNotification(notificationWithAction: NotificationWithAction) - - fun injectLoggerCallback(loggerCallback: LoggerCallback) - fun injectBolusWizard(bolusWizard: BolusWizard) - fun injectQuickWizardEntry(quickWizardEntry: QuickWizardEntry) - - fun injectAuthRequest(authRequest: AuthRequest) - - fun injectSWBreak(swBreak: SWBreak) - fun injectSWButton(swButton: SWButton) - fun injectSWEditNumberWithUnits(swEditNumberWithUnits: SWEditNumberWithUnits) - fun injectSWEditString(swEditString: SWEditString) - fun injectSWEditEncryptedPassword(swSWEditEncryptedPassword: SWEditEncryptedPassword) - fun injectSWEditUrl(swEditUrl: SWEditUrl) - fun injectSWFragment(swFragment: SWFragment) - fun injectSSWHtmlLink(swHtmlLink: SWHtmlLink) - fun injectSWInfotext(swInfotext: SWInfotext) - fun injectSWItem(swItem: SWItem) - fun injectSWPlugin(swPlugin: SWPlugin) - fun injectSWRadioButton(swRadioButton: SWRadioButton) - fun injectSWScreen(swScreen: SWScreen) - fun injectSWEventListener(swEventListener: SWEventListener) - - fun injectProfile(profile: Profile) - fun injectGlucoseStatus(glucoseStatus: GlucoseStatus) - - fun injectGraphData(graphData: GraphData) - - //Medtronic - fun injectRileyLinkCommunicationManager(rileyLinkCommunicationManager: RileyLinkCommunicationManager) - fun injectMedtronicCommunicationManager(medtronicCommunicationManager: MedtronicCommunicationManager) - fun injectMedtronicUITask(medtronicUITask: MedtronicUITask) - fun injectServiceTask(serviceTask: ServiceTask) - fun injectPumpTask(pumpTask: PumpTask) - fun injectDiscoverGattServicesTask(discoverGattServicesTask: DiscoverGattServicesTask) - fun injectInitializePumpManagerTask(initializePumpManagerTask: InitializePumpManagerTask) - fun injectResetRileyLinkConfigurationTask(resetRileyLinkConfigurationTask: ResetRileyLinkConfigurationTask) - fun injectWakeAndTuneTask(wakeAndTuneTask: WakeAndTuneTask) - fun injectRadioResponse(radioResponse: RadioResponse) - fun injectRileyLinkBLE(rileyLinkBLE: RileyLinkBLE) - fun injectRFSpy(rfSpy: RFSpy) - fun injectSendAndListen(sendAndListen: SendAndListen) - fun injectSetPreamble(setPreamble: SetPreamble) - fun injectRadioPacket(radioPacket: RadioPacket) - @Component.Builder interface Builder { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 6d334aa3d4..871f88a503 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -131,180 +131,9 @@ open class AppModule { @Module interface AppBindings { - @ContributesAndroidInjector fun profileStoreInjector(): ProfileStore - - @ContributesAndroidInjector fun pumpEnactResultInjector(): PumpEnactResult - - @ContributesAndroidInjector fun apsResultInjector(): APSResult - @ContributesAndroidInjector fun determineBasalResultSMBInjector(): DetermineBasalResultSMB - @ContributesAndroidInjector fun determineBasalResultAMAInjector(): DetermineBasalResultAMA - - @ContributesAndroidInjector - fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS - - @ContributesAndroidInjector fun commandQueueInjector(): CommandQueue - @ContributesAndroidInjector fun commandBolusInjector(): CommandBolus - - @ContributesAndroidInjector - fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus - - @ContributesAndroidInjector fun commandCancelTempBasalInjector(): CommandCancelTempBasal - @ContributesAndroidInjector fun commandExtendedBolusInjector(): CommandExtendedBolus - - @ContributesAndroidInjector - fun commandInsightSetTBROverNotificationInjector(): CommandInsightSetTBROverNotification - - @ContributesAndroidInjector fun commandLoadEventsInjector(): CommandLoadEvents - @ContributesAndroidInjector fun commandLoadHistoryInjector(): CommandLoadHistory - @ContributesAndroidInjector fun commandLoadTDDsInjector(): CommandLoadTDDs - @ContributesAndroidInjector fun commandReadStatusInjector(): CommandReadStatus - @ContributesAndroidInjector fun commandSetProfileInjector(): CommandSetProfile - @ContributesAndroidInjector fun commandCommandSMBBolusInjector(): CommandSMBBolus - @ContributesAndroidInjector fun commandStartPumpInjector(): CommandStartPump - @ContributesAndroidInjector fun commandStopPumpInjector(): CommandStopPump - @ContributesAndroidInjector fun commandTempBasalAbsoluteInjector(): CommandTempBasalAbsolute - @ContributesAndroidInjector fun commandTempBasalPercentInjector(): CommandTempBasalPercent - @ContributesAndroidInjector fun commandSetUserSettingsInjector(): CommandSetUserSettings - - @ContributesAndroidInjector fun objectiveInjector(): Objective - @ContributesAndroidInjector fun objective0Injector(): Objective0 - @ContributesAndroidInjector fun objective1Injector(): Objective1 - @ContributesAndroidInjector fun objective2Injector(): Objective2 - @ContributesAndroidInjector fun objective3Injector(): Objective3 - @ContributesAndroidInjector fun objective4Injector(): Objective4 - @ContributesAndroidInjector fun objective5Injector(): Objective5 - @ContributesAndroidInjector fun objective6Injector(): Objective6 - @ContributesAndroidInjector fun objective7Injector(): Objective7 - @ContributesAndroidInjector fun objective8Injector(): Objective8 - @ContributesAndroidInjector fun objective9Injector(): Objective9 - @ContributesAndroidInjector fun objective10Injector(): Objective10 - - @ContributesAndroidInjector fun automationEventInjector(): AutomationEvent - - @ContributesAndroidInjector fun triggerInjector(): Trigger - @ContributesAndroidInjector fun triggerAutosensValueInjector(): TriggerAutosensValue - @ContributesAndroidInjector fun triggerBgInjector(): TriggerBg - @ContributesAndroidInjector fun triggerBolusAgoInjector(): TriggerBolusAgo - @ContributesAndroidInjector fun triggerCOBInjector(): TriggerCOB - @ContributesAndroidInjector fun triggerConnectorInjector(): TriggerConnector - @ContributesAndroidInjector fun triggerDeltaInjector(): TriggerDelta - @ContributesAndroidInjector fun triggerDummyInjector(): TriggerDummy - @ContributesAndroidInjector fun triggerIobInjector(): TriggerIob - @ContributesAndroidInjector fun triggerLocationInjector(): TriggerLocation - @ContributesAndroidInjector fun triggerProfilePercentInjector(): TriggerProfilePercent - - @ContributesAndroidInjector - fun triggerPumpLastConnectionInjector(): TriggerPumpLastConnection - - @ContributesAndroidInjector fun triggerBTDeviceInjector(): TriggerBTDevice - @ContributesAndroidInjector fun triggerRecurringTimeInjector(): TriggerRecurringTime - @ContributesAndroidInjector fun triggerTempTargetInjector(): TriggerTempTarget - @ContributesAndroidInjector fun triggerTime(): TriggerTime - @ContributesAndroidInjector fun triggerTimeRangeInjector(): TriggerTimeRange - @ContributesAndroidInjector fun triggerWifiSsidInjector(): TriggerWifiSsid - - @ContributesAndroidInjector fun actionInjector(): Action - @ContributesAndroidInjector fun actionLoopDisableInjector(): ActionLoopDisable - @ContributesAndroidInjector fun actionLoopEnableInjector(): ActionLoopEnable - @ContributesAndroidInjector fun actionLoopResumeInjector(): ActionLoopResume - @ContributesAndroidInjector fun actionLoopSuspendInjector(): ActionLoopSuspend - @ContributesAndroidInjector fun actionNotificationInjector(): ActionNotification - @ContributesAndroidInjector fun actionProfileSwitchInjector(): ActionProfileSwitch - - @ContributesAndroidInjector - fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent - - @ContributesAndroidInjector fun actionSendSMSInjector(): ActionSendSMS - @ContributesAndroidInjector fun actionStartTempTargetInjector(): ActionStartTempTarget - @ContributesAndroidInjector fun actionStopTempTargetInjector(): ActionStopTempTarget - @ContributesAndroidInjector fun actionDummyInjector(): ActionDummy - - @ContributesAndroidInjector fun elementInjector(): Element - @ContributesAndroidInjector fun inputBgInjector(): InputBg - @ContributesAndroidInjector fun inputButtonInjector(): InputButton - @ContributesAndroidInjector fun comparatorInjector(): Comparator - @ContributesAndroidInjector fun comparatorConnectInjector(): ComparatorConnect - @ContributesAndroidInjector fun comparatorExistsInjector(): ComparatorExists - @ContributesAndroidInjector fun inputDateTimeInjector(): InputDateTime - @ContributesAndroidInjector fun inputDeltaInjector(): InputDelta - @ContributesAndroidInjector fun inputDoubleInjector(): InputDouble - @ContributesAndroidInjector fun inputDropdownMenuInjector(): InputDropdownMenu - @ContributesAndroidInjector fun inputDurationInjector(): InputDuration - @ContributesAndroidInjector fun inputInsulinInjector(): InputInsulin - @ContributesAndroidInjector fun inputLocationModeInjector(): InputLocationMode - @ContributesAndroidInjector fun inputPercentInjector(): InputPercent - @ContributesAndroidInjector fun inputProfileNameInjector(): InputProfileName - @ContributesAndroidInjector fun inputStringInjector(): InputString - @ContributesAndroidInjector fun inputTempTargetInjector(): InputTempTarget - @ContributesAndroidInjector fun inputTimeRangeInjector(): InputTimeRange - @ContributesAndroidInjector fun inputTimeInjector(): InputTime - @ContributesAndroidInjector fun inputWeekDayInjector(): InputWeekDay - @ContributesAndroidInjector fun labelWithElementInjector(): LabelWithElement - @ContributesAndroidInjector fun staticLabelInjector(): StaticLabel - - @ContributesAndroidInjector fun autosensDataInjector(): AutosensData - @ContributesAndroidInjector fun iobCobThreadInjector(): IobCobThread - @ContributesAndroidInjector fun iobCobOref1ThreadInjector(): IobCobOref1Thread - - @ContributesAndroidInjector fun bgReadingInjector(): BgReading - @ContributesAndroidInjector fun treatmentInjector(): Treatment - @ContributesAndroidInjector fun profileSwitchInjector(): ProfileSwitch - @ContributesAndroidInjector fun temporaryBasalInjector(): TemporaryBasal - @ContributesAndroidInjector fun careportalEventInjector(): CareportalEvent - - @ContributesAndroidInjector fun notificationWithActionInjector(): NotificationWithAction - - @ContributesAndroidInjector fun loggerCallbackInjector(): LoggerCallback - @ContributesAndroidInjector fun loggerBolusWizard(): BolusWizard - @ContributesAndroidInjector fun loggerQuickWizardEntry(): QuickWizardEntry - - @ContributesAndroidInjector fun authRequestInjector(): AuthRequest - - @ContributesAndroidInjector fun swBreakInjector(): SWBreak - @ContributesAndroidInjector fun swButtonInjector(): SWButton - @ContributesAndroidInjector fun swEditNumberWithUnitsInjector(): SWEditNumberWithUnits - @ContributesAndroidInjector fun swEditStringInjector(): SWEditString - @ContributesAndroidInjector fun swEditEncryptedPasswordInjector(): SWEditEncryptedPassword - @ContributesAndroidInjector fun swEditUrlInjector(): SWEditUrl - @ContributesAndroidInjector fun swFragmentInjector(): SWFragment - @ContributesAndroidInjector fun swHtmlLinkInjector(): SWHtmlLink - @ContributesAndroidInjector fun swInfotextInjector(): SWInfotext - @ContributesAndroidInjector fun swItemInjector(): SWItem - @ContributesAndroidInjector fun swPluginInjector(): SWPlugin - @ContributesAndroidInjector fun swRadioButtonInjector(): SWRadioButton - @ContributesAndroidInjector fun swScreenInjector(): SWScreen - @ContributesAndroidInjector fun swEventListenerInjector(): SWEventListener - - @ContributesAndroidInjector fun profileInjector(): Profile - @ContributesAndroidInjector fun glucoseStatusInjector(): GlucoseStatus - - @ContributesAndroidInjector fun graphDataInjector(): GraphData - - @ContributesAndroidInjector fun cryptoUtilInjector(): CryptoUtil - @ContributesAndroidInjector fun importExportPrefsInjector(): ImportExportPrefs - @ContributesAndroidInjector fun encryptedPrefsFormatInjector(): EncryptedPrefsFormat - @ContributesAndroidInjector fun classicPrefsFormatInjector(): ClassicPrefsFormat - @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector - // Medtronic - @ContributesAndroidInjector fun rileyLinkCommunicationManagerProvider(): RileyLinkCommunicationManager - @ContributesAndroidInjector fun medtronicCommunicationManagerProvider(): MedtronicCommunicationManager - @ContributesAndroidInjector fun medtronicUITaskProvider(): MedtronicUITask - @ContributesAndroidInjector fun serviceTaskProvider(): ServiceTask - @ContributesAndroidInjector fun pumpTaskProvider(): PumpTask - @ContributesAndroidInjector fun discoverGattServicesTaskProvider(): DiscoverGattServicesTask - @ContributesAndroidInjector fun initializePumpManagerTaskProvider(): InitializePumpManagerTask - @ContributesAndroidInjector fun resetRileyLinkConfigurationTaskProvider(): ResetRileyLinkConfigurationTask - @ContributesAndroidInjector fun wakeAndTuneTaskProvider(): WakeAndTuneTask - @ContributesAndroidInjector fun radioResponseProvider(): RadioResponse - @ContributesAndroidInjector fun rileyLinkBLEProvider(): RileyLinkBLE - @ContributesAndroidInjector fun rfSpyProvider(): RFSpy - @ContributesAndroidInjector fun sendAndListenProvider(): SendAndListen - @ContributesAndroidInjector fun setPreambleProvider(): SetPreamble - @ContributesAndroidInjector fun radioPacketProvider(): RadioPacket - @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AutomationModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AutomationModule.kt new file mode 100644 index 0000000000..bf54732d93 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AutomationModule.kt @@ -0,0 +1,71 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.general.automation.AutomationEvent +import info.nightscout.androidaps.plugins.general.automation.actions.* +import info.nightscout.androidaps.plugins.general.automation.elements.* +import info.nightscout.androidaps.plugins.general.automation.triggers.* +import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.queue.commands.* + +@Module +@Suppress("unused") +abstract class AutomationModule { + @ContributesAndroidInjector abstract fun automationEventInjector(): AutomationEvent + + @ContributesAndroidInjector abstract fun triggerInjector(): Trigger + @ContributesAndroidInjector abstract fun triggerAutosensValueInjector(): TriggerAutosensValue + @ContributesAndroidInjector abstract fun triggerBgInjector(): TriggerBg + @ContributesAndroidInjector abstract fun triggerBolusAgoInjector(): TriggerBolusAgo + @ContributesAndroidInjector abstract fun triggerCOBInjector(): TriggerCOB + @ContributesAndroidInjector abstract fun triggerConnectorInjector(): TriggerConnector + @ContributesAndroidInjector abstract fun triggerDeltaInjector(): TriggerDelta + @ContributesAndroidInjector abstract fun triggerDummyInjector(): TriggerDummy + @ContributesAndroidInjector abstract fun triggerIobInjector(): TriggerIob + @ContributesAndroidInjector abstract fun triggerLocationInjector(): TriggerLocation + @ContributesAndroidInjector abstract fun triggerProfilePercentInjector(): TriggerProfilePercent + @ContributesAndroidInjector abstract fun triggerPumpLastConnectionInjector(): TriggerPumpLastConnection + @ContributesAndroidInjector abstract fun triggerBTDeviceInjector(): TriggerBTDevice + @ContributesAndroidInjector abstract fun triggerRecurringTimeInjector(): TriggerRecurringTime + @ContributesAndroidInjector abstract fun triggerTempTargetInjector(): TriggerTempTarget + @ContributesAndroidInjector abstract fun triggerTime(): TriggerTime + @ContributesAndroidInjector abstract fun triggerTimeRangeInjector(): TriggerTimeRange + @ContributesAndroidInjector abstract fun triggerWifiSsidInjector(): TriggerWifiSsid + + @ContributesAndroidInjector abstract fun actionInjector(): Action + @ContributesAndroidInjector abstract fun actionLoopDisableInjector(): ActionLoopDisable + @ContributesAndroidInjector abstract fun actionLoopEnableInjector(): ActionLoopEnable + @ContributesAndroidInjector abstract fun actionLoopResumeInjector(): ActionLoopResume + @ContributesAndroidInjector abstract fun actionLoopSuspendInjector(): ActionLoopSuspend + @ContributesAndroidInjector abstract fun actionNotificationInjector(): ActionNotification + @ContributesAndroidInjector abstract fun actionProfileSwitchInjector(): ActionProfileSwitch + @ContributesAndroidInjector abstract fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent + @ContributesAndroidInjector abstract fun actionSendSMSInjector(): ActionSendSMS + @ContributesAndroidInjector abstract fun actionStartTempTargetInjector(): ActionStartTempTarget + @ContributesAndroidInjector abstract fun actionStopTempTargetInjector(): ActionStopTempTarget + @ContributesAndroidInjector abstract fun actionDummyInjector(): ActionDummy + + @ContributesAndroidInjector abstract fun elementInjector(): Element + @ContributesAndroidInjector abstract fun inputBgInjector(): InputBg + @ContributesAndroidInjector abstract fun inputButtonInjector(): InputButton + @ContributesAndroidInjector abstract fun comparatorInjector(): Comparator + @ContributesAndroidInjector abstract fun comparatorConnectInjector(): ComparatorConnect + @ContributesAndroidInjector abstract fun comparatorExistsInjector(): ComparatorExists + @ContributesAndroidInjector abstract fun inputDateTimeInjector(): InputDateTime + @ContributesAndroidInjector abstract fun inputDeltaInjector(): InputDelta + @ContributesAndroidInjector abstract fun inputDoubleInjector(): InputDouble + @ContributesAndroidInjector abstract fun inputDropdownMenuInjector(): InputDropdownMenu + @ContributesAndroidInjector abstract fun inputDurationInjector(): InputDuration + @ContributesAndroidInjector abstract fun inputInsulinInjector(): InputInsulin + @ContributesAndroidInjector abstract fun inputLocationModeInjector(): InputLocationMode + @ContributesAndroidInjector abstract fun inputPercentInjector(): InputPercent + @ContributesAndroidInjector abstract fun inputProfileNameInjector(): InputProfileName + @ContributesAndroidInjector abstract fun inputStringInjector(): InputString + @ContributesAndroidInjector abstract fun inputTempTargetInjector(): InputTempTarget + @ContributesAndroidInjector abstract fun inputTimeRangeInjector(): InputTimeRange + @ContributesAndroidInjector abstract fun inputTimeInjector(): InputTime + @ContributesAndroidInjector abstract fun inputWeekDayInjector(): InputWeekDay + @ContributesAndroidInjector abstract fun labelWithElementInjector(): LabelWithElement + @ContributesAndroidInjector abstract fun staticLabelInjector(): StaticLabel +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt new file mode 100644 index 0000000000..b0850bacc2 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.queue.commands.* + +@Module +@Suppress("unused") +abstract class CommandQueueModule { + + @ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResult + + @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue + @ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus + @ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus + @ContributesAndroidInjector abstract fun commandCancelTempBasalInjector(): CommandCancelTempBasal + @ContributesAndroidInjector abstract fun commandExtendedBolusInjector(): CommandExtendedBolus + @ContributesAndroidInjector abstract fun commandInsightSetTBROverNotificationInjector(): CommandInsightSetTBROverNotification + @ContributesAndroidInjector abstract fun commandLoadEventsInjector(): CommandLoadEvents + @ContributesAndroidInjector abstract fun commandLoadHistoryInjector(): CommandLoadHistory + @ContributesAndroidInjector abstract fun commandLoadTDDsInjector(): CommandLoadTDDs + @ContributesAndroidInjector abstract fun commandReadStatusInjector(): CommandReadStatus + @ContributesAndroidInjector abstract fun commandSetProfileInjector(): CommandSetProfile + @ContributesAndroidInjector abstract fun commandCommandSMBBolusInjector(): CommandSMBBolus + @ContributesAndroidInjector abstract fun commandStartPumpInjector(): CommandStartPump + @ContributesAndroidInjector abstract fun commandStopPumpInjector(): CommandStopPump + @ContributesAndroidInjector abstract fun commandTempBasalAbsoluteInjector(): CommandTempBasalAbsolute + @ContributesAndroidInjector abstract fun commandTempBasalPercentInjector(): CommandTempBasalPercent + @ContributesAndroidInjector abstract fun commandSetUserSettingsInjector(): CommandSetUserSettings +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt new file mode 100644 index 0000000000..7a3f5ee5e3 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.db.BgReading +import info.nightscout.androidaps.db.CareportalEvent +import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.db.TemporaryBasal +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus +import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.utils.wizard.BolusWizard +import info.nightscout.androidaps.utils.wizard.QuickWizardEntry + +@Module +@Suppress("unused") +abstract class DataClassesModule { + + @ContributesAndroidInjector abstract fun profileInjector(): Profile + @ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus + @ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore + + @ContributesAndroidInjector abstract fun bgReadingInjector(): BgReading + @ContributesAndroidInjector abstract fun treatmentInjector(): Treatment + @ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch + @ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal + @ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent + + @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard + @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt new file mode 100644 index 0000000000..7166906611 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt @@ -0,0 +1,40 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.general.automation.AutomationEvent +import info.nightscout.androidaps.plugins.general.automation.actions.* +import info.nightscout.androidaps.plugins.general.automation.elements.* +import info.nightscout.androidaps.plugins.general.automation.triggers.* +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* +import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager +import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask +import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.queue.commands.* + +@Module +@Suppress("unused") +abstract class MedtronicModule { + @ContributesAndroidInjector abstract fun rileyLinkCommunicationManagerProvider(): RileyLinkCommunicationManager + @ContributesAndroidInjector abstract fun medtronicCommunicationManagerProvider(): MedtronicCommunicationManager + @ContributesAndroidInjector abstract fun medtronicUITaskProvider(): MedtronicUITask + @ContributesAndroidInjector abstract fun serviceTaskProvider(): ServiceTask + @ContributesAndroidInjector abstract fun pumpTaskProvider(): PumpTask + @ContributesAndroidInjector abstract fun discoverGattServicesTaskProvider(): DiscoverGattServicesTask + @ContributesAndroidInjector abstract fun initializePumpManagerTaskProvider(): InitializePumpManagerTask + @ContributesAndroidInjector abstract fun resetRileyLinkConfigurationTaskProvider(): ResetRileyLinkConfigurationTask + @ContributesAndroidInjector abstract fun wakeAndTuneTaskProvider(): WakeAndTuneTask + @ContributesAndroidInjector abstract fun radioResponseProvider(): RadioResponse + @ContributesAndroidInjector abstract fun rileyLinkBLEProvider(): RileyLinkBLE + @ContributesAndroidInjector abstract fun rfSpyProvider(): RFSpy + @ContributesAndroidInjector abstract fun sendAndListenProvider(): SendAndListen + @ContributesAndroidInjector abstract fun setPreambleProvider(): SetPreamble + @ContributesAndroidInjector abstract fun radioPacketProvider(): RadioPacket +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ObjectivesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ObjectivesModule.kt new file mode 100644 index 0000000000..d9524092dc --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ObjectivesModule.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* + +@Module +@Suppress("unused") +abstract class ObjectivesModule { + + @ContributesAndroidInjector abstract fun objectiveInjector(): Objective + @ContributesAndroidInjector abstract fun objective0Injector(): Objective0 + @ContributesAndroidInjector abstract fun objective1Injector(): Objective1 + @ContributesAndroidInjector abstract fun objective2Injector(): Objective2 + @ContributesAndroidInjector abstract fun objective3Injector(): Objective3 + @ContributesAndroidInjector abstract fun objective4Injector(): Objective4 + @ContributesAndroidInjector abstract fun objective5Injector(): Objective5 + @ContributesAndroidInjector abstract fun objective6Injector(): Objective6 + @ContributesAndroidInjector abstract fun objective7Injector(): Objective7 + @ContributesAndroidInjector abstract fun objective8Injector(): Objective8 + @ContributesAndroidInjector abstract fun objective9Injector(): Objective9 + @ContributesAndroidInjector abstract fun objective10Injector(): Objective10 + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt new file mode 100644 index 0000000000..d022d3a726 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.aps.loop.APSResult +import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS +import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB +import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* +import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData +import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread + +@Module +@Suppress("unused") +abstract class OverviewModule { + @ContributesAndroidInjector abstract fun notificationWithActionInjector(): NotificationWithAction + + @ContributesAndroidInjector abstract fun graphDataInjector(): GraphData +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt new file mode 100644 index 0000000000..fa2df68ef0 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs +import info.nightscout.androidaps.plugins.general.maintenance.formats.ClassicPrefsFormat +import info.nightscout.androidaps.plugins.general.maintenance.formats.EncryptedPrefsFormat +import info.nightscout.androidaps.utils.CryptoUtil + +@Module +@Suppress("unused") +abstract class PreferencesModule { + + @ContributesAndroidInjector abstract fun cryptoUtilInjector(): CryptoUtil + @ContributesAndroidInjector abstract fun importExportPrefsInjector(): ImportExportPrefs + @ContributesAndroidInjector abstract fun encryptedPrefsFormatInjector(): EncryptedPrefsFormat + @ContributesAndroidInjector abstract fun classicPrefsFormatInjector(): ClassicPrefsFormat +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SMSModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SMSModule.kt new file mode 100644 index 0000000000..155015ea63 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SMSModule.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest + +@Module +@Suppress("unused") +abstract class SMSModule { + + @ContributesAndroidInjector abstract fun authRequestInjector(): AuthRequest +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt new file mode 100644 index 0000000000..66c99d5e17 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/WizardModule.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.setupwizard.SWEventListener +import info.nightscout.androidaps.setupwizard.SWScreen +import info.nightscout.androidaps.setupwizard.elements.* + +@Module +@Suppress("unused") +abstract class WizardModule { + + @ContributesAndroidInjector abstract fun swBreakInjector(): SWBreak + @ContributesAndroidInjector abstract fun swButtonInjector(): SWButton + @ContributesAndroidInjector abstract fun swEditNumberWithUnitsInjector(): SWEditNumberWithUnits + @ContributesAndroidInjector abstract fun swEditStringInjector(): SWEditString + @ContributesAndroidInjector abstract fun swEditEncryptedPasswordInjector(): SWEditEncryptedPassword + @ContributesAndroidInjector abstract fun swEditUrlInjector(): SWEditUrl + @ContributesAndroidInjector abstract fun swFragmentInjector(): SWFragment + @ContributesAndroidInjector abstract fun swHtmlLinkInjector(): SWHtmlLink + @ContributesAndroidInjector abstract fun swInfotextInjector(): SWInfotext + @ContributesAndroidInjector abstract fun swItemInjector(): SWItem + @ContributesAndroidInjector abstract fun swPluginInjector(): SWPlugin + @ContributesAndroidInjector abstract fun swRadioButtonInjector(): SWRadioButton + @ContributesAndroidInjector abstract fun swScreenInjector(): SWScreen + @ContributesAndroidInjector abstract fun swEventListenerInjector(): SWEventListener +} \ No newline at end of file From 18820441a4fc18d158d2bda7b8a8151469409d19 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 30 Apr 2020 10:55:10 +0200 Subject: [PATCH 03/16] remove some deprecated calls --- .../androidaps/db/DatabaseHelper.java | 17 +++++----- .../androidaps/db/ExtendedBolus.java | 32 +++++++++++++------ .../androidaps/db/TemporaryBasal.java | 26 +++++++-------- .../dependencyInjection/DataClassesModule.kt | 2 ++ .../plugins/configBuilder/PluginStore.kt | 18 +---------- .../pump/danaR/comm/MessageHashTableR.kt | 2 +- .../pump/danaR/comm/MsgStatusBolusExtended.kt | 10 +++--- .../danaR/services/DanaRExecutionService.java | 6 ++-- .../comm/MessageHashTableRKorean.kt | 2 +- .../services/DanaRKoreanExecutionService.java | 6 ++-- .../comm/DanaRS_Packet_APS_History_Events.kt | 2 +- .../pump/danaRv2/comm/MsgHistoryEvents_v2.kt | 2 +- .../pump/insight/LocalInsightPlugin.java | 6 ++-- .../medtronic/data/MedtronicHistoryData.java | 12 ++++--- .../plugins/pump/virtual/VirtualPumpPlugin.kt | 4 +-- .../plugins/treatments/TreatmentsPlugin.java | 4 +-- .../androidaps/services/DataService.java | 4 ++- .../plugins/pump/danaR/comm/DanaRTestBase.kt | 5 +++ .../danaR/comm/MsgStatusBolusExtendedTest.kt | 2 +- .../pump/danaRS/comm/DanaRSTestBase.kt | 4 ++- .../treatments/TreatmentsPluginTest.kt | 3 ++ 21 files changed, 94 insertions(+), 75 deletions(-) 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 661eaea15f..93807543f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -44,6 +44,7 @@ import info.nightscout.androidaps.events.EventReloadTempBasalData; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; @@ -999,7 +1000,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { try { if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal - ExtendedBolus extendedBolus = new ExtendedBolus() + ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance()) .source(Source.NIGHTSCOUT) .date(trJson.getLong("mills")) .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0) @@ -1014,7 +1015,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } createOrUpdate(extendedBolus); } else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end - ExtendedBolus extendedBolus = new ExtendedBolus(); + ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance()); extendedBolus.source = Source.NIGHTSCOUT; extendedBolus.date = trJson.getLong("mills"); extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; @@ -1029,7 +1030,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } createOrUpdate(extendedBolus); } else { - TemporaryBasal tempBasal = new TemporaryBasal() + TemporaryBasal tempBasal = new TemporaryBasal( MainApp.instance()) .date(trJson.getLong("mills")) .source(Source.NIGHTSCOUT) .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0); @@ -1288,7 +1289,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { */ public void createExtendedBolusFromJsonIfNotExists(JSONObject json) { - ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(json); + ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(MainApp.instance(), json); if (extendedBolus != null) createOrUpdate(extendedBolus); } @@ -1480,7 +1481,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List list = getDaoCareportalEvents().query(preparedQuery); CareportalEvent careportalEvent; if (list.size() == 0) { - careportalEvent = new CareportalEvent(); + careportalEvent = new CareportalEvent(MainApp.instance()); careportalEvent.source = Source.NIGHTSCOUT; if (L.isEnabled(L.DATABASE)) log.debug("Adding CareportalEvent record to database: " + trJson.toString()); @@ -1708,9 +1709,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } */ - public void createProfileSwitchFromJsonIfNotExists(JSONObject trJson) { + public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, JSONObject trJson) { try { - ProfileSwitch profileSwitch = new ProfileSwitch(MainApp.instance().injector); + ProfileSwitch profileSwitch = new ProfileSwitch(MainApp.instance()); profileSwitch.date = trJson.getLong("mills"); if (trJson.has("duration")) profileSwitch.durationInMinutes = trJson.getInt("duration"); @@ -1725,7 +1726,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (trJson.has("profileJson")) profileSwitch.profileJson = trJson.getString("profileJson"); else { - ProfileInterface profileInterface = PluginStore.Companion.getInstance().getActiveProfileInterface(); + ProfileInterface profileInterface = activePluginProvider.getActiveProfileInterface(); ProfileStore store = profileInterface.getProfile(); if (store != null) { Profile profile = store.getSpecificProfile(profileSwitch.profileName); diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java index cd26b960f5..15dd969e09 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java @@ -10,18 +10,20 @@ import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import org.json.JSONObject; -import org.slf4j.Logger; import java.util.Objects; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.Constants; +import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.configBuilder.PluginStore; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries; @@ -38,7 +40,10 @@ import info.nightscout.androidaps.utils.Round; @DatabaseTable(tableName = DatabaseHelper.DATABASE_EXTENDEDBOLUSES) public class ExtendedBolus implements Interval, DataPointWithLabelInterface { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE); + + @Inject ActivePluginProvider activePlugin; + + private HasAndroidInjector injector; @DatabaseField(id = true) public long date; @@ -64,10 +69,19 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { @DatabaseField public double dia = Constants.defaultDIA; + @Deprecated public ExtendedBolus() { + injector = MainApp.instance(); + injector.androidInjector().inject(this); } - public ExtendedBolus(long date) { + public ExtendedBolus(HasAndroidInjector injector) { + this.injector = injector; + injector.androidInjector().inject(this); + } + + public ExtendedBolus(HasAndroidInjector injector, long date) { + this(injector); this.date = date; } @@ -124,8 +138,8 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { pumpId = t.pumpId; } - public static ExtendedBolus createFromJson(JSONObject json) { - ExtendedBolus extendedBolus = new ExtendedBolus() + public static ExtendedBolus createFromJson(HasAndroidInjector injector, JSONObject json) { + ExtendedBolus extendedBolus = new ExtendedBolus(injector) .source(Source.NIGHTSCOUT) .date(JsonHelper.safeGetLong(json, "mills")) .durationInMinutes(JsonHelper.safeGetInt(json, "duration")) @@ -219,7 +233,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { public IobTotal iobCalc(long time) { IobTotal result = new IobTotal(time); - InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin(); + InsulinInterface insulinInterface = activePlugin.getActiveInsulin(); double realDuration = getDurationToTime(time); @@ -251,7 +265,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface { public IobTotal iobCalc(long time, Profile profile, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) { IobTotal result = new IobTotal(time); - InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin(); + InsulinInterface insulinInterface = activePlugin.getActiveInsulin(); double realDuration = getDurationToTime(time); double netBasalAmount = 0d; diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java index 3e5eb5a553..c65732b932 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java @@ -3,8 +3,6 @@ package info.nightscout.androidaps.db; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; -import org.slf4j.Logger; - import java.util.Objects; import javax.inject.Inject; @@ -15,17 +13,16 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.Interval; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.configBuilder.PluginStore; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 21.05.2017. @@ -33,9 +30,12 @@ import info.nightscout.androidaps.utils.SP; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS) public class TemporaryBasal implements Interval, DbObjectBase { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATABASE); + @Inject public AAPSLogger aapsLogger; @Inject public ProfileFunction profileFunction; + @Inject public ActivePluginProvider activePlugin; + @Inject public SP sp; + private HasAndroidInjector injector; @DatabaseField(id = true) @@ -246,12 +246,12 @@ public class TemporaryBasal implements Interval, DbObjectBase { public IobTotal iobCalc(long time, Profile profile) { if (isFakeExtended) { - log.error("iobCalc should only be called on Extended boluses separately"); + aapsLogger.error("iobCalc should only be called on Extended boluses separately"); return new IobTotal(time); } IobTotal result = new IobTotal(time); - InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin(); + InsulinInterface insulinInterface = activePlugin.getActiveInsulin(); int realDuration = getDurationToTime(time); double netBasalAmount = 0d; @@ -301,12 +301,12 @@ public class TemporaryBasal implements Interval, DbObjectBase { public IobTotal iobCalc(long time, Profile profile, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) { if (isFakeExtended) { - log.error("iobCalc should only be called on Extended boluses separately"); + aapsLogger.error("iobCalc should only be called on Extended boluses separately"); return new IobTotal(time); } IobTotal result = new IobTotal(time); - InsulinInterface insulinInterface = PluginStore.Companion.getInstance().getActiveInsulin(); + InsulinInterface insulinInterface = activePlugin.getActiveInsulin(); double realDuration = getDurationToTime(time); double netBasalAmount = 0d; @@ -452,7 +452,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { rate = absoluteRate; } - if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) { + if (sp.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && sp.getBoolean(R.string.key_danar_useextended, false)) { Profile profile = profileFunction.getProfile(); if (profile != null) { double basal = profile.getBasal(); @@ -483,7 +483,7 @@ public class TemporaryBasal implements Interval, DbObjectBase { rate = absoluteRate; } - if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) { + if (sp.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && sp.getBoolean(R.string.key_danar_useextended, false)) { double basal = profile.getBasal(); if (basal != 0) { return Math.round(rate * 100d / basal) + "% "; diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt index 7a3f5ee5e3..2eb498b0e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt @@ -6,6 +6,7 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.db.CareportalEvent +import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus @@ -26,6 +27,7 @@ abstract class DataClassesModule { @ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch @ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal @ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent + @ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt index 558e23df2b..35ba1db642 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt @@ -12,21 +12,6 @@ class PluginStore @Inject constructor( val aapsLogger: AAPSLogger ) : ActivePluginProvider { - // TODO remove - init { - pluginStore = this - } - - companion object { - var pluginStore: PluginStore? = null - - @Deprecated("Use dagger instead") - fun getInstance(): PluginStore { - checkNotNull(pluginStore) { "Accessing PluginStore before first instantiation" } - return pluginStore!! - } - } - lateinit var plugins: List<@JvmSuppressWildcards PluginBase> private var activeBgSource: BgSourceInterface? = null @@ -165,8 +150,7 @@ class PluginStore @Inject constructor( * @return */ private fun determineActivePlugin(pluginInterface: Class, pluginType: PluginType): T? { - val pluginsInCategory: ArrayList - pluginsInCategory = pluginStore!!.getSpecificPluginsListByInterface(pluginInterface) + val pluginsInCategory: ArrayList = getSpecificPluginsListByInterface(pluginInterface) return determineActivePlugin(pluginsInCategory, pluginType) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt index a0cb2ae0c8..a81408b381 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt @@ -39,7 +39,7 @@ class MessageHashTableR @Inject constructor( put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I + put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS // 0x0301 CMD_PUMPINIT_TIME_INFO diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt index 60055ad96e..448b45346a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.interfaces.ActivePluginProvider @@ -10,6 +11,7 @@ import info.nightscout.androidaps.utils.DateUtil import kotlin.math.ceil class MsgStatusBolusExtended( + private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, private val danaRPump: DanaRPump, private val activePlugin: ActivePluginProvider @@ -60,11 +62,11 @@ class MsgStatusBolusExtended( if (extendedBolus != null) { if (danaRPump.isExtendedInProgress) { if (extendedBolus.absoluteRate() != danaRPump.extendedBolusAbsoluteRate) { // Close current extended - val exStop = ExtendedBolus(danaRPump.extendedBolusStart - 1000) + val exStop = ExtendedBolus(injector, danaRPump.extendedBolusStart - 1000) exStop.source = Source.USER activePlugin.activeTreatments.addToHistoryExtendedBolus(exStop) // Create new - val newExtended = ExtendedBolus() + val newExtended = ExtendedBolus(injector) .date(danaRPump.extendedBolusStart) .insulin(danaRPump.extendedBolusAmount) .durationInMinutes(danaRPump.extendedBolusMinutes) @@ -73,13 +75,13 @@ class MsgStatusBolusExtended( } } else { // Close current temp basal - val exStop = ExtendedBolus(now) + val exStop = ExtendedBolus(injector, now) .source(Source.USER) activePlugin.activeTreatments.addToHistoryExtendedBolus(exStop) } } else { if (danaRPump.isExtendedInProgress) { // Create new - val newExtended = ExtendedBolus() + val newExtended = ExtendedBolus(injector) .date(danaRPump.extendedBolusStart) .insulin(danaRPump.extendedBolusAmount) .durationInMinutes(danaRPump.extendedBolusMinutes) 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 af5c6ef814..832826cf52 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 @@ -150,7 +150,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { MsgStatus statusMsg = new MsgStatus(aapsLogger, danaRPump); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(aapsLogger, danaRPump); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector); - MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin); + MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin); MsgCheckValue checkValue = new MsgCheckValue(aapsLogger, danaRPump, danaRPlugin); if (danaRPump.isNewPump()) { @@ -259,7 +259,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -268,7 +268,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(aapsLogger)); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt index 5e09f02a5d..7c8f5ca33b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt @@ -39,7 +39,7 @@ class MessageHashTableRKorean @Inject constructor( put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I + put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I put(MsgStatusBasic_k(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I put(MsgStatus_k(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS put(MsgInitConnStatusTime_k(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue)) // 0x0301 CMD_PUMPINIT_TIME_INFO 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 44fb504e79..0d18b1ecef 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 @@ -139,7 +139,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { //MsgStatus_k statusMsg = new MsgStatus_k(); MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(aapsLogger, danaRPump); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector); - MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin); + MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin); MsgCheckValue_k checkValue = new MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin); if (danaRPump.isNewPump()) { @@ -246,7 +246,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -255,7 +255,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(aapsLogger)); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); rxBus.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.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.kt index 03eb4ef64b..4681e68e92 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.kt @@ -78,7 +78,7 @@ open class DanaRS_Packet_APS_History_Events( val param1 = (intFromBuff(data, 7, 1) shl 8 and 0xFF00) + (intFromBuff(data, 8, 1) and 0xFF) val param2 = (intFromBuff(data, 9, 1) shl 8 and 0xFF00) + (intFromBuff(data, 10, 1) and 0xFF) val temporaryBasal = TemporaryBasal(injector).date(datetime).source(Source.PUMP).pumpId(datetime) - val extendedBolus = ExtendedBolus().date(datetime).source(Source.PUMP).pumpId(datetime) + val extendedBolus = ExtendedBolus(injector).date(datetime).source(Source.PUMP).pumpId(datetime) val status: String when (recordCode.toInt()) { DanaRPump.TEMPSTART -> { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt index 6c4e553208..0280b0a3e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt @@ -67,7 +67,7 @@ class MsgHistoryEvents_v2 constructor( .date(datetime) .source(Source.PUMP) .pumpId(datetime) - val extendedBolus = ExtendedBolus() + val extendedBolus = ExtendedBolus(injector) .date(datetime) .source(Source.PUMP) .pumpId(datetime) 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 0b3a513bf5..b91823a24a 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 @@ -817,7 +817,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, insightBolusID.timestamp = System.currentTimeMillis(); insightBolusID.pumpSerial = connectionService.getPumpSystemIdentification().getSerialNumber(); MainApp.getDbHelper().createOrUpdate(insightBolusID); - ExtendedBolus extendedBolus = new ExtendedBolus(); + ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); extendedBolus.date = insightBolusID.timestamp; extendedBolus.source = Source.PUMP; extendedBolus.durationInMinutes = durationInMinutes; @@ -1409,7 +1409,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, true); } if ((event.getBolusType() == BolusType.EXTENDED || event.getBolusType() == BolusType.MULTIWAVE)) { - ExtendedBolus extendedBolus = new ExtendedBolus(); + ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); extendedBolus.date = bolusID.timestamp; extendedBolus.source = Source.PUMP; extendedBolus.durationInMinutes = event.getDuration(); @@ -1452,7 +1452,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, MainApp.getDbHelper().delete(extendedBolus); } } else { - ExtendedBolus extendedBolus = new ExtendedBolus(); + ExtendedBolus extendedBolus = new ExtendedBolus(getInjector()); extendedBolus.date = bolusID.timestamp; extendedBolus.source = Source.PUMP; extendedBolus.durationInMinutes = event.getDuration(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index cfa3fdcc51..4d81eccc3a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java @@ -21,6 +21,7 @@ import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.db.CareportalEvent; @@ -73,6 +74,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton public class MedtronicHistoryData { + private final HasAndroidInjector injector; private final AAPSLogger aapsLogger; private final SP sp; private final ActivePluginProvider activePlugin; @@ -100,6 +102,7 @@ public class MedtronicHistoryData { @Inject public MedtronicHistoryData( + HasAndroidInjector injector, AAPSLogger aapsLogger, SP sp, ActivePluginProvider activePlugin, @@ -108,6 +111,7 @@ public class MedtronicHistoryData { ) { this.allHistory = new ArrayList<>(); + this.injector = injector; this.aapsLogger = aapsLogger; this.sp = sp; this.activePlugin = activePlugin; @@ -533,7 +537,7 @@ public class MedtronicHistoryData { if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); data.put("created_at", DateUtil.toISOString(date)); data.put("eventType", event); - CareportalEvent careportalEvent = new CareportalEvent(); + CareportalEvent careportalEvent = new CareportalEvent(injector); careportalEvent.date = date; careportalEvent.source = Source.USER; careportalEvent.eventType = event; @@ -954,7 +958,7 @@ public class MedtronicHistoryData { case Audio: case Extended: { - ExtendedBolus extendedBolus = new ExtendedBolus(); + ExtendedBolus extendedBolus = new ExtendedBolus(injector); extendedBolus.date = tryToGetByLocalTime(bolus.atechDateTime); extendedBolus.source = Source.PUMP; extendedBolus.insulin = bolusDTO.getDeliveredAmount(); @@ -1021,7 +1025,7 @@ public class MedtronicHistoryData { String operation = "editTBR"; if (temporaryBasalDb == null) { - temporaryBasalDb = new TemporaryBasal(); + temporaryBasalDb = new TemporaryBasal(injector); temporaryBasalDb.date = tryToGetByLocalTime(treatment.atechDateTime); operation = "addTBR"; @@ -1055,7 +1059,7 @@ public class MedtronicHistoryData { if (tempBasal == null) { // add - tempBasal = new TemporaryBasal(); + tempBasal = new TemporaryBasal(injector); tempBasal.date = tryToGetByLocalTime(tempBasalProcess.itemOne.atechDateTime); tempBasal.source = Source.PUMP; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 4854112fc3..007d585408 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -283,7 +283,7 @@ class VirtualPumpPlugin @Inject constructor( override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { val result = cancelExtendedBolus() if (!result.success) return result - val extendedBolus = ExtendedBolus() + val extendedBolus = ExtendedBolus(injector) .date(System.currentTimeMillis()) .insulin(insulin) .durationInMinutes(durationInMinutes) @@ -321,7 +321,7 @@ class VirtualPumpPlugin @Inject constructor( override fun cancelExtendedBolus(): PumpEnactResult { val result = PumpEnactResult(injector) if (treatmentsPlugin.isInHistoryExtendedBoluslInProgress) { - val exStop = ExtendedBolus(System.currentTimeMillis()) + val exStop = ExtendedBolus(injector, System.currentTimeMillis()) exStop.source = Source.USER treatmentsPlugin.addToHistoryExtendedBolus(exStop) } 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 f5a514b24e..460fa3eb23 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 @@ -423,7 +423,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface Profile profile = profileFunction.getProfile(e.date); if (profile == null) continue; if (truncate && e.end() > truncateTime) { - ExtendedBolus dummyExt = new ExtendedBolus(); + ExtendedBolus dummyExt = new ExtendedBolus(getInjector()); dummyExt.copyFrom(e); dummyExt.cutEndTo(truncateTime); calc = dummyExt.iobCalc(time); @@ -498,7 +498,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface Profile profile = profileFunction.getProfile(e.date); if (profile == null) continue; if (e.end() > truncateTime) { - ExtendedBolus dummyExt = new ExtendedBolus(); + ExtendedBolus dummyExt = new ExtendedBolus(getInjector()); dummyExt.copyFrom(e); dummyExt.cutEndTo(truncateTime); calc = dummyExt.iobCalc(time, profile, lastAutosensResult, exercise_mode, half_basal_exercise_target, isTempTarget); 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 9134cccb38..83891275a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -15,6 +15,7 @@ import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.events.EventNsTreatment; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.BundleLogger; import info.nightscout.androidaps.logging.LTag; @@ -51,6 +52,7 @@ public class DataService extends DaggerIntentService { @Inject TomatoPlugin tomatoPlugin; @Inject XdripPlugin xdripPlugin; @Inject NSProfilePlugin nsProfilePlugin; + @Inject ActivePluginProvider activePlugin; public DataService() { super("DataService"); @@ -208,7 +210,7 @@ public class DataService extends DaggerIntentService { } else if (eventType.equals(CareportalEvent.COMBOBOLUS)) { MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); } else if (eventType.equals(CareportalEvent.PROFILESWITCH)) { - MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(json); + MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePlugin, json); } else if (eventType.equals(CareportalEvent.SITECHANGE) || eventType.equals(CareportalEvent.INSULINCHANGE) || eventType.equals(CareportalEvent.SENSORCHANGE) || diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt index 5d9ca661d9..5a9107ccb0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt @@ -4,6 +4,7 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.db.TemporaryBasal +import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.utils.sharedPreferences.SP @@ -14,11 +15,15 @@ open class DanaRTestBase : TestBase() { @Mock lateinit var sp: SP @Mock lateinit var profileFunction: ProfileFunction + @Mock lateinit var activePluginProvider: ActivePluginProvider val injector = HasAndroidInjector { AndroidInjector { if (it is TemporaryBasal) { + it.aapsLogger = aapsLogger + it.activePlugin = activePluginProvider it.profileFunction = profileFunction + it.sp = sp } } } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtendedTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtendedTest.kt index d2e2336ac2..67403dfcd3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtendedTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtendedTest.kt @@ -18,7 +18,7 @@ class MsgStatusBolusExtendedTest : DanaRTestBase() { @Test fun runTest() { `when`(activePlugin.activeTreatments).thenReturn(treatmentsPlugin) - val packet = MsgStatusBolusExtended(aapsLogger, danaRPump, activePlugin) + val packet = MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin) // test message decoding val array = ByteArray(100) putByteToArray(array, 0, 1) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt index a79657bf64..1d82f58369 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSTestBase.kt @@ -4,7 +4,6 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Before @@ -17,7 +16,10 @@ open class DanaRSTestBase : TestBaseWithProfile() { val injector = HasAndroidInjector { AndroidInjector { if (it is TemporaryBasal) { + it.aapsLogger = aapsLogger + it.activePlugin = activePluginProvider it.profileFunction = profileFunction + it.sp = sp } } } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt index c97957daeb..8aa4ccad2d 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPluginTest.kt @@ -37,7 +37,10 @@ class TreatmentsPluginTest : TestBaseWithProfile() { val injector = HasAndroidInjector { AndroidInjector { if (it is TemporaryBasal) { + it.aapsLogger = aapsLogger + it.activePlugin = activePluginProvider it.profileFunction = profileFunction + it.sp = sp } } } From ddd58c37a38079e3e5be708be0547dd14f7bdde2 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 30 Apr 2020 17:56:40 +0200 Subject: [PATCH 04/16] move ongoing notification to extra class --- .../info/nightscout/androidaps/MainApp.java | 49 ------------------- .../persistentNotification/DummyService.kt | 10 ++-- .../PersistentNotificationPlugin.kt | 20 ++++---- .../androidaps/services/AlarmSoundService.kt | 8 +-- .../androidaps/services/LocationService.kt | 8 +-- .../androidNotification/NotificationHolder.kt | 42 ++++++++++++++++ 6 files changed, 65 insertions(+), 72 deletions(-) create mode 100644 app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index e39516934f..798185f68a 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -1,21 +1,13 @@ package info.nightscout.androidaps; -import android.app.Notification; -import android.app.NotificationManager; -import android.app.PendingIntent; import android.bluetooth.BluetoothDevice; -import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; -import androidx.annotation.ColorRes; import androidx.annotation.StringRes; -import androidx.core.app.NotificationCompat; -import androidx.core.app.TaskStackBuilder; -import androidx.core.content.ContextCompat; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.crashlytics.android.Crashlytics; @@ -68,10 +60,6 @@ public class MainApp extends DaggerApplication { static DatabaseHelper sDatabaseHelper = null; - private String CHANNEL_ID = "AndroidAPS-Ongoing"; // TODO: move to OngoingNotificationProvider (and dagger) - private int ONGOING_NOTIFICATION_ID = 4711; // TODO: move to OngoingNotificationProvider (and dagger) - private Notification notification; // TODO: move to OngoingNotificationProvider (and dagger) - @Inject PluginStore pluginStore; @Inject public HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; @@ -95,7 +83,6 @@ public class MainApp extends DaggerApplication { sInstance = this; sResources = getResources(); LocaleHelper.INSTANCE.update(this); - generateEmptyNotification(); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { @@ -230,42 +217,6 @@ public class MainApp extends DaggerApplication { return firebaseAnalytics; } - // global Notification has been moved to MainApp because PersistentNotificationPlugin is initialized too late - private void generateEmptyNotification() { - NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); - builder.setOngoing(true) - .setOnlyAlertOnce(true) - .setCategory(NotificationCompat.CATEGORY_STATUS) - .setSmallIcon(resourceHelper.getNotificationIcon()) - .setLargeIcon(resourceHelper.decodeResource(resourceHelper.getIcon())); - builder.setContentTitle(resourceHelper.gs(R.string.loading)); - Intent resultIntent = new Intent(this, MainApp.class); - TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); - stackBuilder.addParentStack(MainActivity.class); - stackBuilder.addNextIntent(resultIntent); - PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); - builder.setContentIntent(resultPendingIntent); - NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); - notification = builder.build(); - mNotificationManager.notify(ONGOING_NOTIFICATION_ID, notification); - } - - public int notificationId() { - return ONGOING_NOTIFICATION_ID; - } - - public String channelId() { - return CHANNEL_ID; - } - - public void setNotification(Notification notification) { - this.notification = notification; - } - - public Notification getNotification() { - return notification; - } - @Override public void onTerminate() { aapsLogger.debug(LTag.CORE, "onTerminate"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt index e83b31a1e2..8d4c605057 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt @@ -4,12 +4,12 @@ import android.app.Service import android.content.Intent import android.os.IBinder import dagger.android.DaggerService -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import javax.inject.Inject @@ -21,8 +21,8 @@ class DummyService : DaggerService() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var aapsLogger: AAPSLogger - @Inject lateinit var mainApp: MainApp @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var notificationHolder: NotificationHolder private val disposable = CompositeDisposable() @@ -32,14 +32,14 @@ class DummyService : DaggerService() { 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(mainApp.notificationId(), mainApp.notification) + startForeground(notificationHolder.notificationID, notificationHolder.notification) disposable.add(rxBus .toObservable(EventAppExit::class.java) .observeOn(Schedulers.io()) .subscribe({ aapsLogger.debug(LTag.CORE, "EventAppExit received") stopSelf() - }) { fabricPrivacy.logException(it) } + }) { fabricPrivacy::logException } ) } @@ -52,7 +52,7 @@ class DummyService : DaggerService() { override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) - startForeground(mainApp.notificationId(), mainApp.notification) + startForeground(notificationHolder.notificationID, notificationHolder.notification) return Service.START_STICKY } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index 991599ae46..cabbf3b1ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -12,7 +12,6 @@ import androidx.core.app.TaskStackBuilder import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainActivity -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* @@ -28,6 +27,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers @@ -45,7 +45,7 @@ class PersistentNotificationPlugin @Inject constructor( private var iobCobCalculatorPlugin: IobCobCalculatorPlugin, private var rxBus: RxBusWrapper, private var context: Context, - private var mainApp: MainApp + private var notificationHolder: NotificationHolder ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .neverVisible(true) @@ -109,7 +109,7 @@ class PersistentNotificationPlugin @Inject constructor( private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - val channel = NotificationChannel(mainApp.channelId(), mainApp.channelId() as CharSequence, NotificationManager.IMPORTANCE_HIGH) + val channel = NotificationChannel(notificationHolder.channelID, notificationHolder.channelID as CharSequence, NotificationManager.IMPORTANCE_HIGH) mNotificationManager.createNotificationChannel(channel) } } @@ -176,20 +176,20 @@ class PersistentNotificationPlugin @Inject constructor( val msgReadIntent = Intent() .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) .setAction(READ_ACTION) - .putExtra(CONVERSATION_ID, mainApp.notificationId()) + .putExtra(CONVERSATION_ID, notificationHolder.notificationID) .setPackage(PACKAGE) val msgReadPendingIntent = PendingIntent.getBroadcast(context, - mainApp.notificationId(), + notificationHolder.notificationID, msgReadIntent, PendingIntent.FLAG_UPDATE_CURRENT) val msgReplyIntent = Intent() .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) .setAction(REPLY_ACTION) - .putExtra(CONVERSATION_ID, mainApp.notificationId()) + .putExtra(CONVERSATION_ID, notificationHolder.notificationID) .setPackage(PACKAGE) val msgReplyPendingIntent = PendingIntent.getBroadcast( context, - mainApp.notificationId(), + notificationHolder.notificationID, msgReplyIntent, PendingIntent.FLAG_UPDATE_CURRENT) // Build a RemoteInput for receiving voice input from devices @@ -205,7 +205,7 @@ class PersistentNotificationPlugin @Inject constructor( } else { line1 = resourceHelper.gs(R.string.noprofileset) } - val builder = NotificationCompat.Builder(context, mainApp.channelId()) + val builder = NotificationCompat.Builder(context, notificationHolder.channelID) builder.setOngoing(true) builder.setOnlyAlertOnce(true) builder.setCategory(NotificationCompat.CATEGORY_STATUS) @@ -231,7 +231,7 @@ class PersistentNotificationPlugin @Inject constructor( builder.setContentIntent(resultPendingIntent) val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notification = builder.build() - mNotificationManager.notify(mainApp.notificationId(), notification) - mainApp.notification = notification + mNotificationManager.notify(notificationHolder.notificationID, notification) + notificationHolder.notification = notification } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt b/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt index 46b30339cc..0d261b5071 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt +++ b/app/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt @@ -6,17 +6,17 @@ import android.media.AudioManager import android.media.MediaPlayer import android.os.IBinder import dagger.android.DaggerService -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject class AlarmSoundService : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var mainApp: MainApp + @Inject lateinit var notificationHolder: NotificationHolder private var player: MediaPlayer? = null private var resourceId = R.raw.error @@ -26,11 +26,11 @@ class AlarmSoundService : DaggerService() { override fun onCreate() { super.onCreate() aapsLogger.debug(LTag.CORE, "onCreate") - startForeground(mainApp.notificationId(), mainApp.notification) + startForeground(notificationHolder.notificationID, notificationHolder.notification) } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { - startForeground(mainApp.notificationId(), mainApp.notification) + startForeground(notificationHolder.notificationID, notificationHolder.notification) player?.let { if (it.isPlaying) it.stop() } diff --git a/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt b/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt index f94a18c975..35374b47d7 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt +++ b/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt @@ -12,7 +12,6 @@ import android.os.IBinder import androidx.core.app.ActivityCompat import com.google.android.gms.location.LocationServices import dagger.android.DaggerService -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventLocationChange @@ -21,6 +20,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers @@ -32,7 +32,7 @@ class LocationService : DaggerService() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var mainApp: MainApp + @Inject lateinit var notificationHolder: NotificationHolder @Inject lateinit var lastLocationDataContainer: LastLocationDataContainer private val disposable = CompositeDisposable() @@ -73,13 +73,13 @@ class LocationService : DaggerService() { override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) - startForeground(mainApp.notificationId(), mainApp.notification) + startForeground(notificationHolder.notificationID, notificationHolder.notification) return Service.START_STICKY } override fun onCreate() { super.onCreate() - startForeground(mainApp.notificationId(), mainApp.notification) + startForeground(notificationHolder.notificationID, notificationHolder.notification) // Get last location once until we get regular update LocationServices.getFusedLocationProviderClient(this).lastLocation.addOnSuccessListener { diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt new file mode 100644 index 0000000000..9ec04d59d7 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt @@ -0,0 +1,42 @@ +package info.nightscout.androidaps.utils.androidNotification + +import android.app.Notification +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import androidx.core.app.NotificationCompat +import androidx.core.app.TaskStackBuilder +import info.nightscout.androidaps.MainActivity +import info.nightscout.androidaps.MainApp +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.resources.ResourceHelper +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class NotificationHolder @Inject constructor( + private val resourceHelper: ResourceHelper, + private val context: Context +) { + + val channelID = "AndroidAPS-Ongoing" + val notificationID = 4711 + var notification: Notification + + init { + val stackBuilder = TaskStackBuilder.create(context) + .addParentStack(MainActivity::class.java) + .addNextIntent(Intent(context, MainApp::class.java)) + val builder = NotificationCompat.Builder(context, channelID) + .setOngoing(true) + .setOnlyAlertOnce(true) + .setCategory(NotificationCompat.CATEGORY_STATUS) + .setSmallIcon(resourceHelper.getNotificationIcon()) + .setLargeIcon(resourceHelper.decodeResource(resourceHelper.getIcon())) + .setContentTitle(resourceHelper.gs(R.string.loading)) + .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) + notification = builder.build() + (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).notify(notificationID, notification) + } +} From 585b45fb97e30ca082a7a9cf21c9a64aee96e05f Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Thu, 30 Apr 2020 18:39:52 +0200 Subject: [PATCH 05/16] MainApp cleanup --- .../info/nightscout/androidaps/MainApp.java | 58 ------- .../nightscout/androidaps/data/Profile.java | 2 +- .../androidaps/db/ProfileSwitch.java | 2 +- .../nightscout/androidaps/db/TempTarget.java | 5 +- .../dependencyInjection/DataClassesModule.kt | 3 + .../actions/ActionStartTempTarget.kt | 2 +- .../plugins/pump/combo/ComboFragment.java | 5 +- .../pump/medtronic/MedtronicPumpPlugin.java | 10 -- .../plugins/treatments/TreatmentService.java | 149 ++++++++---------- .../plugins/treatments/TreatmentsPlugin.java | 2 +- .../TreatmentsTempTargetFragment.java | 5 +- .../androidaps/utils/FabricPrivacy.kt | 41 +++-- .../info/nightscout/androidaps/utils/SP.java | 2 +- .../androidaps/utils/stats/TddCalculator.kt | 2 +- .../comm/MedtronicHistoryDataUTest.java | 1 - 15 files changed, 112 insertions(+), 177 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 798185f68a..66acee4016 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -10,22 +10,16 @@ import android.net.wifi.WifiManager; import androidx.annotation.StringRes; import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import com.crashlytics.android.Crashlytics; -import com.google.firebase.analytics.FirebaseAnalytics; import com.j256.ormlite.android.apptools.OpenHelperManager; import net.danlew.android.joda.JodaTimeAndroid; -import org.json.JSONException; - import java.util.List; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.interfaces.PluginBase; @@ -33,7 +27,6 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.PluginStore; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.receivers.BTReceiver; @@ -41,35 +34,24 @@ import info.nightscout.androidaps.receivers.ChargingStateReceiver; import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.NetworkChangeReceiver; -import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.utils.ActivityMonitor; -import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.LocaleHelper; -import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.fabric.sdk.android.Fabric; public class MainApp extends DaggerApplication { static MainApp sInstance; private static Resources sResources; - static FirebaseAnalytics firebaseAnalytics; - static DatabaseHelper sDatabaseHelper = null; @Inject PluginStore pluginStore; - @Inject public HasAndroidInjector injector; @Inject AAPSLogger aapsLogger; - @Inject ReceiverStatusStore receiverStatusStore; @Inject ActivityMonitor activityMonitor; - @Inject FabricPrivacy fabricPrivacy; - @Inject ResourceHelper resourceHelper; @Inject VersionCheckerUtils versionCheckersUtils; @Inject SP sp; - @Inject ProfileFunction profileFunction; @Inject ConfigBuilderPlugin configBuilderPlugin; @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; @@ -93,19 +75,8 @@ public class MainApp extends DaggerApplication { aapsLogger.error("Uncaught exception crashing app", ex); }); - try { - if (fabricPrivacy.fabricEnabled()) { - Fabric.with(this, new Crashlytics()); - } - } catch (Exception e) { - aapsLogger.error("Error with Fabric init! " + e); - } - registerActivityLifecycleCallbacks(activityMonitor); - firebaseAnalytics = FirebaseAnalytics.getInstance(this); - firebaseAnalytics.setAnalyticsCollectionEnabled(!Boolean.getBoolean("disableFirebase") && fabricPrivacy.fabricEnabled()); - JodaTimeAndroid.init(this); aapsLogger.debug("Version: " + BuildConfig.VERSION_NAME); @@ -130,26 +101,6 @@ public class MainApp extends DaggerApplication { private void doMigrations() { - // guarantee that the unreachable threshold is at least 30 and of type String - // Added in 1.57 at 21.01.2018 - int unreachable_threshold = sp.getInt(R.string.key_pump_unreachable_threshold, 30); - sp.remove(R.string.key_pump_unreachable_threshold); - if (unreachable_threshold < 30) unreachable_threshold = 30; - sp.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold)); - - // 2.5 -> 2.6 - if (!sp.contains(R.string.key_units)) { - String newUnits = Constants.MGDL; - Profile p = profileFunction.getProfile(); - if (p != null && p.getData() != null && p.getData().has("units")) { - try { - newUnits = p.getData().getString("units"); - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - } - } - sp.putString(R.string.key_units, newUnits); - } } @Override @@ -199,11 +150,6 @@ public class MainApp extends DaggerApplication { return sResources.getString(id); } - @Deprecated - public static String gs(@StringRes int id, Object... args) { - return sResources.getString(id, args); - } - @Deprecated public static MainApp instance() { return sInstance; @@ -213,10 +159,6 @@ public class MainApp extends DaggerApplication { return sDatabaseHelper; } - public FirebaseAnalytics getFirebaseAnalytics() { - return firebaseAnalytics; - } - @Override public void onTerminate() { aapsLogger.debug(LTag.CORE, "onTerminate"); diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index f1204f8b72..0fcc0321c2 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -64,7 +64,7 @@ public class Profile { // Default constructor for DB public Profile() { - MainApp.instance().injector.androidInjector().inject(this); + MainApp.instance().androidInjector().inject(this); } protected Profile(HasAndroidInjector injector) { diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java index c16b34d96a..00c31586f4 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java +++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java @@ -76,7 +76,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface { @Inject public ResourceHelper resourceHelper; public ProfileSwitch() { - this.injector = MainApp.instance().injector; + this.injector = MainApp.instance(); injector.androidInjector().inject(this); } diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java index 9966425260..925d56e81d 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java +++ b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java @@ -17,6 +17,7 @@ import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; +import info.nightscout.androidaps.utils.resources.ResourceHelper; @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS) public class TempTarget implements Interval { @@ -195,10 +196,10 @@ public class TempTarget implements Interval { '}'; } - public String friendlyDescription(String units) { + public String friendlyDescription(String units, ResourceHelper resourceHelper) { return Profile.toTargetRangeString(low, high, Constants.MGDL, units) + units + - "@" + MainApp.gs(R.string.mins, durationInMinutes) + + "@" + resourceHelper.gs(R.string.mins, durationInMinutes) + (reason != null && !reason.equals("") ? "(" + reason + ")" : ""); } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt index 2eb498b0e7..99ffb12f25 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.db.ProfileSwitch import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @@ -29,6 +30,8 @@ abstract class DataClassesModule { @ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent @ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus + @ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService + @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt index d7f1b6a4e2..d0cb6b09e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt @@ -36,7 +36,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) { } override fun friendlyName(): Int = R.string.starttemptarget - override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units) + override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper) @DrawableRes override fun icon(): Int = R.drawable.icon_cp_cgm_target override fun doAction(callback: Callback) { 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 e44060d9ed..ad15a1e64f 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 @@ -37,6 +37,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene @Inject ResourceHelper resourceHelper; @Inject RxBusWrapper rxBus; @Inject SP sp; + @Inject FabricPrivacy fabricPrivacy; private CompositeDisposable disposable = new CompositeDisposable(); @@ -80,12 +81,12 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene disposable.add(rxBus .toObservable(EventComboPumpUpdateGUI.class) .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> updateGui(), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventQueueChanged.class) .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> updateGui(), fabricPrivacy::logException) ); 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 45ed524fdf..4bb5609f33 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 @@ -105,7 +105,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter private final RileyLinkServiceData rileyLinkServiceData; private final ServiceTaskExecutor serviceTaskExecutor; - protected static MedtronicPumpPlugin plugin = null; private RileyLinkMedtronicService rileyLinkMedtronicService; // variables for handling statuses and history @@ -149,7 +148,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy ); - this.plugin = this; this.rileyLinkUtil = rileyLinkUtil; this.medtronicUtil = medtronicUtil; @@ -194,14 +192,6 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter super.onStart(); } - @Deprecated - public static MedtronicPumpPlugin getPlugin() { - if (plugin == null) - throw new IllegalStateException("Plugin not injected jet"); - return plugin; - } - - @Override public void updatePreferenceSummary(@NotNull Preference pref) { super.updatePreferenceSummary(pref); 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 6e250bd851..cd81621252 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 @@ -18,8 +18,6 @@ import com.j256.ormlite.table.TableUtils; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.ArrayList; @@ -29,6 +27,9 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.Source; @@ -36,13 +37,12 @@ import info.nightscout.androidaps.events.Event; 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.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; -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; @@ -54,16 +54,22 @@ import io.reactivex.schedulers.Schedulers; */ public class TreatmentService extends OrmLiteBaseService { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.DATATREATMENTS); + + @Inject AAPSLogger aapsLogger; + @Inject FabricPrivacy fabricPrivacy; + @Inject RxBusWrapper rxBus; + @Inject MedtronicPumpPlugin medtronicPumpPlugin; + private CompositeDisposable disposable = new CompositeDisposable(); private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledTreatmentEventPost = null; - public TreatmentService() { + public TreatmentService(HasAndroidInjector injector) { + injector.androidInjector().inject(this); onCreate(); dbInitialize(); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventNsTreatment.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -75,7 +81,7 @@ public class TreatmentService extends OrmLiteBaseService { } else { // EventNsTreatment.REMOVE this.deleteNS(payload); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); } @@ -101,7 +107,7 @@ public class TreatmentService extends OrmLiteBaseService { try { return DaoManager.createDao(this.getConnectionSource(), Treatment.class); } catch (SQLException e) { - log.error("Cannot create Dao for Treatment.class"); + aapsLogger.error("Cannot create Dao for Treatment.class"); } return null; @@ -111,35 +117,33 @@ public class TreatmentService extends OrmLiteBaseService { public void onCreate() { super.onCreate(); try { - if (L.isEnabled(L.DATATREATMENTS)) - log.info("onCreate"); + aapsLogger.info(LTag.DATATREATMENTS, "onCreate"); TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); } catch (SQLException e) { - log.error("Can't create database", e); + aapsLogger.error("Can't create database", e); throw new RuntimeException(e); } } public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { if (oldVersion == 7 && newVersion == 8) { - log.debug("Upgrading database from v7 to v8"); + aapsLogger.debug("Upgrading database from v7 to v8"); try { TableUtils.dropTable(connectionSource, Treatment.class, true); TableUtils.createTableIfNotExists(connectionSource, Treatment.class); } catch (SQLException e) { - log.error("Can't create database", e); + aapsLogger.error("Can't create database", e); throw new RuntimeException(e); } } else if (oldVersion == 8 && newVersion == 9) { - log.debug("Upgrading database from v8 to v9"); + aapsLogger.debug("Upgrading database from v8 to v9"); try { getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` ADD COLUMN boluscalc STRING;"); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } else { - if (L.isEnabled(L.DATATREATMENTS)) - log.info("onUpgrade"); + aapsLogger.info(LTag.DATATREATMENTS, "onUpgrade"); // this.resetFood(); } } @@ -149,7 +153,7 @@ public class TreatmentService extends OrmLiteBaseService { try { getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` DROP COLUMN boluscalc STRING;"); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } } @@ -160,7 +164,7 @@ public class TreatmentService extends OrmLiteBaseService { TableUtils.createTableIfNotExists(this.getConnectionSource(), Treatment.class); DatabaseHelper.updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleTreatmentChange(null, true); } @@ -185,13 +189,11 @@ public class TreatmentService extends OrmLiteBaseService { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Firing EventReloadTreatmentData"); - RxBus.Companion.getINSTANCE().send(event); + aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventReloadTreatmentData"); + rxBus.send(event); if (DatabaseHelper.earliestDataChange != null) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Firing EventNewHistoryData"); - RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); + aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventNewHistoryData"); + rxBus.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); } DatabaseHelper.earliestDataChange = null; callback.setPost(null); @@ -212,13 +214,11 @@ public class TreatmentService extends OrmLiteBaseService { */ public void scheduleTreatmentChange(@Nullable final Treatment treatment, boolean runImmediately) { if (runImmediately) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Firing EventReloadTreatmentData"); - RxBus.Companion.getINSTANCE().send(new EventReloadTreatmentData(new EventTreatmentChange(treatment))); + aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventReloadTreatmentData"); + rxBus.send(new EventReloadTreatmentData(new EventTreatmentChange(treatment))); if (DatabaseHelper.earliestDataChange != null) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Firing EventNewHistoryData"); - RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); + aapsLogger.debug(LTag.DATATREATMENTS, "Firing EventNewHistoryData"); + rxBus.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange)); } DatabaseHelper.earliestDataChange = null; } else { @@ -240,7 +240,7 @@ public class TreatmentService extends OrmLiteBaseService { try { return this.getDao().queryForAll(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); @@ -266,16 +266,16 @@ public class TreatmentService extends OrmLiteBaseService { if (treatment != null) { if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicPumpPlugin.getPlugin().isEnabled()); + aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", medtronicPumpPlugin.isEnabled()); - if (!MedtronicPumpPlugin.getPlugin().isEnabled()) + if (!medtronicPumpPlugin.isEnabled()) createOrUpdate(treatment); else createOrUpdateMedtronic(treatment, true); } else - log.error("Date is null: " + treatment.toString()); + aapsLogger.error("Date is null: " + treatment.toString()); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -283,7 +283,7 @@ public class TreatmentService extends OrmLiteBaseService { // return true if new record is created public UpdateReturn createOrUpdate(Treatment treatment) { if (treatment != null && treatment.source == Source.NONE) { - log.error("Coder error: source is not set for treatment: " + treatment, new Exception()); + aapsLogger.error("Coder error: source is not set for treatment: " + treatment, new Exception()); //FabricPrivacy.logException(new Exception("Coder error: source is not set for treatment: " + treatment)); } try { @@ -298,8 +298,7 @@ public class TreatmentService extends OrmLiteBaseService { boolean sameSource = existingTreatment.source == treatment.source; if (!equalRePumpHistory) { // another treatment exists. Update it with the treatment coming from the pump - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); long oldDate = existingTreatment.date; //preserve carbs @@ -323,8 +322,7 @@ public class TreatmentService extends OrmLiteBaseService { boolean equalRePumpHistory = existingTreatment.equalsRePumpHistory(treatment); boolean sameSource = existingTreatment.source == treatment.source; long oldDate = existingTreatment.date; - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Pump record already found in database: " + existingTreatment.toString() + " wanting to add " + treatment.toString()); //preserve carbs if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { @@ -340,8 +338,7 @@ public class TreatmentService extends OrmLiteBaseService { return new UpdateReturn(equalRePumpHistory || sameSource, false); } getDao().create(treatment); - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, true); @@ -355,8 +352,7 @@ public class TreatmentService extends OrmLiteBaseService { getDao().delete(old); // need to delete/create because date may change too old.copyFrom(treatment); getDao().create(old); - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Updating record by date from: " + Source.getString(treatment.source) + " " + old.toString()); if (historyChange) { DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(old.date); @@ -364,8 +360,7 @@ public class TreatmentService extends OrmLiteBaseService { scheduleTreatmentChange(treatment, false); return new UpdateReturn(true, true); } - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Equal record by date from: " + Source.getString(treatment.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Equal record by date from: " + Source.getString(treatment.source) + " " + old.toString()); return new UpdateReturn(true, false); } // find by NS _id @@ -378,8 +373,7 @@ public class TreatmentService extends OrmLiteBaseService { getDao().delete(old); // need to delete/create because date may change too old.copyFrom(treatment); getDao().create(old); - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Updating record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); if (historyChange) { DatabaseHelper.updateEarliestDataChange(oldDate); DatabaseHelper.updateEarliestDataChange(old.date); @@ -387,28 +381,25 @@ public class TreatmentService extends OrmLiteBaseService { scheduleTreatmentChange(treatment, false); return new UpdateReturn(true, true); } - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Equal record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Equal record by _id from: " + Source.getString(treatment.source) + " " + old.toString()); return new UpdateReturn(true, false); } } getDao().create(treatment); - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment, false); return new UpdateReturn(true, true); } if (treatment.source == Source.USER) { getDao().create(treatment); - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, true); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new UpdateReturn(false, false); } @@ -417,7 +408,7 @@ public class TreatmentService extends OrmLiteBaseService { public UpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); + aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); try { treatment.date = DatabaseHelper.roundDateToSec(treatment.date); @@ -425,12 +416,11 @@ public class TreatmentService extends OrmLiteBaseService { Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date); if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment); + aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment); if (existingTreatment == null) { getDao().create(treatment); - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "New record from: " + Source.getString(treatment.source) + " " + treatment.toString()); DatabaseHelper.updateEarliestDataChange(treatment.date); scheduleTreatmentChange(treatment, true); return new UpdateReturn(true, true); @@ -438,7 +428,7 @@ public class TreatmentService extends OrmLiteBaseService { if (existingTreatment.date == treatment.date) { if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date==treatment.date)"); + aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date==treatment.date)"); // we will do update only, if entry changed if (!optionalTreatmentCopy(existingTreatment, treatment, fromNightScout)) { @@ -450,7 +440,7 @@ public class TreatmentService extends OrmLiteBaseService { return new UpdateReturn(true, false); } else { if (MedtronicHistoryData.doubleBolusDebug) - log.debug("DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date != treatment.date)"); + aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date != treatment.date)"); // date is different, we need to remove entry getDao().delete(existingTreatment); @@ -463,7 +453,7 @@ public class TreatmentService extends OrmLiteBaseService { } } catch (SQLException e) { - log.error("Unhandled SQL exception: {}", e.getMessage(), e); + aapsLogger.error("Unhandled SQL exception: {}", e.getMessage(), e); } return new UpdateReturn(false, false); } @@ -471,7 +461,7 @@ public class TreatmentService extends OrmLiteBaseService { private boolean optionalTreatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { - log.debug("optionalTreatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "optionalTreatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); boolean changed = false; @@ -537,7 +527,7 @@ public class TreatmentService extends OrmLiteBaseService { changed = true; } - log.debug("optionalTreatmentCopy [changed={}, newAfterChange={}]", changed, oldTreatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "optionalTreatmentCopy [changed={}, newAfterChange={}]", changed, oldTreatment.toString()); return changed; } @@ -551,7 +541,7 @@ public class TreatmentService extends OrmLiteBaseService { @Deprecated private void treatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { - log.debug("treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); if (fromNightScout) { @@ -574,7 +564,7 @@ public class TreatmentService extends OrmLiteBaseService { oldTreatment.copyFrom(newTreatment); } - log.debug("treatmentCopy [newAfterChange={}]", oldTreatment.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [newAfterChange={}]", oldTreatment.toString()); } @@ -595,7 +585,7 @@ public class TreatmentService extends OrmLiteBaseService { try { record = getDao().queryForId(date); } catch (SQLException ex) { - log.error("Error getting entry by id ({}", date); + aapsLogger.error("Error getting entry by id ({}", date); } return record; @@ -619,7 +609,7 @@ public class TreatmentService extends OrmLiteBaseService { if (result.isEmpty()) return null; if (result.size() > 1) - log.warn("Multiple records with the same pump id found (returning first one): " + result.toString()); + aapsLogger.warn(LTag.DATATREATMENTS, "Multiple records with the same pump id found (returning first one): " + result.toString()); return result.get(0); } catch (SQLException e) { throw new RuntimeException(e); @@ -642,12 +632,11 @@ public class TreatmentService extends OrmLiteBaseService { private void deleteByNSId(String _id) { Treatment stored = findByNSId(_id); if (stored != null) { - if (L.isEnabled(L.DATATREATMENTS)) - log.debug("Removing Treatment record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATATREATMENTS, "Removing Treatment record from database: " + stored.toString()); try { getDao().delete(stored); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } DatabaseHelper.updateEarliestDataChange(stored.date); this.scheduleTreatmentChange(stored, false); @@ -667,7 +656,7 @@ public class TreatmentService extends OrmLiteBaseService { DatabaseHelper.updateEarliestDataChange(treatment.date); this.scheduleTreatmentChange(treatment, true); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -676,7 +665,7 @@ public class TreatmentService extends OrmLiteBaseService { getDao().update(treatment); DatabaseHelper.updateEarliestDataChange(treatment.date); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleTreatmentChange(treatment, true); } @@ -705,7 +694,7 @@ public class TreatmentService extends OrmLiteBaseService { return trList.get(0); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -722,7 +711,7 @@ public class TreatmentService extends OrmLiteBaseService { treatments = daoTreatments.query(preparedQuery); return treatments; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -739,7 +728,7 @@ public class TreatmentService extends OrmLiteBaseService { treatments = daoTreatments.query(preparedQuery); return treatments; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } 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 460fa3eb23..51c602bfd2 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 @@ -122,7 +122,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override protected void onStart() { - this.service = new TreatmentService(); + this.service = new TreatmentService(getInjector()); initializeData(range()); super.onStart(); disposable.add(rxBus 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 32803f9cae..1d95d4306b 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 @@ -47,6 +47,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { @Inject RxBusWrapper rxBus; @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; + @Inject FabricPrivacy fabricPrivacy; private CompositeDisposable disposable = new CompositeDisposable(); @@ -139,7 +140,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { remove.setOnClickListener(v -> { final TempTarget tempTarget = (TempTarget) v.getTag(); OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.removerecord), - resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(profileFunction.getUnits()) + + resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(profileFunction.getUnits(), resourceHelper) + "\n" + DateUtil.dateAndTimeString(tempTarget.date), (dialog, id) -> { final String _id = tempTarget._id; @@ -189,7 +190,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { disposable.add(rxBus .toObservable(EventTempTargetChange.class) .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> updateGui(), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> updateGui(), fabricPrivacy::logException) ); updateGui(); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt index 41eb2464f5..a87fd3fef9 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.kt @@ -1,11 +1,11 @@ package info.nightscout.androidaps.utils +import android.content.Context import android.os.Bundle import com.crashlytics.android.Crashlytics import com.google.firebase.analytics.FirebaseAnalytics import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger @@ -13,6 +13,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin import info.nightscout.androidaps.utils.sharedPreferences.SP +import io.fabric.sdk.android.Fabric import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -24,16 +25,24 @@ import javax.inject.Singleton */ @Singleton class FabricPrivacy @Inject constructor( + context: Context, private val aapsLogger: AAPSLogger, private val sp: SP, private val constraintChecker: ConstraintChecker, - private val mainApp: MainApp, private val signatureVerifierPlugin: SignatureVerifierPlugin, private val activePlugin: ActivePluginProvider ) { + private var firebaseAnalytics: FirebaseAnalytics + init { instance = this + firebaseAnalytics = FirebaseAnalytics.getInstance(context) + firebaseAnalytics.setAnalyticsCollectionEnabled(!java.lang.Boolean.getBoolean("disableFirebase") && fabricEnabled()) + + if (fabricEnabled()) { + Fabric.with(context, Crashlytics()) + } } companion object { @@ -48,7 +57,7 @@ class FabricPrivacy @Inject constructor( fun logCustom(event: Bundle) { try { if (fabricEnabled()) { - mainApp.firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM, event) + firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM, event) } else { aapsLogger.debug(LTag.CORE, "Ignoring recently opted-out event: $event") } @@ -63,7 +72,7 @@ class FabricPrivacy @Inject constructor( fun logCustom(event: String) { try { if (fabricEnabled()) { - mainApp.firebaseAnalytics.logEvent(event, Bundle()) + firebaseAnalytics.logEvent(event, Bundle()) } else { aapsLogger.debug(LTag.CORE, "Ignoring recently opted-out event: $event") } @@ -125,19 +134,19 @@ class FabricPrivacy @Inject constructor( .replace(".com/", ":") .replace(".org/", ":") .replace(".net/", ":") - mainApp.firebaseAnalytics.setUserProperty("Mode", BuildConfig.APPLICATION_ID + "-" + closedLoopEnabled) - mainApp.firebaseAnalytics.setUserProperty("Language", sp.getString(R.string.key_language, Locale.getDefault().language)) - mainApp.firebaseAnalytics.setUserProperty("Version", BuildConfig.VERSION) - mainApp.firebaseAnalytics.setUserProperty("HEAD", BuildConfig.HEAD) - mainApp.firebaseAnalytics.setUserProperty("Remote", remote) + firebaseAnalytics.setUserProperty("Mode", BuildConfig.APPLICATION_ID + "-" + closedLoopEnabled) + firebaseAnalytics.setUserProperty("Language", sp.getString(R.string.key_language, Locale.getDefault().language)) + firebaseAnalytics.setUserProperty("Version", BuildConfig.VERSION) + firebaseAnalytics.setUserProperty("HEAD", BuildConfig.HEAD) + firebaseAnalytics.setUserProperty("Remote", remote) val hashes: List = signatureVerifierPlugin.shortHashes() - if (hashes.isNotEmpty()) mainApp.firebaseAnalytics.setUserProperty("Hash", hashes[0]) - activePlugin.activePump.let { mainApp.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } + if (hashes.isNotEmpty()) firebaseAnalytics.setUserProperty("Hash", hashes[0]) + activePlugin.activePump.let { firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } if (!Config.NSCLIENT && !Config.PUMPCONTROL) - activePlugin.activeAPS.let { mainApp.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } - activePlugin.activeBgSource.let { mainApp.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) } - mainApp.firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName) - activePlugin.activeSensitivity.let { mainApp.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } - activePlugin.activeInsulin.let { mainApp.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } + activePlugin.activeAPS.let { firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } + activePlugin.activeBgSource.let { firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) } + firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName) + activePlugin.activeSensitivity.let { firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } + activePlugin.activeInsulin.let { firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SP.java b/app/src/main/java/info/nightscout/androidaps/utils/SP.java index b3c581fee1..08ad3a8693 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SP.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/SP.java @@ -145,7 +145,7 @@ public class SP { @Deprecated static public void incInt(int resourceID) { - int value = SP.getInt(resourceID, 0) + 1; + int value = getInt(resourceID, 0) + 1; sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply(); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 0dc0cab7f3..906516d5ea 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -35,7 +35,7 @@ class TddCalculator @Inject constructor( ) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy) { init { - service = TreatmentService() // plugin is not started + service = TreatmentService(injector) // plugin is not started } fun calculate(days: Long): LongSparseArray { diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java index 4db64d90b1..824d9a3f1e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java @@ -11,7 +11,6 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistoryPage; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry; -import info.nightscout.androidaps.utils.SP; import static org.mockito.Mockito.when; //import uk.org.lidalia.slf4jtest.TestLogger; From 01e8934f7a9b9009d2155b43213d277eedb72d59 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 00:05:50 +1200 Subject: [PATCH 06/16] Add deterministic LGS function --- .../androidaps/plugins/aps/loop/LoopPlugin.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 fefd50f132..dcf32753a1 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 @@ -288,6 +288,21 @@ public class LoopPlugin extends PluginBase { return true; } + public boolean isLGS(){ + Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); + Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); + String APSmode = sp.getString(R.string.key_aps_mode, "open"); + Double LGSthreshold = 0d; + PumpInterface pump = activePlugin.getActivePump(); + boolean isLGS = false; + if (!isSuspended() && !pump.isSuspended()) + if (closedLoopEnabled.value()) + if ((MaxIOBallowed.equals(LGSthreshold)) || (APSmode.equals("lgs"))) + isLGS = true; + + return isLGS; + } + public boolean isSuperBolus() { if (loopSuspendedTill == 0) return false; From b54e1a0af365bcbe3ab37530634d70ba656c2f8d Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 00:07:24 +1200 Subject: [PATCH 07/16] Add LGS --- .../plugins/constraints/safety/SafetyPlugin.java | 6 +++++- .../plugins/general/overview/OverviewFragment.kt | 6 ++++-- .../java/info/nightscout/androidaps/utils/HardLimits.kt | 8 ++++++++ app/src/main/res/values/arrays.xml | 2 ++ app/src/main/res/values/colors.xml | 1 + app/src/main/res/values/strings.xml | 2 ++ 6 files changed, 22 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index a32b7233e1..dbb2b650ed 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -98,7 +98,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @NonNull @Override public Constraint isClosedLoopAllowed(@NonNull Constraint value) { String mode = sp.getString(R.string.key_aps_mode, "open"); - if (!mode.equals("closed")) + if ((mode.equals("open"))) value.set(getAapsLogger(), false, getResourceHelper().gs(R.string.closedmodedisabledinpreferences), this); if (!buildHelper.isEngineeringModeOrRelease()) { @@ -266,6 +266,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { @NonNull @Override public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) { double maxIobPref; + String apsmode = sp.getString(R.string.key_aps_mode, "open"); if (openAPSSMBPlugin.isEnabled(PluginType.APS)) maxIobPref = sp.getDouble(R.string.key_openapssmb_max_iob, 3d); else @@ -276,6 +277,9 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobAMA(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobAMA(), getResourceHelper().gs(R.string.hardlimit)), this); if (openAPSSMBPlugin.isEnabled(PluginType.APS)) maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobSMB(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobSMB(), getResourceHelper().gs(R.string.hardlimit)), this); + if ((apsmode.equals("lgs"))) + maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobLGS(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobLGS(), getResourceHelper().gs(R.string.lowglucosesuspend)), this); + return maxIob; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index cc3f881a13..fc1b80bd2a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -622,8 +622,10 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } loopPlugin.isEnabled(PluginType.LOOP) -> { - overview_apsmode?.text = if (closedLoopEnabled.value()) resourceHelper.gs(R.string.closedloop) else resourceHelper.gs(R.string.openloop) - overview_apsmode?.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) + val APSmode = sp.getString(R.string.key_aps_mode, "open") + val isLGS = loopPlugin.isLGS + overview_apsmode?.text = if (closedLoopEnabled.value()) if (isLGS) resourceHelper.gs(R.string.lgs) else resourceHelper.gs(R.string.closedloop) else resourceHelper.gs(R.string.openloop) + overview_apsmode?.setBackgroundColor(if (isLGS) resourceHelper.gc(R.color.ribbonUnusual) else resourceHelper.gc(R.color.ribbonDefault)) overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt index 48eba49112..5943da70a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt @@ -45,6 +45,10 @@ class HardLimits @Inject constructor( val MAXIOB_SMB = doubleArrayOf(3.0, 7.0, 12.0, 25.0) val MAXBASAL = doubleArrayOf(2.0, 5.0, 10.0, 12.0) + //LGS Hard limits + //No IOB at all + val MAXIOB_LGS = 0.0 + private fun loadAge(): Int { val sp_age = sp.getString(R.string.key_age, "") val age: Int @@ -68,6 +72,10 @@ class HardLimits @Inject constructor( return MAXIOB_SMB[loadAge()] } + fun maxIobLGS(): Double { + return MAXIOB_LGS + } + fun maxBasal(): Double { return MAXBASAL[loadAge()] } diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml index 04d78d3406..d11a14eefd 100644 --- a/app/src/main/res/values/arrays.xml +++ b/app/src/main/res/values/arrays.xml @@ -4,10 +4,12 @@ @string/closedloop @string/openloop + @string/lowglucosesuspend closed open + lgs diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index 8d1b977fea..d30a19a76e 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -86,6 +86,7 @@ #ff0400 #FFFFFF #303030 + #01017A #FFFFFF #2E2E2E diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b0f6821b69..45ed657b64 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -187,10 +187,12 @@ Closed Loop Open Loop + Low Glucose Suspend Loop Disabled Disable loop Enable loop + LGS New suggestion available Unsupported version of Nightscout LOOP DISABLED BY CONSTRAINTS From 560a081c7c3b5c0006ba078de7b2cc7437ba0bea Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 01:50:35 +1200 Subject: [PATCH 08/16] Inherit from HardLimits class --- .../androidaps/plugins/aps/loop/LoopPlugin.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) 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 dcf32753a1..93fcef0f0b 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 @@ -68,6 +68,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; +import info.nightscout.androidaps.utils.HardLimits; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @@ -88,6 +89,7 @@ public class LoopPlugin extends PluginBase { private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final ReceiverStatusStore receiverStatusStore; private final FabricPrivacy fabricPrivacy; + private final HardLimits hardLimits; private CompositeDisposable disposable = new CompositeDisposable(); @@ -132,7 +134,8 @@ public class LoopPlugin extends PluginBase { Lazy actionStringHandler, // TODO Adrian use RxBus instead of Lazy IobCobCalculatorPlugin iobCobCalculatorPlugin, ReceiverStatusStore receiverStatusStore, - FabricPrivacy fabricPrivacy + FabricPrivacy fabricPrivacy, + HardLimits hardLimits ) { super(new PluginDescription() .mainType(PluginType.LOOP) @@ -158,6 +161,7 @@ public class LoopPlugin extends PluginBase { this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.receiverStatusStore = receiverStatusStore; this.fabricPrivacy = fabricPrivacy; + this.hardLimits = hardLimits; loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L); isSuperBolus = sp.getBoolean("isSuperBolus", false); @@ -292,12 +296,12 @@ public class LoopPlugin extends PluginBase { Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); String APSmode = sp.getString(R.string.key_aps_mode, "open"); - Double LGSthreshold = 0d; PumpInterface pump = activePlugin.getActivePump(); boolean isLGS = false; + if (!isSuspended() && !pump.isSuspended()) if (closedLoopEnabled.value()) - if ((MaxIOBallowed.equals(LGSthreshold)) || (APSmode.equals("lgs"))) + if ((MaxIOBallowed.equals(hardLimits.getMAXIOB_LGS())) || (APSmode.equals("lgs"))) isLGS = true; return isLGS; From 96757145bf039a2a9d8a147f18c78a296358918d Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 01:54:08 +1200 Subject: [PATCH 09/16] Use auto getter method --- .../androidaps/plugins/constraints/safety/SafetyPlugin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index dbb2b650ed..ab325f1f0c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -278,7 +278,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { if (openAPSSMBPlugin.isEnabled(PluginType.APS)) maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobSMB(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobSMB(), getResourceHelper().gs(R.string.hardlimit)), this); if ((apsmode.equals("lgs"))) - maxIob.setIfSmaller(getAapsLogger(), hardLimits.maxIobLGS(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.maxIobLGS(), getResourceHelper().gs(R.string.lowglucosesuspend)), this); + maxIob.setIfSmaller(getAapsLogger(), hardLimits.getMAXIOB_LGS(), String.format(getResourceHelper().gs(R.string.limitingiob), hardLimits.getMAXIOB_LGS(), getResourceHelper().gs(R.string.lowglucosesuspend)), this); return maxIob; } From 9e2c3255e2568b3198d53542d46841191f494574 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 01:54:46 +1200 Subject: [PATCH 10/16] Remove not needed getter function --- .../main/java/info/nightscout/androidaps/utils/HardLimits.kt | 4 ---- 1 file changed, 4 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt index 5943da70a4..c9e2835ceb 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt @@ -72,10 +72,6 @@ class HardLimits @Inject constructor( return MAXIOB_SMB[loadAge()] } - fun maxIobLGS(): Double { - return MAXIOB_LGS - } - fun maxBasal(): Double { return MAXBASAL[loadAge()] } From 5c3876217813d76f4651ef74cf42227043274a34 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 01:55:11 +1200 Subject: [PATCH 11/16] Format code so its easier to read --- .../plugins/general/overview/OverviewFragment.kt | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index fc1b80bd2a..962e443c66 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -622,9 +622,16 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } loopPlugin.isEnabled(PluginType.LOOP) -> { - val APSmode = sp.getString(R.string.key_aps_mode, "open") val isLGS = loopPlugin.isLGS - overview_apsmode?.text = if (closedLoopEnabled.value()) if (isLGS) resourceHelper.gs(R.string.lgs) else resourceHelper.gs(R.string.closedloop) else resourceHelper.gs(R.string.openloop) + overview_apsmode?.text = + if (closedLoopEnabled.value()) + if (isLGS) + resourceHelper.gs(R.string.lgs) + else + resourceHelper.gs(R.string.closedloop) + else + resourceHelper.gs(R.string.openloop) + overview_apsmode?.setBackgroundColor(if (isLGS) resourceHelper.gc(R.color.ribbonUnusual) else resourceHelper.gc(R.color.ribbonDefault)) overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) } From 0bbdca3b4adf67a59145a98b9959c53abf6ed2c8 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 14:50:53 +1200 Subject: [PATCH 12/16] Add test --- .../plugins/constraints/safety/SafetyPluginTest.kt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt index 9da162a301..28261260a9 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt @@ -242,4 +242,14 @@ class SafetyPluginTest : TestBaseWithProfile() { """.trimIndent(), d.getReasons(aapsLogger)) Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) } + + @Test fun iobShouldBeZero() { + `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("lgs") + + // Apply IOB limits + var d = Constraint(hardLimits.MAXIOB_LGS) + d = safetyPlugin.applyMaxIOBConstraints(d) + Assert.assertEquals(0.0, d.value()!!) + Assert.assertEquals("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend", d.getMostLimitedReasons(aapsLogger)) + } } \ No newline at end of file From 4c2fdef71abb5c10315322ed44f699f1a34e6070 Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 19:13:16 +1200 Subject: [PATCH 13/16] Fix tests --- .../androidaps/plugins/aps/loop/LoopPluginTest.kt | 8 +++++++- .../plugins/constraints/safety/SafetyPluginTest.kt | 11 +---------- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt index dbfa209d11..40495880a3 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt @@ -19,6 +19,7 @@ import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.junit.Assert @@ -49,11 +50,15 @@ class LoopPluginTest : TestBase() { @Mock lateinit var fabricPrivacy: FabricPrivacy @Mock lateinit var receiverStatusStore: ReceiverStatusStore + private lateinit var hardLimits: HardLimits + lateinit var loopPlugin: LoopPlugin val injector = HasAndroidInjector { AndroidInjector { } } @Before fun prepareMock() { - loopPlugin = LoopPlugin(injector, aapsLogger, rxBus, sp, constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, treatmentsPlugin, virtualPumpPlugin, actionStringHandler, iobCobCalculatorPlugin, receiverStatusStore, fabricPrivacy) + hardLimits = HardLimits(aapsLogger, rxBus, sp, resourceHelper, context) + + loopPlugin = LoopPlugin(injector, aapsLogger, rxBus, sp, constraintChecker, resourceHelper, profileFunction, context, commandQueue, activePlugin, treatmentsPlugin, virtualPumpPlugin, actionStringHandler, iobCobCalculatorPlugin, receiverStatusStore, fabricPrivacy, hardLimits) `when`(activePlugin.getActivePump()).thenReturn(virtualPumpPlugin) } @@ -61,6 +66,7 @@ class LoopPluginTest : TestBase() { fun testPluginInterface() { `when`(resourceHelper.gs(R.string.loop)).thenReturn("Loop") `when`(resourceHelper.gs(R.string.loop_shortname)).thenReturn("LOOP") + `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed") val pumpDescription = PumpDescription() `when`(virtualPumpPlugin.pumpDescription).thenReturn(pumpDescription) Assert.assertEquals(LoopFragment::class.java.name, loopPlugin.pluginDescription.fragmentClass) diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt index 28261260a9..3e36b8bca0 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.kt @@ -230,6 +230,7 @@ class SafetyPluginTest : TestBaseWithProfile() { } @Test fun iobShouldBeLimited() { + `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed") `when`(sp.getDouble(R.string.key_openapsma_max_iob, 1.5)).thenReturn(1.5) `when`(sp.getString(R.string.key_age, "")).thenReturn("teenage") @@ -242,14 +243,4 @@ class SafetyPluginTest : TestBaseWithProfile() { """.trimIndent(), d.getReasons(aapsLogger)) Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons(aapsLogger)) } - - @Test fun iobShouldBeZero() { - `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("lgs") - - // Apply IOB limits - var d = Constraint(hardLimits.MAXIOB_LGS) - d = safetyPlugin.applyMaxIOBConstraints(d) - Assert.assertEquals(0.0, d.value()!!) - Assert.assertEquals("Safety: Limiting IOB to 0.0 U because of Low Glucose Suspend", d.getMostLimitedReasons(aapsLogger)) - } } \ No newline at end of file From 9efbbd3c1715fa1984d8fe7e71c4b105c29b30c4 Mon Sep 17 00:00:00 2001 From: Milos Kozak Date: Sat, 2 May 2020 10:49:55 +0200 Subject: [PATCH 14/16] clanup --- .../general/overview/StatusLightHandler.kt | 18 +++--- .../maintenance/ClassicPrefsFormatTest.kt | 24 ++++---- .../maintenance/EncryptedPrefsFormatTest.kt | 35 ++++++------ .../testing/mockers/AAPSMocker.java | 56 ------------------- .../testing/utils/SingleStringStorage.kt | 12 +--- 5 files changed, 42 insertions(+), 103 deletions(-) delete mode 100644 app/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt index 54bb6f3177..b05e1cb015 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt @@ -28,17 +28,17 @@ class StatusLightHandler @Inject constructor( */ fun updateStatusLights(careportal_canulaage: TextView?, careportal_insulinage: TextView?, careportal_reservoirlevel: TextView?, careportal_sensorage: TextView?, careportal_pbage: TextView?, careportal_batterylevel: TextView?) { val pump = activePlugin.activePump - handleAge(careportal_canulaage, "cage", CareportalEvent.SITECHANGE, R.string.key_statuslights_cage_warning, 48.0, R.string.key_statuslights_cage_critical, 72.0) - handleAge(careportal_insulinage, "iage", CareportalEvent.INSULINCHANGE, R.string.key_statuslights_iage_warning, 72.0, R.string.key_statuslights_iage_critical, 144.0) - handleAge(careportal_sensorage, "sage", CareportalEvent.SENSORCHANGE, R.string.key_statuslights_sage_warning, 216.0, R.string.key_statuslights_sage_critical, 240.0) - handleAge(careportal_pbage, "bage", CareportalEvent.PUMPBATTERYCHANGE, R.string.key_statuslights_bage_warning, 216.0, R.string.key_statuslights_bage_critical, 240.0) + handleAge(careportal_canulaage, CareportalEvent.SITECHANGE, R.string.key_statuslights_cage_warning, 48.0, R.string.key_statuslights_cage_critical, 72.0) + handleAge(careportal_insulinage, CareportalEvent.INSULINCHANGE, R.string.key_statuslights_iage_warning, 72.0, R.string.key_statuslights_iage_critical, 144.0) + handleAge(careportal_sensorage, CareportalEvent.SENSORCHANGE, R.string.key_statuslights_sage_warning, 216.0, R.string.key_statuslights_sage_critical, 240.0) + handleAge(careportal_pbage, CareportalEvent.PUMPBATTERYCHANGE, R.string.key_statuslights_bage_warning, 216.0, R.string.key_statuslights_bage_critical, 240.0) if (!Config.NSCLIENT) - handleLevel(careportal_reservoirlevel, R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, pump.reservoirLevel) + handleLevel(careportal_reservoirlevel, R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, pump.reservoirLevel, "U") if (!Config.NSCLIENT && pump.model() != PumpType.AccuChekCombo) - handleLevel(careportal_batterylevel, R.string.key_statuslights_bat_critical, 26.0, R.string.key_statuslights_bat_warning, 51.0, pump.batteryLevel.toDouble()) + handleLevel(careportal_batterylevel, R.string.key_statuslights_bat_critical, 26.0, R.string.key_statuslights_bat_warning, 51.0, pump.batteryLevel.toDouble(), "%") } - private fun handleAge(view: TextView?, nsSettingPlugin: String, eventName: String, @StringRes warnSettings: Int, defaultWarnThreshold: Double, @StringRes urgentSettings: Int, defaultUrgentThreshold: Double) { + private fun handleAge(view: TextView?, eventName: String, @StringRes warnSettings: Int, defaultWarnThreshold: Double, @StringRes urgentSettings: Int, defaultUrgentThreshold: Double) { val warn = sp.getDouble(warnSettings, defaultWarnThreshold) val urgent = sp.getDouble(urgentSettings, defaultUrgentThreshold) val careportalEvent = MainApp.getDbHelper().getLastCareportalEvent(eventName) @@ -50,11 +50,11 @@ class StatusLightHandler @Inject constructor( } } - private fun handleLevel(view: TextView?, criticalSetting: Int, criticalDefaultValue: Double, warnSetting: Int, warnDefaultValue: Double, level: Double) { + private fun handleLevel(view: TextView?, criticalSetting: Int, criticalDefaultValue: Double, warnSetting: Int, warnDefaultValue: Double, level: Double, units: String) { val resUrgent = sp.getDouble(criticalSetting, criticalDefaultValue) val resWarn = sp.getDouble(warnSetting, warnDefaultValue) @Suppress("SetTextI18n") - view?.text = " " + DecimalFormatter.to0Decimal(level) + view?.text = " " + DecimalFormatter.to0Decimal(level) + units warnColors.setColorInverse(view, level, resWarn, resUrgent) } } \ No newline at end of file diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/ClassicPrefsFormatTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/ClassicPrefsFormatTest.kt index 0755190d2b..f0a5c07491 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/ClassicPrefsFormatTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/ClassicPrefsFormatTest.kt @@ -1,45 +1,36 @@ package info.nightscout.androidaps.plugins.general.maintenance -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.plugins.general.maintenance.formats.ClassicPrefsFormat import info.nightscout.androidaps.plugins.general.maintenance.formats.Prefs -import info.nightscout.androidaps.testing.mockers.AAPSMocker import info.nightscout.androidaps.testing.utils.SingleStringStorage import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import org.hamcrest.CoreMatchers import org.junit.Assert -import org.junit.Before import org.junit.Test import org.junit.runner.RunWith -import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mock +import org.mockito.Mockito import org.mockito.Mockito.`when` import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner import java.io.File @RunWith(PowerMockRunner::class) -@PrepareForTest(AAPSMocker::class, MainApp::class, File::class) +@PrepareForTest(File::class) class ClassicPrefsFormatTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var sp: SP - @Before - fun mock() { - AAPSMocker.prepareMock() - AAPSMocker.resetMockedSharedPrefs() - } - @Test fun preferenceLoadingTest() { val test = "key1::val1\nkeyB::valB" val classicFormat = ClassicPrefsFormat(resourceHelper, SingleStringStorage(test)) - val prefs = classicFormat.loadPreferences(AAPSMocker.getMockedFile(), "") + val prefs = classicFormat.loadPreferences(getMockedFile(), "") Assert.assertThat(prefs.values.size, CoreMatchers.`is`(2)) Assert.assertThat(prefs.values["key1"], CoreMatchers.`is`("val1")) @@ -59,7 +50,14 @@ class ClassicPrefsFormatTest : TestBase() { mapOf() ) - classicFormat.savePreferences(AAPSMocker.getMockedFile(), prefs) + classicFormat.savePreferences(getMockedFile(), prefs) } + private fun getMockedFile(): File { + val file = Mockito.mock(File::class.java) + `when`(file.exists()).thenReturn(true) + `when`(file.canRead()).thenReturn(true) + `when`(file.canWrite()).thenReturn(true) + return file + } } diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/EncryptedPrefsFormatTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/EncryptedPrefsFormatTest.kt index 4537783ce4..fa52651e50 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/EncryptedPrefsFormatTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/EncryptedPrefsFormatTest.kt @@ -1,9 +1,7 @@ package info.nightscout.androidaps.plugins.general.maintenance -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.plugins.general.maintenance.formats.* -import info.nightscout.androidaps.testing.mockers.AAPSMocker import info.nightscout.androidaps.testing.utils.SingleStringStorage import info.nightscout.androidaps.utils.CryptoUtil import info.nightscout.androidaps.utils.assumeAES256isSupported @@ -24,19 +22,17 @@ import java.io.File @PowerMockIgnore("javax.crypto.*") @RunWith(PowerMockRunner::class) -@PrepareForTest(AAPSMocker::class, MainApp::class, File::class, ResourceHelper::class) +@PrepareForTest(File::class) class EncryptedPrefsFormatTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var sp: SP - var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger) + private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger) @Before fun mock() { - AAPSMocker.prepareMock() - AAPSMocker.resetMockedSharedPrefs() Mockito.`when`(resourceHelper.gs(ArgumentMatchers.anyInt())).thenReturn("mock translation") } @@ -56,7 +52,7 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - val prefs = encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "sikret") + val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") assumeAES256isSupported(cryptoUtil) @@ -82,7 +78,7 @@ class EncryptedPrefsFormatTest : TestBase() { PrefsMetadataKey.ENCRYPTION to PrefMetadata(EncryptedPrefsFormat.FORMAT_KEY_ENC, PrefsStatus.OK) ) ) - encryptedFormat.savePreferences(AAPSMocker.getMockedFile(), prefs, "sikret") + encryptedFormat.savePreferences(getMockedFile(), prefs, "sikret") aapsLogger.debug(storage.contents) } @@ -99,8 +95,8 @@ class EncryptedPrefsFormatTest : TestBase() { PrefsMetadataKey.ENCRYPTION to PrefMetadata(EncryptedPrefsFormat.FORMAT_KEY_ENC, PrefsStatus.OK) ) ) - encryptedFormat.savePreferences(AAPSMocker.getMockedFile(), prefsIn, "tajemnica") - val prefsOut = encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "tajemnica") + encryptedFormat.savePreferences(getMockedFile(), prefsIn, "tajemnica") + val prefsOut = encryptedFormat.loadPreferences(getMockedFile(), "tajemnica") assumeAES256isSupported(cryptoUtil) @@ -129,7 +125,7 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - val prefs = encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "it-is-NOT-right-secret") + val prefs = encryptedFormat.loadPreferences(getMockedFile(), "it-is-NOT-right-secret") Assert.assertThat(prefs.values.size, CoreMatchers.`is`(0)) @@ -156,7 +152,7 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - val prefs = encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "sikret") + val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") assumeAES256isSupported(cryptoUtil) @@ -183,7 +179,7 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - val prefs = encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "sikret") + val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") Assert.assertThat(prefs.values.size, CoreMatchers.`is`(0)) Assert.assertThat(prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status, CoreMatchers.`is`(PrefsStatus.ERROR)) @@ -198,7 +194,7 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - val prefs = encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "sikret") + val prefs = encryptedFormat.loadPreferences(getMockedFile(), "sikret") Assert.assertThat(prefs.values.size, CoreMatchers.`is`(0)) Assert.assertThat(prefs.metadata[PrefsMetadataKey.FILE_FORMAT]?.status, CoreMatchers.`is`(PrefsStatus.ERROR)) @@ -210,7 +206,7 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "sikret") + encryptedFormat.loadPreferences(getMockedFile(), "sikret") } @Test(expected = PrefFormatError::class) @@ -229,7 +225,14 @@ class EncryptedPrefsFormatTest : TestBase() { val storage = SingleStringStorage(frozenPrefs) val encryptedFormat = EncryptedPrefsFormat(resourceHelper, cryptoUtil, storage) - encryptedFormat.loadPreferences(AAPSMocker.getMockedFile(), "sikret") + encryptedFormat.loadPreferences(getMockedFile(), "sikret") } + private fun getMockedFile(): File { + val file = Mockito.mock(File::class.java) + Mockito.`when`(file.exists()).thenReturn(true) + Mockito.`when`(file.canRead()).thenReturn(true) + Mockito.`when`(file.canWrite()).thenReturn(true) + return file + } } diff --git a/app/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java b/app/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java deleted file mode 100644 index 3b495af147..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java +++ /dev/null @@ -1,56 +0,0 @@ -package info.nightscout.androidaps.testing.mockers; - -import android.content.Context; -import android.content.SharedPreferences; - -import org.mockito.ArgumentMatchers; -import org.mockito.invocation.InvocationOnMock; -import org.powermock.api.mockito.PowerMockito; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.powermock.api.mockito.PowerMockito.mockStatic; - -public class AAPSMocker { - - private static final Map mockedSharedPrefs = new HashMap<>(); - - public static void prepareMock() throws Exception { - Context mockedContext = mock(Context.class); - mockStatic(MainApp.class, InvocationOnMock::callRealMethod); - - PowerMockito.when(mockedContext, "getSharedPreferences", ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()).thenAnswer(invocation -> { - - final String key = invocation.getArgument(0); - if (mockedSharedPrefs.containsKey(key)) { - return mockedSharedPrefs.get(key); - } else { - SharedPreferencesMock newPrefs = new SharedPreferencesMock(); - mockedSharedPrefs.put(key, newPrefs); - return newPrefs; - } - }); - - resetMockedSharedPrefs(); - } - - public static void resetMockedSharedPrefs() { - mockedSharedPrefs.clear(); - } - - public static File getMockedFile() { - File file = mock(File.class); - when(file.exists()).thenReturn(true); - when(file.canRead()).thenReturn(true); - when(file.canWrite()).thenReturn(true); - return file; - } - -} diff --git a/app/src/test/java/info/nightscout/androidaps/testing/utils/SingleStringStorage.kt b/app/src/test/java/info/nightscout/androidaps/testing/utils/SingleStringStorage.kt index 8a3b06d56e..9991779066 100644 --- a/app/src/test/java/info/nightscout/androidaps/testing/utils/SingleStringStorage.kt +++ b/app/src/test/java/info/nightscout/androidaps/testing/utils/SingleStringStorage.kt @@ -3,20 +3,14 @@ package info.nightscout.androidaps.testing.utils import info.nightscout.androidaps.utils.storage.Storage import java.io.File -class SingleStringStorage : Storage { - - var contents: String = "" - - constructor(contents: String) { - this.contents = contents - } +class SingleStringStorage(var contents: String) : Storage { override fun getFileContents(file: File): String { return contents } - override fun putFileContents(file: File, putContents: String) { - contents = putContents + override fun putFileContents(file: File, contents: String) { + this.contents = contents } override fun toString(): String { From 40519b92a22dd849288dcea21cb8f0273399953a Mon Sep 17 00:00:00 2001 From: Tim Gunn <2896311+Tornado-Tim@users.noreply.github.com> Date: Sat, 2 May 2020 21:22:21 +1200 Subject: [PATCH 15/16] Fix further tests --- .../nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt index cd090dbde4..7698cc6844 100644 --- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.kt @@ -310,6 +310,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Test fun iobAMAShouldBeLimited() { // No limit by default + `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed") `when`(sp.getDouble(R.string.key_openapsma_max_iob, 1.5)).thenReturn(1.5) `when`(sp.getString(R.string.key_age, "")).thenReturn("teenage") openAPSAMAPlugin.setPluginEnabled(PluginType.APS, true) @@ -325,6 +326,7 @@ class ConstraintsCheckerTest : TestBaseWithProfile() { @Test fun iobSMBShouldBeLimited() { // No limit by default + `when`(sp.getString(R.string.key_aps_mode, "open")).thenReturn("closed") `when`(sp.getDouble(R.string.key_openapssmb_max_iob, 3.0)).thenReturn(3.0) `when`(sp.getString(R.string.key_age, "")).thenReturn("teenage") openAPSSMBPlugin.setPluginEnabled(PluginType.APS, true) From 9995e7448b596e79e9f71f4139152b96d3b499f8 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Tue, 28 Apr 2020 21:31:25 +0200 Subject: [PATCH 16/16] RandomBGPlugin - stay between min and max The sinus is in interval [-1,1]. If we shift it by one interval it would map it to 0 to 2 times the interval -> divide by two. --- .../info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index 27f3fd4b4c..bb008b383b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -79,7 +79,7 @@ class RandomBgPlugin @Inject constructor( val cal = GregorianCalendar() val currentMinute = cal.get(Calendar.MINUTE) + (cal.get(Calendar.HOUR_OF_DAY) % 2) * 60 - val bgMgdl = min + (max - min) + (max - min) * sin(currentMinute / 120.0 * 2 * PI) + val bgMgdl = min + ((max - min) + (max - min) * sin(currentMinute / 120.0 * 2 * PI))/2 val bgReading = BgReading() bgReading.value = bgMgdl