From 16f35870ebf749346406328a586655da9cce3306 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Tue, 23 Feb 2021 00:08:56 +0100 Subject: [PATCH 001/649] Minor renaming --- .../nightscout/androidaps/dependencyInjection/PluginsModule.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt index 02506911ec..e106245afb 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -160,7 +160,7 @@ abstract class PluginsModule { @PumpDriver @IntoMap @IntKey(155) - abstract fun bindOmnipodPumpPlugin(plugin: OmnipodErosPumpPlugin): PluginBase + abstract fun bindOmnipodErosPumpPlugin(plugin: OmnipodErosPumpPlugin): PluginBase @Binds @NotNSClient From 12ff37123dae0e13e6ed47ac3e3cb0eec95c8d0e Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Tue, 23 Feb 2021 01:26:57 +0100 Subject: [PATCH 002/649] Add and wire some Omnipod Dash UI --- .../dependencyInjection/AppComponent.kt | 2 + .../dependencyInjection/PluginsModule.kt | 7 + omnipod-dash/src/main/AndroidManifest.xml | 6 + .../omnipod/dash/OmnipodDashPumpPlugin.java | 18 ++- .../omnipod/dash/dagger/OmnipodDashModule.kt | 25 ++++ .../OmnipodDashWizardViewModelsModule.kt | 89 +++++++++++ .../dash/ui/DashPodManagementActivity.kt | 113 ++++++++++++++ .../dash/ui/OmnipodDashOverviewFragment.kt | 9 ++ .../DashPodActivationWizardActivity.kt | 5 + .../action/DashInitializePodViewModel.kt | 31 ++++ .../action/DashInsertCannulaViewModel.kt | 26 ++++ .../viewmodel/info/DashAttachPodViewModel.kt | 15 ++ .../info/DashPodActivatedViewModel.kt | 15 ++ .../info/DashStartPodActivationViewModel.kt | 15 ++ .../DashPodDeactivationWizardActivity.kt | 5 + .../action/DashDeactivatePodViewModel.kt | 23 +++ .../info/DashPodDeactivatedViewModel.kt | 16 ++ .../info/DashPodDiscardedViewModel.kt | 15 ++ .../info/DashStartPodDeactivationViewModel.kt | 15 ++ ...omnipod_dash_overview_bluetooth_status.xml | 70 +++++---- .../layout/omnipod_dash_pod_management.xml | 139 ++++++++++++++++++ omnipod-dash/src/main/res/values/strings.xml | 4 + .../omnipod/eros/OmnipodErosPumpPlugin.java | 6 +- .../omnipod/eros/dagger/OmnipodErosModule.kt | 18 +-- .../action/AcknowledgeAlertsAction.java | 8 +- .../action/AssignAddressAction.java | 6 +- .../communication/action/BolusAction.java | 8 +- .../action/CancelDeliveryAction.java | 6 +- .../action/ConfigureAlertsAction.java | 8 +- .../action/ConfigureBeepAction.java | 8 +- .../action/DeactivatePodAction.java | 6 +- .../action/GetPodInfoAction.java | 6 +- .../communication/action/GetStatusAction.java | 6 +- .../action/InsertCannulaAction.java | 6 +- .../communication/action/PrimeAction.java | 6 +- .../action/SetBasalScheduleAction.java | 6 +- .../action/SetTempBasalAction.java | 6 +- .../communication/action/SetupPodAction.java | 6 +- .../service/ExpirationReminderBuilder.java | 4 +- .../action/service/PrimeService.java | 8 +- ...eManager.java => ErosPodStateManager.java} | 4 +- .../eros/driver/manager/OmnipodManager.java | 4 +- .../eros/manager/AapsErosPodStateManager.java | 4 +- .../eros/manager/AapsOmnipodErosManager.java | 6 +- .../OmnipodRileyLinkCommunicationManager.java | 26 ++-- .../service/RileyLinkOmnipodService.java | 4 +- .../eros/ui/ErosPodManagementActivity.kt | 4 +- .../eros/ui/OmnipodErosOverviewFragment.kt | 4 +- .../omnipod/eros/util/AapsOmnipodUtil.java | 4 +- 49 files changed, 715 insertions(+), 136 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt create mode 100644 omnipod-dash/src/main/res/layout/omnipod_dash_pod_management.xml rename omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/{PodStateManager.java => ErosPodStateManager.java} (99%) 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 d431be7a6c..e1df8f6c34 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -15,6 +15,7 @@ import info.nightscout.androidaps.danars.di.InsightModule import info.nightscout.androidaps.database.DatabaseModule import info.nightscout.androidaps.plugins.pump.common.di.RileyLinkModule import info.nightscout.androidaps.plugins.pump.medtronic.di.MedtronicModule +import info.nightscout.androidaps.plugins.pump.omnipod.dash.dagger.OmnipodDashModule import info.nightscout.androidaps.plugins.pump.omnipod.eros.dagger.OmnipodErosModule import javax.inject.Singleton @@ -36,6 +37,7 @@ import javax.inject.Singleton WizardModule::class, RileyLinkModule::class, MedtronicModule::class, + OmnipodDashModule::class, OmnipodErosModule::class, APSModule::class, PreferencesModule::class, diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt index e106245afb..3d10603408 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -42,6 +42,7 @@ import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin +import info.nightscout.androidaps.plugins.pump.omnipod.dash.OmnipodDashPumpPlugin import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin @@ -162,6 +163,12 @@ abstract class PluginsModule { @IntKey(155) abstract fun bindOmnipodErosPumpPlugin(plugin: OmnipodErosPumpPlugin): PluginBase + @Binds + @PumpDriver + @IntoMap + @IntKey(156) + abstract fun bindOmnipodDashPumpPlugin(plugin: OmnipodDashPumpPlugin): PluginBase + @Binds @NotNSClient @IntoMap diff --git a/omnipod-dash/src/main/AndroidManifest.xml b/omnipod-dash/src/main/AndroidManifest.xml index 25a6e46f21..180d3b98ce 100644 --- a/omnipod-dash/src/main/AndroidManifest.xml +++ b/omnipod-dash/src/main/AndroidManifest.xml @@ -6,4 +6,10 @@ + + + + + + \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java index 5831caabde..628445b62b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java @@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash; import androidx.annotation.Nullable; +import com.google.gson.JsonObject; + import org.jetbrains.annotations.NotNull; import org.json.JSONObject; @@ -56,7 +58,7 @@ public class OmnipodDashPumpPlugin extends PumpPluginBase implements PumpInterfa } @Override public boolean isInitialized() { - return false; + return true; } @Override public boolean isSuspended() { @@ -64,7 +66,8 @@ public class OmnipodDashPumpPlugin extends PumpPluginBase implements PumpInterfa } @Override public boolean isBusy() { - return false; + // prevents the queue from executing + return true; } @Override public boolean isConnected() { @@ -100,15 +103,18 @@ public class OmnipodDashPumpPlugin extends PumpPluginBase implements PumpInterfa } @NotNull @Override public PumpEnactResult setNewBasalProfile(@NotNull Profile profile) { - return null; + // TODO + return new PumpEnactResult(getInjector()).success(true).enacted(true); } @Override public boolean isThisProfileSet(@NotNull Profile profile) { - return false; + // TODO + return true; } @Override public long lastDataTime() { - return 0; + // TODO + return System.currentTimeMillis(); } @Override public double getBaseBasalRate() { @@ -152,7 +158,7 @@ public class OmnipodDashPumpPlugin extends PumpPluginBase implements PumpInterfa } @NotNull @Override public JSONObject getJSONStatus(@NotNull Profile profile, @NotNull String profileName, @NotNull String version) { - return null; + return new JSONObject(); } @NotNull @Override public ManufacturerType manufacturer() { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index 285349495a..9a3e241e52 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -1,8 +1,33 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.dagger import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ActivityScope +import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodWizardModule +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.DashPodManagementActivity +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOverviewFragment +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.DashPodActivationWizardActivity +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.DashPodDeactivationWizardActivity @Module @Suppress("unused") abstract class OmnipodDashModule { + // ACTIVITIES + + @ContributesAndroidInjector + abstract fun contributesDashPodManagementActivity(): DashPodManagementActivity + + @ActivityScope + @ContributesAndroidInjector(modules = [OmnipodWizardModule::class, OmnipodDashWizardViewModelsModule::class]) + abstract fun contributesDashActivationWizardActivity(): DashPodActivationWizardActivity + + @ActivityScope + @ContributesAndroidInjector(modules = [OmnipodWizardModule::class, OmnipodDashWizardViewModelsModule::class]) + abstract fun contributesDashDeactivationWizardActivity(): DashPodDeactivationWizardActivity + + // FRAGMENTS + + @ContributesAndroidInjector + abstract fun contributesOmnipodDashOverviewFragment(): OmnipodDashOverviewFragment + } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt new file mode 100644 index 0000000000..1b1aaf6f13 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt @@ -0,0 +1,89 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.dagger + +import androidx.lifecycle.ViewModel +import dagger.Binds +import dagger.Module +import dagger.multibindings.IntoMap +import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodPluginQualifier +import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ViewModelKey +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info.AttachPodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info.PodActivatedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info.StartPodActivationViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.info.PodDeactivatedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.info.PodDiscardedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.info.StartPodDeactivationViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action.DashInitializePodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action.DashInsertCannulaViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.info.DashAttachPodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.info.DashPodActivatedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.info.DashStartPodActivationViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.action.DashDeactivatePodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.info.DashPodDeactivatedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.info.DashPodDiscardedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.info.DashStartPodDeactivationViewModel + +@Module +@Suppress("unused") +abstract class OmnipodDashWizardViewModelsModule { + // #### VIEW MODELS ############################################################################ + + // POD ACTIVATION + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(StartPodActivationViewModel::class) + internal abstract fun startPodActivationViewModel(viewModel: DashStartPodActivationViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(InitializePodViewModel::class) + internal abstract fun initializePodViewModel(viewModel: DashInitializePodViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(AttachPodViewModel::class) + internal abstract fun attachPodViewModel(viewModel: DashAttachPodViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(InsertCannulaViewModel::class) + internal abstract fun insertCannulaViewModel(viewModel: DashInsertCannulaViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(PodActivatedViewModel::class) + internal abstract fun podActivatedViewModel(viewModel: DashPodActivatedViewModel): ViewModel + + // POD DEACTIVATION + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(StartPodDeactivationViewModel::class) + internal abstract fun startPodDeactivationViewModel(viewModel: DashStartPodDeactivationViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(DeactivatePodViewModel::class) + internal abstract fun deactivatePodViewModel(viewModel: DashDeactivatePodViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(PodDeactivatedViewModel::class) + internal abstract fun podDeactivatedViewModel(viewModel: DashPodDeactivatedViewModel): ViewModel + + @Binds + @IntoMap + @OmnipodPluginQualifier + @ViewModelKey(PodDiscardedViewModel::class) + internal abstract fun podDiscardedViewModel(viewModel: DashPodDiscardedViewModel): ViewModel +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt new file mode 100644 index 0000000000..ac96ad394b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt @@ -0,0 +1,113 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.activities.NoSplashAppCompatActivity +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandPlayTestBeep +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.PodActivationWizardActivity +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashPodManagementBinding +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.DashPodActivationWizardActivity +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.DashPodDeactivationWizardActivity +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.queue.events.EventQueueChanged +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.alertDialogs.OKDialog +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.rxkotlin.plusAssign +import javax.inject.Inject + +/** + * Created by andy on 30/08/2019 + */ +class DashPodManagementActivity : NoSplashAppCompatActivity() { + + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var injector: HasAndroidInjector + @Inject lateinit var context: Context + @Inject lateinit var aapsSchedulers: AapsSchedulers + + private var disposables: CompositeDisposable = CompositeDisposable() + + private lateinit var binding: OmnipodDashPodManagementBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + + binding = OmnipodDashPodManagementBinding.inflate(layoutInflater) + setContentView(binding.root) + + binding.buttonActivatePod.setOnClickListener { + /* TODO determine type + val type: PodActivationWizardActivity.Type = if (podStateManager.isPodInitialized + and podStateManager.activationProgress.isAtLeast(ActivationProgress.PRIMING_COMPLETED)) { + PodActivationWizardActivity.Type.SHORT + } else { + PodActivationWizardActivity.Type.LONG + } + */ + + val intent = Intent(this, DashPodActivationWizardActivity::class.java) + intent.putExtra(PodActivationWizardActivity.KEY_TYPE, PodActivationWizardActivity.Type.LONG) + startActivity(intent) + } + + binding.buttonDeactivatePod.setOnClickListener { + startActivity(Intent(this, DashPodDeactivationWizardActivity::class.java)) + } + + binding.buttonDiscardPod.setOnClickListener { + OKDialog.showConfirmation(this, + resourceHelper.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), Thread { + // TODO discard Pod + }) + } + + binding.buttonPlayTestBeep.setOnClickListener { + // TODO + binding.buttonPlayTestBeep.isEnabled = false + binding.buttonPlayTestBeep.setText(R.string.omnipod_common_pod_management_button_playing_test_beep) + + commandQueue.customCommand(CommandPlayTestBeep(), object : Callback() { + override fun run() { + if (!result.success) { + displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, resourceHelper.gs(R.string.omnipod_common_error_failed_to_play_test_beep), result.comment), false) + } + } + }) + } + } + + override fun onResume() { + super.onResume() + disposables += rxBus + .toObservable(EventQueueChanged::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ refreshButtons() }, fabricPrivacy::logException) + + refreshButtons() + } + + override fun onPause() { + super.onPause() + disposables.clear() + } + + private fun refreshButtons() { + // TODO update button state from Pod state + } + + private fun displayErrorDialog(title: String, message: String, @Suppress("SameParameterValue") withSound: Boolean) { + context.let { + ErrorHelperActivity.runAlarm(it, message, title, if (withSound) R.raw.boluserror else 0) + } + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt index cb01eafe10..295afbf47b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui +import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View @@ -31,4 +32,12 @@ class OmnipodDashOverviewFragment : DaggerFragment() { _bluetoothStatusBinding = OmnipodDashOverviewBluetoothStatusBinding.bind(it.root) _binding = it }.root + + override fun onViewCreated(view: View, savedInstanceState: Bundle?) { + super.onViewCreated(view, savedInstanceState) + + buttonBinding.buttonPodManagement.setOnClickListener { + startActivity(Intent(context, DashPodManagementActivity::class.java)) + } + } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt new file mode 100644 index 0000000000..6f87bfd8f6 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation + +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.PodActivationWizardActivity + +class DashPodActivationWizardActivity : PodActivationWizardActivity() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt new file mode 100644 index 0000000000..b6a3b8de7e --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action + +import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger, private val injector: HasAndroidInjector) : InitializePodViewModel() { + + override fun isPodInAlarm(): Boolean = false // TODO + + override fun isPodActivationTimeExceeded(): Boolean = false // TODO + + override fun isPodDeactivatable(): Boolean = true // TODO + + override fun doExecuteAction(): PumpEnactResult { + // TODO FIRST STEP OF ACTIVATION + aapsLogger.debug(LTag.PUMP, "started activation part 1") + return PumpEnactResult(injector).success(false).comment("not implemented") + } + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_initialize_pod_title + + @StringRes + override fun getTextId() = R.string.omnipod_dash_pod_activation_wizard_initialize_pod_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt new file mode 100644 index 0000000000..0f353b17e8 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -0,0 +1,26 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action + +import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashInsertCannulaViewModel @Inject constructor(private val injector: HasAndroidInjector, private val profileFunction: ProfileFunction) : InsertCannulaViewModel() { + + override fun isPodInAlarm(): Boolean = false // TODO + + override fun isPodActivationTimeExceeded(): Boolean = false // TODO + + override fun isPodDeactivatable(): Boolean = true // TODO + + override fun doExecuteAction(): PumpEnactResult = PumpEnactResult(injector) // TODO + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_insert_cannula_title + + @StringRes + override fun getTextId() = R.string.omnipod_common_pod_activation_wizard_insert_cannula_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt new file mode 100644 index 0000000000..dfad36eb91 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.info + +import androidx.annotation.StringRes +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info.AttachPodViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashAttachPodViewModel @Inject constructor() : AttachPodViewModel() { + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_attach_pod_title + + @StringRes + override fun getTextId() = R.string.omnipod_common_pod_activation_wizard_attach_pod_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt new file mode 100644 index 0000000000..88721268a9 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.info + +import androidx.annotation.StringRes +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info.PodActivatedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashPodActivatedViewModel @Inject constructor() : PodActivatedViewModel() { + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_pod_activated_title + + @StringRes + override fun getTextId() = R.string.omnipod_common_pod_activation_wizard_pod_activated_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt new file mode 100644 index 0000000000..0e7538b621 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.info + +import androidx.annotation.StringRes +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.info.StartPodActivationViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashStartPodActivationViewModel @Inject constructor() : StartPodActivationViewModel() { + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_start_pod_activation_title + + @StringRes + override fun getTextId(): Int = R.string.omnipod_dash_pod_activation_wizard_start_pod_activation_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt new file mode 100644 index 0000000000..0a45f38be8 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation + +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.PodDeactivationWizardActivity + +class DashPodDeactivationWizardActivity : PodDeactivationWizardActivity() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt new file mode 100644 index 0000000000..093b93fe51 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.action + +import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.plugins.pump.omnipod.common.R +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel +import javax.inject.Inject + +class DashDeactivatePodViewModel @Inject constructor(private val injector: HasAndroidInjector) : DeactivatePodViewModel() { + + override fun doExecuteAction(): PumpEnactResult = PumpEnactResult(injector) // TODO + + override fun discardPod() { + // TODO + } + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_deactivation_wizard_deactivating_pod_title + + @StringRes + override fun getTextId(): Int = R.string.omnipod_common_pod_deactivation_wizard_deactivating_pod_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt new file mode 100644 index 0000000000..3496076606 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.info + +import androidx.annotation.StringRes +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.info.PodDeactivatedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashPodDeactivatedViewModel @Inject constructor() : PodDeactivatedViewModel() { + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_deactivation_wizard_pod_deactivated_title + + @StringRes + override fun getTextId() = R.string.omnipod_common_pod_deactivation_wizard_pod_deactivated_text + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt new file mode 100644 index 0000000000..27fb8fd625 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.info + +import androidx.annotation.StringRes +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.info.PodDiscardedViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashPodDiscardedViewModel @Inject constructor() : PodDiscardedViewModel() { + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_deactivation_wizard_pod_discarded_title + + @StringRes + override fun getTextId() = R.string.omnipod_common_pod_deactivation_wizard_pod_discarded_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt new file mode 100644 index 0000000000..099ce1f53c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.info + +import androidx.annotation.StringRes +import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.info.StartPodDeactivationViewModel +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import javax.inject.Inject + +class DashStartPodDeactivationViewModel @Inject constructor() : StartPodDeactivationViewModel() { + + @StringRes + override fun getTitleId(): Int = R.string.omnipod_common_pod_deactivation_wizard_start_pod_deactivation_title + + @StringRes + override fun getTextId() = R.string.omnipod_common_pod_deactivation_wizard_start_pod_deactivation_text +} \ No newline at end of file diff --git a/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml b/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml index ae28ff9884..16d1031ed9 100644 --- a/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml +++ b/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml @@ -37,47 +37,45 @@ android:paddingStart="5dp" android:paddingEnd="5dp" android:textSize="14sp" /> + - + + - - - - - - - + android:layout_weight="1.5" + android:gravity="end" + android:paddingStart="5dp" + android:paddingEnd="5dp" + android:text="@string/omnipod_dash_bluetooth_status" + android:textSize="14sp" /> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/omnipod-dash/src/main/res/values/strings.xml b/omnipod-dash/src/main/res/values/strings.xml index 5ea562af03..c1353658eb 100644 --- a/omnipod-dash/src/main/res/values/strings.xml +++ b/omnipod-dash/src/main/res/values/strings.xml @@ -11,4 +11,8 @@ Bluetooth Status Bluetooth Address + + + Fill a new Pod with enough insulin for 3 days.\n\nListen for two beeps from the Pod during the filling process. These indicate that the minimum amount of 85U has been inserted. Be sure to completely empty the fill syringe, even after hearing the two beeps.\n\nAfter filling the Pod, please press Next.\n\nNote: do not remove the Pod\'s needle cap at this time. + Trying to pair with the new Pod and prime it.\n\nWhen the initialization process has successfully been completed, you can press Next. \ No newline at end of file diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index 2ebdd9a1cd..81e1f40997 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -82,7 +82,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Al import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.util.TimeUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosActiveAlertsChanged; import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosFaultEventChanged; @@ -122,7 +122,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa public static final int STARTUP_STATUS_REQUEST_TRIES = 2; public static final double RESERVOIR_OVER_50_UNITS_DEFAULT = 75.0; - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final RileyLinkServiceData rileyLinkServiceData; private final AapsOmnipodErosManager aapsOmnipodErosManager; private final AapsOmnipodUtil aapsOmnipodUtil; @@ -167,7 +167,7 @@ public class OmnipodErosPumpPlugin extends PumpPluginBase implements PumpInterfa ResourceHelper resourceHelper, ActivePluginProvider activePlugin, SP sp, - PodStateManager podStateManager, + ErosPodStateManager podStateManager, AapsOmnipodErosManager aapsOmnipodErosManager, CommandQueueProvider commandQueue, FabricPrivacy fabricPrivacy, diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/dagger/OmnipodErosModule.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/dagger/OmnipodErosModule.kt index 453f1f7f86..341779fbec 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/dagger/OmnipodErosModule.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/dagger/OmnipodErosModule.kt @@ -6,7 +6,7 @@ import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ActivityScope import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodWizardModule import info.nightscout.androidaps.plugins.pump.omnipod.eros.data.RLHistoryItemOmnipod -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.service.RileyLinkOmnipodService @@ -23,36 +23,36 @@ abstract class OmnipodErosModule { // ACTIVITIES @ContributesAndroidInjector - abstract fun contributesPodManagementActivity(): ErosPodManagementActivity - @ContributesAndroidInjector abstract fun contributesPodHistoryActivity(): ErosPodHistoryActivity + abstract fun contributesErosPodManagementActivity(): ErosPodManagementActivity + @ContributesAndroidInjector abstract fun contributesErosPodHistoryActivity(): ErosPodHistoryActivity @ActivityScope @ContributesAndroidInjector(modules = [OmnipodWizardModule::class, OmnipodErosWizardViewModelsModule::class]) - abstract fun contributesActivationWizardActivity(): ErosPodActivationWizardActivity + abstract fun contributesErosActivationWizardActivity(): ErosPodActivationWizardActivity @ActivityScope @ContributesAndroidInjector(modules = [OmnipodWizardModule::class, OmnipodErosWizardViewModelsModule::class]) - abstract fun contributesDeactivationWizardActivity(): ErosPodDeactivationWizardActivity + abstract fun contributesErosDeactivationWizardActivity(): ErosPodDeactivationWizardActivity // FRAGMENTS @ContributesAndroidInjector - abstract fun contributesOmnipodFragment(): OmnipodErosOverviewFragment + abstract fun contributesOmnipodErosOverviewFragment(): OmnipodErosOverviewFragment // SERVICES @ContributesAndroidInjector - abstract fun omnipodCommunicationManagerProvider(): OmnipodRileyLinkCommunicationManager + abstract fun contributesOmnipodRileyLinkCommunicationManagerProvider(): OmnipodRileyLinkCommunicationManager @ContributesAndroidInjector abstract fun contributesRileyLinkOmnipodService(): RileyLinkOmnipodService // DATA - @ContributesAndroidInjector abstract fun rlHistoryItemOmnipod(): RLHistoryItemOmnipod + @ContributesAndroidInjector abstract fun contributesRlHistoryItemOmnipod(): RLHistoryItemOmnipod companion object { @Provides - fun podStateManagerProvider(aapsErosPodStateManager: AapsErosPodStateManager): PodStateManager = aapsErosPodStateManager + fun erosPodStateManagerProvider(aapsErosPodStateManager: AapsErosPodStateManager): ErosPodStateManager = aapsErosPodStateManager } } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AcknowledgeAlertsAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AcknowledgeAlertsAction.java index 6252d6db56..24dc417c72 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AcknowledgeAlertsAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AcknowledgeAlertsAction.java @@ -6,14 +6,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class AcknowledgeAlertsAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final AlertSet alerts; - public AcknowledgeAlertsAction(PodStateManager podStateManager, AlertSet alerts) { + public AcknowledgeAlertsAction(ErosPodStateManager podStateManager, AlertSet alerts) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); } @@ -26,7 +26,7 @@ public class AcknowledgeAlertsAction implements OmnipodAction { this.alerts = alerts; } - public AcknowledgeAlertsAction(PodStateManager podStateManager, AlertSlot alertSlot) { + public AcknowledgeAlertsAction(ErosPodStateManager podStateManager, AlertSlot alertSlot) { this(podStateManager, new AlertSet(Collections.singletonList(alertSlot))); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AssignAddressAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AssignAddressAction.java index 2d615177de..5f1314c59d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AssignAddressAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/AssignAddressAction.java @@ -14,14 +14,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Pa import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalMessageAddressException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalPacketTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalVersionResponseTypeException; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class AssignAddressAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final AAPSLogger aapsLogger; - public AssignAddressAction(PodStateManager podStateManager, AAPSLogger aapsLogger) { + public AssignAddressAction(ErosPodStateManager podStateManager, AAPSLogger aapsLogger) { if (podStateManager == null) { throw new IllegalArgumentException("podStateManager can not be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/BolusAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/BolusAction.java index 465a68a9ca..7ed57a6db6 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/BolusAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/BolusAction.java @@ -9,17 +9,17 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.SetInsulinScheduleCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BolusDeliverySchedule; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class BolusAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final double units; private final Duration timeBetweenPulses; private final boolean acknowledgementBeep; private final boolean completionBeep; - public BolusAction(PodStateManager podStateManager, double units, Duration timeBetweenPulses, + public BolusAction(ErosPodStateManager podStateManager, double units, Duration timeBetweenPulses, boolean acknowledgementBeep, boolean completionBeep) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); @@ -34,7 +34,7 @@ public class BolusAction implements OmnipodAction { this.completionBeep = completionBeep; } - public BolusAction(PodStateManager podStateManager, double units, boolean acknowledgementBeep, boolean completionBeep) { + public BolusAction(ErosPodStateManager podStateManager, double units, boolean acknowledgementBeep, boolean completionBeep) { this(podStateManager, units, Duration.standardSeconds(2), acknowledgementBeep, completionBeep); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/CancelDeliveryAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/CancelDeliveryAction.java index 5140edf673..5fc280207f 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/CancelDeliveryAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/CancelDeliveryAction.java @@ -14,15 +14,15 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryType; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class CancelDeliveryAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final EnumSet deliveryTypes; private final boolean acknowledgementBeep; - public CancelDeliveryAction(PodStateManager podStateManager, EnumSet deliveryTypes, + public CancelDeliveryAction(ErosPodStateManager podStateManager, EnumSet deliveryTypes, boolean acknowledgementBeep) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureAlertsAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureAlertsAction.java index 39265c03a7..ad10e1284d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureAlertsAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureAlertsAction.java @@ -5,14 +5,14 @@ import java.util.List; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.ConfigureAlertsCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertConfiguration; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class ConfigureAlertsAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final List alertConfigurations; - public ConfigureAlertsAction(PodStateManager podStateManager, List alertConfigurations) { + public ConfigureAlertsAction(ErosPodStateManager podStateManager, List alertConfigurations) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); } @@ -31,7 +31,7 @@ public class ConfigureAlertsAction implements OmnipodAction { return statusResponse; } - public static void updateConfiguredAlerts(PodStateManager podStateManager, List alertConfigurations) { + public static void updateConfiguredAlerts(ErosPodStateManager podStateManager, List alertConfigurations) { for (AlertConfiguration alertConfiguration : alertConfigurations) { if (alertConfiguration.isActive()) { podStateManager.putConfiguredAlert(alertConfiguration.getAlertSlot(), alertConfiguration.getAlertType()); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureBeepAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureBeepAction.java index b8b8914256..c1dd3e2a55 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureBeepAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/ConfigureBeepAction.java @@ -5,11 +5,11 @@ import org.joda.time.Duration; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.BeepConfigCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.BeepConfigType; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class ConfigureBeepAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final BeepConfigType beepType; private final boolean basalCompletionBeep; private final Duration basalIntervalBeep; @@ -18,7 +18,7 @@ public class ConfigureBeepAction implements OmnipodAction { private final boolean bolusCompletionBeep; private final Duration bolusIntervalBeep; - public ConfigureBeepAction(PodStateManager podState, BeepConfigType beepType, boolean basalCompletionBeep, Duration basalIntervalBeep, boolean tempBasalCompletionBeep, Duration tempBasalIntervalBeep, boolean bolusCompletionBeep, Duration bolusIntervalBeep) { + public ConfigureBeepAction(ErosPodStateManager podState, BeepConfigType beepType, boolean basalCompletionBeep, Duration basalIntervalBeep, boolean tempBasalCompletionBeep, Duration tempBasalIntervalBeep, boolean bolusCompletionBeep, Duration bolusIntervalBeep) { if (podState == null || beepType == null) { throw new IllegalArgumentException("Required parameter(s) missing"); } @@ -33,7 +33,7 @@ public class ConfigureBeepAction implements OmnipodAction { this.podStateManager = podState; } - public ConfigureBeepAction(PodStateManager podState, BeepConfigType beepType) { + public ConfigureBeepAction(ErosPodStateManager podState, BeepConfigType beepType) { this(podState, beepType, false, Duration.ZERO, false, Duration.ZERO, false, Duration.ZERO); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/DeactivatePodAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/DeactivatePodAction.java index 2170a43e20..ec70547c6d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/DeactivatePodAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/DeactivatePodAction.java @@ -6,14 +6,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.DeliveryType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.PodFaultException; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class DeactivatePodAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final boolean acknowledgementBeep; - public DeactivatePodAction(PodStateManager podStateManager, boolean acknowledgementBeep) { + public DeactivatePodAction(ErosPodStateManager podStateManager, boolean acknowledgementBeep) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetPodInfoAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetPodInfoAction.java index 399309b4f7..efbfc3157d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetPodInfoAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetPodInfoAction.java @@ -3,14 +3,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.GetStatusCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.podinfo.PodInfoResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class GetPodInfoAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final PodInfoType podInfoType; - public GetPodInfoAction(PodStateManager podStateManager, PodInfoType podInfoType) { + public GetPodInfoAction(ErosPodStateManager podStateManager, PodInfoType podInfoType) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetStatusAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetStatusAction.java index 9cb087e328..b68928e2b2 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetStatusAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/GetStatusAction.java @@ -3,13 +3,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.GetStatusCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodInfoType; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class GetStatusAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; - public GetStatusAction(PodStateManager podState) { + public GetStatusAction(ErosPodStateManager podState) { if (podState == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/InsertCannulaAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/InsertCannulaAction.java index 994d3a8d07..15c76ae683 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/InsertCannulaAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/InsertCannulaAction.java @@ -11,17 +11,17 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Al import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalActivationProgressException; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class InsertCannulaAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final BasalSchedule initialBasalSchedule; private final Duration expirationReminderTimeBeforeShutdown; private final Integer lowReservoirAlertUnits; - public InsertCannulaAction(PodStateManager podStateManager, BasalSchedule initialBasalSchedule, + public InsertCannulaAction(ErosPodStateManager podStateManager, BasalSchedule initialBasalSchedule, Duration expirationReminderTimeBeforeShutdown, Integer lowReservoirAlertUnits) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/PrimeAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/PrimeAction.java index 582df47447..df02efe473 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/PrimeAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/PrimeAction.java @@ -3,15 +3,15 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communicatio import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.action.service.PrimeService; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalActivationProgressException; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class PrimeAction implements OmnipodAction { private final PrimeService service; - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; - public PrimeAction(PrimeService primeService, PodStateManager podStateManager) { + public PrimeAction(PrimeService primeService, ErosPodStateManager podStateManager) { if (primeService == null) { throw new IllegalArgumentException("Prime service cannot be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetBasalScheduleAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetBasalScheduleAction.java index a96d2c0853..ff1f98407f 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetBasalScheduleAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetBasalScheduleAction.java @@ -9,17 +9,17 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.SetInsulinScheduleCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.schedule.BasalSchedule; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class SetBasalScheduleAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final BasalSchedule basalSchedule; private final boolean confidenceReminder; private final Duration scheduleOffset; private final boolean acknowledgementBeep; - public SetBasalScheduleAction(PodStateManager podStateManager, BasalSchedule basalSchedule, + public SetBasalScheduleAction(ErosPodStateManager podStateManager, BasalSchedule basalSchedule, boolean confidenceReminder, Duration scheduleOffset, boolean acknowledgementBeep) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetTempBasalAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetTempBasalAction.java index e26a2d803b..b643c174e3 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetTempBasalAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetTempBasalAction.java @@ -10,17 +10,17 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.SetInsulinScheduleCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.command.TempBasalExtraCommand; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class SetTempBasalAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final double rate; private final Duration duration; private final boolean acknowledgementBeep; private final boolean completionBeep; - public SetTempBasalAction(PodStateManager podStateManager, double rate, Duration duration, + public SetTempBasalAction(ErosPodStateManager podStateManager, double rate, Duration duration, boolean acknowledgementBeep, boolean completionBeep) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager cannot be null"); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetupPodAction.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetupPodAction.java index 5188210bca..cd4614c6ac 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetupPodAction.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/SetupPodAction.java @@ -16,14 +16,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.Ill import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalPacketTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalPodProgressException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.IllegalVersionResponseTypeException; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class SetupPodAction implements OmnipodAction { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final AAPSLogger aapsLogger; - public SetupPodAction(PodStateManager podStateManager, AAPSLogger aapsLogger) { + public SetupPodAction(ErosPodStateManager podStateManager, AAPSLogger aapsLogger) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager can not be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/ExpirationReminderBuilder.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/ExpirationReminderBuilder.java index 3e208d87ba..a2cd03d4de 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/ExpirationReminderBuilder.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/ExpirationReminderBuilder.java @@ -11,14 +11,14 @@ import java.util.Map; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertConfiguration; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.util.AlertConfigurationUtil; public final class ExpirationReminderBuilder { private final Map alerts = new HashMap<>(); private final DateTime endOfServiceTime; - public ExpirationReminderBuilder(PodStateManager podStateManager) { + public ExpirationReminderBuilder(ErosPodStateManager podStateManager) { this.endOfServiceTime = podStateManager.getActivatedAt().plus(OmnipodConstants.SERVICE_DURATION); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/PrimeService.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/PrimeService.java index e5973ca1e9..640869dc00 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/PrimeService.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/communication/action/service/PrimeService.java @@ -11,26 +11,26 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.communication.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertConfiguration; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.util.AlertConfigurationUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; public class PrimeService { - public StatusResponse executeDisableTab5Sub16And17FaultConfigCommand(OmnipodRileyLinkCommunicationManager communicationService, PodStateManager podStateManager) { + public StatusResponse executeDisableTab5Sub16And17FaultConfigCommand(OmnipodRileyLinkCommunicationManager communicationService, ErosPodStateManager podStateManager) { FaultConfigCommand faultConfigCommand = new FaultConfigCommand(podStateManager.getCurrentNonce(), (byte) 0x00, (byte) 0x00); OmnipodMessage faultConfigMessage = new OmnipodMessage(podStateManager.getAddress(), Collections.singletonList(faultConfigCommand), podStateManager.getMessageNumber()); return communicationService.exchangeMessages(StatusResponse.class, podStateManager, faultConfigMessage); } - public StatusResponse executeFinishSetupReminderAlertCommand(OmnipodRileyLinkCommunicationManager communicationService, PodStateManager podStateManager) { + public StatusResponse executeFinishSetupReminderAlertCommand(OmnipodRileyLinkCommunicationManager communicationService, ErosPodStateManager podStateManager) { AlertConfiguration finishSetupReminderAlertConfiguration = AlertConfigurationUtil.createFinishSetupReminderAlertConfiguration(); return communicationService.executeAction(new ConfigureAlertsAction(podStateManager, Collections.singletonList(finishSetupReminderAlertConfiguration))); } - public StatusResponse executePrimeBolusCommand(OmnipodRileyLinkCommunicationManager communicationService, PodStateManager podStateManager) { + public StatusResponse executePrimeBolusCommand(OmnipodRileyLinkCommunicationManager communicationService, ErosPodStateManager podStateManager) { return communicationService.executeAction(new BolusAction(podStateManager, OmnipodConstants.POD_PRIME_BOLUS_UNITS, Duration.standardSeconds(1), false, true)); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/PodStateManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/ErosPodStateManager.java similarity index 99% rename from omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/PodStateManager.java rename to omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/ErosPodStateManager.java index adc56510bb..e066f5e1a9 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/PodStateManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/ErosPodStateManager.java @@ -38,13 +38,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.sc import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.util.TimeUtil; // TODO add nullchecks on some setters -public abstract class PodStateManager { +public abstract class ErosPodStateManager { private final AAPSLogger aapsLogger; private final Gson gsonInstance; private PodState podState; - protected PodStateManager(AAPSLogger aapsLogger) { + protected ErosPodStateManager(AAPSLogger aapsLogger) { this.aapsLogger = aapsLogger; this.gsonInstance = createGson(); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/OmnipodManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/OmnipodManager.java index d76b183cf6..6649eced0d 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/OmnipodManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/driver/manager/OmnipodManager.java @@ -63,7 +63,7 @@ public class OmnipodManager { private static final int ACTION_VERIFICATION_TRIES = 1; private final OmnipodRileyLinkCommunicationManager communicationService; - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private ActiveBolusData activeBolusData; private SingleSubject bolusCommandExecutionSubject; @@ -76,7 +76,7 @@ public class OmnipodManager { public OmnipodManager(AAPSLogger aapsLogger, AapsSchedulers aapsSchedulers, OmnipodRileyLinkCommunicationManager communicationService, - PodStateManager podStateManager) { + ErosPodStateManager podStateManager) { if (communicationService == null) { throw new IllegalArgumentException("Communication service cannot be null"); } diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManager.java index 99e58b3550..4a170d5c35 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsErosPodStateManager.java @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.pump.omnipod.eros.definition.OmnipodErosStorageKeys; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosActiveAlertsChanged; import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosFaultEventChanged; import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosTbrChanged; @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodEr import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton -public class AapsErosPodStateManager extends PodStateManager { +public class AapsErosPodStateManager extends ErosPodStateManager { private final SP sp; private final RxBusWrapper rxBus; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java index 0acab0537b..068dd53793 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java @@ -80,7 +80,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.Ril import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnexpectedException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnreachableException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.OmnipodManager; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosPumpValuesChanged; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil; @@ -94,7 +94,7 @@ import io.reactivex.subjects.SingleSubject; @Singleton public class AapsOmnipodErosManager { - private final PodStateManager podStateManager; + private final ErosPodStateManager podStateManager; private final AapsOmnipodUtil aapsOmnipodUtil; private final AAPSLogger aapsLogger; private final AapsSchedulers aapsSchedulers; @@ -127,7 +127,7 @@ public class AapsOmnipodErosManager { @Inject public AapsOmnipodErosManager(OmnipodRileyLinkCommunicationManager communicationService, - PodStateManager podStateManager, + ErosPodStateManager podStateManager, AapsOmnipodUtil aapsOmnipodUtil, AAPSLogger aapsLogger, AapsSchedulers aapsSchedulers, diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/manager/OmnipodRileyLinkCommunicationManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/manager/OmnipodRileyLinkCommunicationManager.java index 2e405af2ee..bd8ae128ee 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/manager/OmnipodRileyLinkCommunicationManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/manager/OmnipodRileyLinkCommunicationManager.java @@ -43,7 +43,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.Pod import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkTimeoutException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnexpectedException; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.exception.RileyLinkUnreachableException; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; /** * Created by andy on 6/29/18. @@ -86,11 +86,11 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication return super.sendAndListen(msg, timeout_ms, repeatCount, retryCount, extendPreamble_ms); } - public T sendCommand(Class responseClass, PodStateManager podStateManager, MessageBlock command) { + public T sendCommand(Class responseClass, ErosPodStateManager podStateManager, MessageBlock command) { return sendCommand(responseClass, podStateManager, command, true); } - public T sendCommand(Class responseClass, PodStateManager podStateManager, MessageBlock command, boolean automaticallyResyncNone) { + public T sendCommand(Class responseClass, ErosPodStateManager podStateManager, MessageBlock command, boolean automaticallyResyncNone) { OmnipodMessage message = new OmnipodMessage(podStateManager.getAddress(), Collections.singletonList(command), podStateManager.getMessageNumber()); return exchangeMessages(responseClass, podStateManager, message, automaticallyResyncNone); } @@ -100,19 +100,19 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication return action.execute(this); } - public T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message) { + public T exchangeMessages(Class responseClass, ErosPodStateManager podStateManager, OmnipodMessage message) { return exchangeMessages(responseClass, podStateManager, message, true); } - public T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message, boolean automaticallyResyncNonce) { + public T exchangeMessages(Class responseClass, ErosPodStateManager podStateManager, OmnipodMessage message, boolean automaticallyResyncNonce) { return exchangeMessages(responseClass, podStateManager, message, null, null, automaticallyResyncNonce); } - public synchronized T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { + public synchronized T exchangeMessages(Class responseClass, ErosPodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { return exchangeMessages(responseClass, podStateManager, message, addressOverride, ackAddressOverride, true); } - public synchronized T exchangeMessages(Class responseClass, PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) { + public synchronized T exchangeMessages(Class responseClass, ErosPodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride, boolean automaticallyResyncNonce) { aapsLogger.debug(LTag.PUMPBTCOMM, "Exchanging OmnipodMessage: responseClass={}, podStateManager={}, message={}, addressOverride={}, ackAddressOverride={}, automaticallyResyncNonce={}", // responseClass.getSimpleName(), podStateManager, message, addressOverride, ackAddressOverride, automaticallyResyncNonce); @@ -192,7 +192,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication } - private MessageBlock transportMessages(PodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { + private MessageBlock transportMessages(ErosPodStateManager podStateManager, OmnipodMessage message, Integer addressOverride, Integer ackAddressOverride) { int packetAddress = podStateManager.getAddress(); if (addressOverride != null) { packetAddress = addressOverride; @@ -298,7 +298,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication return messageBlock; } - private OmnipodPacket createAckPacket(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { + private OmnipodPacket createAckPacket(ErosPodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { if (packetAddress == null) { packetAddress = podStateManager.getAddress(); } @@ -308,7 +308,7 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication return new OmnipodPacket(packetAddress, PacketType.ACK, podStateManager.getPacketNumber(), ByteUtil.getBytesFromInt(messageAddress)); } - private void ackUntilQuiet(PodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { + private void ackUntilQuiet(ErosPodStateManager podStateManager, Integer packetAddress, Integer messageAddress) { OmnipodPacket ack = createAckPacket(podStateManager, packetAddress, messageAddress); boolean quiet = false; while (!quiet) try { @@ -326,15 +326,15 @@ public class OmnipodRileyLinkCommunicationManager extends RileyLinkCommunication podStateManager.increasePacketNumber(); } - private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet) { + private OmnipodPacket exchangePackets(ErosPodStateManager podStateManager, OmnipodPacket packet) { return exchangePackets(podStateManager, packet, 0, 333, 9000, 127); } - private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int preambleExtensionMilliseconds) { + private OmnipodPacket exchangePackets(ErosPodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int preambleExtensionMilliseconds) { return exchangePackets(podStateManager, packet, repeatCount, 333, 9000, preambleExtensionMilliseconds); } - private OmnipodPacket exchangePackets(PodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int responseTimeoutMilliseconds, int exchangeTimeoutMilliseconds, int preambleExtensionMilliseconds) { + private OmnipodPacket exchangePackets(ErosPodStateManager podStateManager, OmnipodPacket packet, int repeatCount, int responseTimeoutMilliseconds, int exchangeTimeoutMilliseconds, int preambleExtensionMilliseconds) { long timeoutTime = System.currentTimeMillis() + exchangeTimeoutMilliseconds; podStateManager.increasePacketNumber(); diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java index 89524f0129..31ca482106 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/rileylink/service/RileyLinkOmnipodService.java @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin; import info.nightscout.androidaps.plugins.pump.omnipod.eros.R; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.OmnipodRileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil; @@ -36,7 +36,7 @@ public class RileyLinkOmnipodService extends RileyLinkService { @Inject OmnipodErosPumpPlugin omnipodErosPumpPlugin; @Inject AapsOmnipodUtil aapsOmnipodUtil; - @Inject PodStateManager podStateManager; + @Inject ErosPodStateManager podStateManager; @Inject DatabaseHelperInterface databaseHelper; @Inject AapsOmnipodErosManager aapsOmnipodErosManager; @Inject OmnipodRileyLinkCommunicationManager omnipodRileyLinkCommunicationManager; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt index 95c3e7e586..4ddf876f02 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodManagementActivity.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugi import info.nightscout.androidaps.plugins.pump.omnipod.eros.R import info.nightscout.androidaps.plugins.pump.omnipod.eros.databinding.OmnipodErosPodManagementBinding import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosPumpValuesChanged import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.queue.command.CommandReadPulseLog @@ -44,7 +44,7 @@ class ErosPodManagementActivity : NoSplashAppCompatActivity() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var commandQueue: CommandQueueProvider - @Inject lateinit var podStateManager: PodStateManager + @Inject lateinit var podStateManager: ErosPodStateManager @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData @Inject lateinit var aapsOmnipodManager: AapsOmnipodErosManager diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt index 356f3d0444..1b232a6527 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt @@ -35,7 +35,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.databinding.OmnipodE import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.OmnipodConstants import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.PodProgressStatus -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.util.TimeUtil import info.nightscout.androidaps.plugins.pump.omnipod.eros.event.EventOmnipodErosPumpValuesChanged import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager @@ -74,7 +74,7 @@ class OmnipodErosOverviewFragment : DaggerFragment() { @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var omnipodErosPumpPlugin: OmnipodErosPumpPlugin - @Inject lateinit var podStateManager: PodStateManager + @Inject lateinit var podStateManager: ErosPodStateManager @Inject lateinit var sp: SP @Inject lateinit var omnipodUtil: AapsOmnipodUtil @Inject lateinit var omnipodAlertUtil: OmnipodAlertUtil diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java index ad99d1746b..2ac8d0cdf2 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.R; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertType; -import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.PodStateManager; +import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; import info.nightscout.androidaps.utils.resources.ResourceHelper; /** @@ -56,7 +56,7 @@ public class AapsOmnipodUtil { return this.gsonInstance; } - public List getTranslatedActiveAlerts(PodStateManager podStateManager) { + public List getTranslatedActiveAlerts(ErosPodStateManager podStateManager) { List translatedAlerts = new ArrayList<>(); AlertSet activeAlerts = podStateManager.getActiveAlerts(); From fa8fdd981655e8f9db7a0e7995f6f35252a3d8ad Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Tue, 23 Feb 2021 21:20:51 +0100 Subject: [PATCH 003/649] Implement ble-scanning for a new pod --- .../omnipod/dash/dagger/OmnipodDashModule.kt | 3 + .../dash/driver/comm/BleCommCallbacks.java | 7 + .../omnipod/dash/driver/comm/BleManager.java | 159 ++++++++++++++++++ .../driver/comm/blecommand/BleCommand.java | 22 +++ .../comm/blecommand/BleCommandHello.java | 14 ++ .../comm/blecommand/BleCommandType.java | 30 ++++ .../CharacteristicNotFoundException.java | 7 + .../CouldNotSendBleCmdException.java | 4 + .../exceptions/CouldNotSendBleException.java | 4 + .../DiscoveredInvalidPodException.java | 11 ++ .../exceptions/FailedToConnectException.java | 11 ++ .../comm/exceptions/ScanFailException.java | 10 ++ .../ScanFailFoundTooManyException.java | 20 +++ .../exceptions/ScanFailNotFoundException.java | 4 + .../exceptions/ServiceNotFoundException.java | 7 + .../driver/comm/scan/BleDiscoveredDevice.java | 94 +++++++++++ .../dash/driver/comm/scan/PodScanner.java | 62 +++++++ .../dash/driver/comm/scan/ScanCollector.java | 66 ++++++++ .../action/DashInitializePodViewModel.kt | 17 +- 19 files changed, 550 insertions(+), 2 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index 9a3e241e52..0d9b275dd6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -4,6 +4,7 @@ import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ActivityScope import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodWizardModule +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.DashPodManagementActivity import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOverviewFragment import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.DashPodActivationWizardActivity @@ -30,4 +31,6 @@ abstract class OmnipodDashModule { @ContributesAndroidInjector abstract fun contributesOmnipodDashOverviewFragment(): OmnipodDashOverviewFragment + @ContributesAndroidInjector + abstract fun contributesBleManager(): BleManager } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java new file mode 100644 index 0000000000..235cd5434d --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; + +import android.bluetooth.BluetoothGattCallback; + +public class BleCommCallbacks extends BluetoothGattCallback { + +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java new file mode 100644 index 0000000000..c8a14ed336 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java @@ -0,0 +1,159 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; + +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCallback; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; +import android.bluetooth.BluetoothManager; +import android.bluetooth.BluetoothProfile; +import android.content.Context; + +import java.math.BigInteger; +import java.util.UUID; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand.BleCommand; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand.BleCommandHello; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand.BleCommandType; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleCmdException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.FailedToConnectException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner; + +@Singleton +public class BleManager implements OmnipodDashCommunicationManager { + private static final int CONNECT_TIMEOUT_MS = 5000; + private static final int DISCOVER_SERVICES_TIMEOUT_MS = 5000; + private static final String SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f"; + private static final String CMD_CHARACTERISTIC_UUID = "1a7e-2441-e3ed-4464-8b7e-751e03d0dc5f"; + private static final String DATA_CHARACTERISTIC_UUID = "1a7e-2442-e3ed-4464-8b7e-751e03d0dc5f"; + private static final int CONTROLLER_ID = 4242; // TODO read from preferences or somewhere else. + private static BleManager instance = null; + private final Context context; + private final BluetoothAdapter bluetoothAdapter; + private final BluetoothManager bluetoothManager; + @Inject AAPSLogger aapsLogger; + private String podAddress; + private BluetoothGatt gatt; + + private BluetoothGattCharacteristic cmdCharacteristic; + private BluetoothGattCharacteristic dataCharacteristic; + + @Inject + public BleManager(Context context) { + this.context = context; + this.bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); + this.bluetoothAdapter = bluetoothManager.getAdapter(); + } + + public static BleManager getInstance(Context context) { + BleManager ret; + synchronized (BleManager.class) { + if (instance == null) { + instance = new BleManager(context); + } + ret = instance; + } + return ret; + } + + private static UUID uuidFromString(String s) { + return new UUID( + new BigInteger(s.replace("-", "").substring(0, 16), 16).longValue(), + new BigInteger(s.replace("-", "").substring(16), 16).longValue() + ); + } + + public void activateNewPod() + throws InterruptedException, + ScanFailException, + FailedToConnectException, + CouldNotSendBleException { + this.aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation"); + PodScanner podScanner = new PodScanner(this.aapsLogger, this.bluetoothAdapter); + this.podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).getScanResult().getDevice().getAddress(); + // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; + this.connect(); + // do the dance: send SP0, SP1, etc + // get and save LTK + } + + public void connect() + throws FailedToConnectException, + CouldNotSendBleException { + // TODO: locking? + + BluetoothDevice podDevice = this.bluetoothAdapter.getRemoteDevice(this.podAddress); + BluetoothGattCallback bleCommCallback = new BleCommCallbacks(); + + aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to " + this.podAddress); + gatt = podDevice.connectGatt(this.context, true, bleCommCallback, BluetoothDevice.TRANSPORT_LE); + + try { + Thread.sleep(CONNECT_TIMEOUT_MS); + } catch (InterruptedException e) { + // we get interrupted on successful connection + // TODO: interrupt this thread onConnect() + } + + int connectionState = this.bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT); + aapsLogger.debug(LTag.PUMPBTCOMM, "GATT connection state: " + connectionState); + if (connectionState != BluetoothProfile.STATE_CONNECTED) { + throw new FailedToConnectException(this.podAddress); + } + this.discoverServicesAndSayHello(gatt); + + } + + private void discoverServicesAndSayHello(BluetoothGatt gatt) + throws FailedToConnectException, + CouldNotSendBleException { + gatt.discoverServices(); + try { + Thread.sleep(CONNECT_TIMEOUT_MS); + } catch (InterruptedException e) { + // we get interrupted on successfull connection + // TODO: interrupt this thread onConnect() + } + + BluetoothGattService service = gatt.getService(uuidFromString(SERVICE_UUID)); + if (service == null) { + throw new ServiceNotFoundException(SERVICE_UUID); + } + BluetoothGattCharacteristic cmdChar = service.getCharacteristic(uuidFromString(CMD_CHARACTERISTIC_UUID)); + if (cmdChar == null) { + throw new CharacteristicNotFoundException(CMD_CHARACTERISTIC_UUID); + } + BluetoothGattCharacteristic dataChar = service.getCharacteristic(uuidFromString(DATA_CHARACTERISTIC_UUID)); + if (dataChar == null) { + throw new CharacteristicNotFoundException(DATA_CHARACTERISTIC_UUID); + } + this.cmdCharacteristic = cmdChar; + this.dataCharacteristic = dataChar; + + BleCommand hello = new BleCommandHello(CONTROLLER_ID); + if (!this.sendCmd(hello.asByteArray())) { + throw new CouldNotSendBleCmdException(); + } + aapsLogger.debug(LTag.PUMPBTCOMM, "saying hello to the pod" + hello.asByteArray()); + + } + + private boolean sendCmd(byte[] payload) { + // TODO move out of here + this.cmdCharacteristic.setValue(payload); + boolean ret = this.gatt.writeCharacteristic(cmdCharacteristic); + aapsLogger.debug(LTag.PUMPBTCOMM, "Sending command status. data:" + payload.toString() + "status: " + ret); + return ret; + } +} + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java new file mode 100644 index 0000000000..fdcbde4e7c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand; + +import org.jetbrains.annotations.NotNull; + +public class BleCommand { + private final byte[] data; + + public BleCommand(@NotNull BleCommandType type) { + this.data = new byte[]{type.getValue()}; + } + + public BleCommand(@NotNull BleCommandType type, @NotNull byte[] payload) { + int n = payload.length + 1; + this.data = new byte[n]; + this.data[0] = type.getValue(); + System.arraycopy(payload, 0, data, 1, payload.length); + } + + public byte[] asByteArray() { + return this.data; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java new file mode 100644 index 0000000000..3bcabacc28 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand; + +import java.nio.ByteBuffer; + +public class BleCommandHello extends BleCommand { + public BleCommandHello(int controllerId) { + super(BleCommandType.HELLO, + ByteBuffer.allocate(6) + .put((byte) 1) // TODO find the meaning of this constant + .put((byte) 4) // TODO find the meaning of this constant + .putInt(controllerId).array() + ); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java new file mode 100644 index 0000000000..4bd71a357d --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand; + +public enum BleCommandType { + RTS((byte) 0x00), + CTS((byte) 0x01), + NACK((byte) 0x02), + ABORT((byte) 0x03), + SUCCESS((byte) 0x04), + FAIL((byte) 0x05), + HELLO((byte) 0x06); + + public final byte value; + + BleCommandType(byte value) { + this.value = value; + } + + public static BleCommandType byValue(byte value) { + for (BleCommandType type : values()) { + if (type.value == value) { + return type; + } + } + throw new IllegalArgumentException("Unknown BleCommandType: " + value); + } + + public byte getValue() { + return this.value; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java new file mode 100644 index 0000000000..1405d93f32 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class CharacteristicNotFoundException extends FailedToConnectException { + public CharacteristicNotFoundException(String cmdCharacteristicUuid) { + super("characteristic not found: " + cmdCharacteristicUuid); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java new file mode 100644 index 0000000000..ae2d1e4be4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class CouldNotSendBleCmdException extends CouldNotSendBleException { +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java new file mode 100644 index 0000000000..8bca9c732d --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class CouldNotSendBleException extends Exception { +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java new file mode 100644 index 0000000000..9de20faf07 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +import android.os.ParcelUuid; + +import java.util.List; + +public class DiscoveredInvalidPodException extends Exception { + public DiscoveredInvalidPodException(String message, List serviceUUIds) { + super(message + " service UUIDs: " + serviceUUIds); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java new file mode 100644 index 0000000000..dd4cf724ed --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class FailedToConnectException extends Exception { + public FailedToConnectException() { + super(); + } + + public FailedToConnectException(String message) { + super(message); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java new file mode 100644 index 0000000000..f99fbe32d4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class ScanFailException extends Exception { + public ScanFailException() { + } + + public ScanFailException(int errorCode) { + super("errorCode" + errorCode); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java new file mode 100644 index 0000000000..7fc00ae2df --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java @@ -0,0 +1,20 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.BleDiscoveredDevice; + +public class ScanFailFoundTooManyException extends ScanFailException { + private final List devices; + + public ScanFailFoundTooManyException(List devices) { + super(); + this.devices = new ArrayList<>(devices); + } + + public List getDiscoveredDevices() { + return Collections.unmodifiableList(this.devices); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java new file mode 100644 index 0000000000..9bf2284db3 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class ScanFailNotFoundException extends ScanFailException { +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java new file mode 100644 index 0000000000..51bfa5b8ef --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class ServiceNotFoundException extends FailedToConnectException { + public ServiceNotFoundException(String serviceUuid) { + super("service not found: " + serviceUuid); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java new file mode 100644 index 0000000000..d4c0a19ef8 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java @@ -0,0 +1,94 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan; + +import android.bluetooth.le.ScanRecord; +import android.bluetooth.le.ScanResult; +import android.os.ParcelUuid; + +import java.util.List; + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException; + +public class BleDiscoveredDevice { + private final ScanResult scanResult; + private final long podID; + private final int sequenceNo; + private final long lotNo; + + public BleDiscoveredDevice(ScanResult scanResult, long searchPodID) + throws DiscoveredInvalidPodException { + + this.scanResult = scanResult; + this.podID = searchPodID; + + this.validateServiceUUIDs(); + this.validatePodID(); + this.lotNo = this.parseLotNo(); + this.sequenceNo = this.parseSeqNo(); + } + + private static String extractUUID16(ParcelUuid uuid) { + return uuid.toString().substring(4, 8); + } + + private void validateServiceUUIDs() + throws DiscoveredInvalidPodException { + ScanRecord scanRecord = scanResult.getScanRecord(); + List serviceUUIDs = scanRecord.getServiceUuids(); + + if (serviceUUIDs.size() != 9) { + throw new DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUUIDs.size(), serviceUUIDs); + } + if (!extractUUID16(serviceUUIDs.get(0)).equals("4024")) { + // this is the service that we filtered for + throw new DiscoveredInvalidPodException("The first exposed service UUID should be 4024, got " + extractUUID16(serviceUUIDs.get(0)), serviceUUIDs); + } + // TODO understand what is serviceUUIDs[1]. 0x2470. Alarms? + if (!extractUUID16(serviceUUIDs.get(2)).equals("000a")) { + // constant? + throw new DiscoveredInvalidPodException("The third exposed service UUID should be 000a, got " + serviceUUIDs.get(2), serviceUUIDs); + } + } + + private void validatePodID() + throws DiscoveredInvalidPodException { + ScanRecord scanRecord = scanResult.getScanRecord(); + List serviceUUIDs = scanRecord.getServiceUuids(); + String hexPodID = extractUUID16(serviceUUIDs.get(3)) + extractUUID16(serviceUUIDs.get(4)); + Long podID = Long.parseLong(hexPodID, 16); + if (this.podID != podID) { + throw new DiscoveredInvalidPodException("This is not the POD we are looking for. " + this.podID + " found: " + podID, serviceUUIDs); + } + } + + private long parseLotNo() { + ScanRecord scanRecord = scanResult.getScanRecord(); + List serviceUUIDs = scanRecord.getServiceUuids(); + String lotSeq = extractUUID16(serviceUUIDs.get(5)) + + extractUUID16(serviceUUIDs.get(6)) + + extractUUID16(serviceUUIDs.get(7)); + + return Long.parseLong(lotSeq.substring(0, 10), 16); + } + + private int parseSeqNo() { + ScanRecord scanRecord = scanResult.getScanRecord(); + List serviceUUIDs = scanRecord.getServiceUuids(); + String lotSeq = extractUUID16(serviceUUIDs.get(7)) + + extractUUID16(serviceUUIDs.get(8)); + + return Integer.parseInt(lotSeq.substring(2), 16); + } + + public ScanResult getScanResult() { + return this.scanResult; + } + + @Override public String toString() { + return "BleDiscoveredDevice{" + + "scanResult=" + scanResult + + ", podID=" + podID + + ", sequenceNo=" + sequenceNo + + ", lotNo=" + lotNo + + '}'; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java new file mode 100644 index 0000000000..c3953f75d1 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java @@ -0,0 +1,62 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan; + +import android.bluetooth.BluetoothAdapter; +import android.bluetooth.le.BluetoothLeScanner; +import android.bluetooth.le.ScanFilter; +import android.bluetooth.le.ScanSettings; +import android.os.ParcelUuid; + +import java.util.Arrays; +import java.util.List; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailFoundTooManyException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailNotFoundException; + +public class PodScanner { + public static final String SCAN_FOR_SERVICE_UUID = "00004024-0000-1000-8000-00805F9B34FB"; + public static final long POD_ID_NOT_ACTIVATED = 4294967294L; + private static final int SCAN_DURATION_MS = 5000; + + private final BluetoothAdapter bluetoothAdapter; + private final AAPSLogger logger; + + public PodScanner(AAPSLogger logger, BluetoothAdapter bluetoothAdapter) { + this.bluetoothAdapter = bluetoothAdapter; + this.logger = logger; + } + + public BleDiscoveredDevice scanForPod(String serviceUUID, long podID) + throws InterruptedException, ScanFailException { + BluetoothLeScanner scanner = this.bluetoothAdapter.getBluetoothLeScanner(); + + ScanFilter filter = new ScanFilter.Builder() + .setServiceUuid(ParcelUuid.fromString(serviceUUID)) + .build(); + + ScanSettings scanSettings = new ScanSettings.Builder() + .setLegacy(false) + .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build(); + + ScanCollector scanCollector = new ScanCollector(this.logger, podID); + this.logger.debug(LTag.PUMPBTCOMM, "Scanning with filters: "+ filter.toString() + " settings" + scanSettings.toString()); + scanner.startScan(Arrays.asList(filter), scanSettings, scanCollector); + + Thread.sleep(SCAN_DURATION_MS); + + scanner.flushPendingScanResults(scanCollector); + scanner.stopScan(scanCollector); + + List collected = scanCollector.collect(); + if (collected.size() == 0) { + throw new ScanFailNotFoundException(); + } else if (collected.size() > 1) { + throw new ScanFailFoundTooManyException(collected); + } + return collected.get(0); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java new file mode 100644 index 0000000000..9121b0f5a4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java @@ -0,0 +1,66 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan; + +import android.bluetooth.le.ScanCallback; +import android.bluetooth.le.ScanResult; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; + +public class ScanCollector extends ScanCallback { + private final AAPSLogger logger; + private final long podID; + // there could be different threads calling the onScanResult callback + private final ConcurrentHashMap found; + private int scanFailed; + + public ScanCollector(AAPSLogger logger, long podID) { + this.podID = podID; + this.logger = logger; + this.found = new ConcurrentHashMap(); + } + + @Override + public void onScanResult(int callbackType, ScanResult result) { + // callbackType will be ALL + this.logger.debug(LTag.PUMPBTCOMM, "Scan found: "+result.toString()); + this.found.put(result.getDevice().getAddress(), result); + } + + @Override + public void onScanFailed(int errorCode) { + this.scanFailed = errorCode; + this.logger.warn(LTag.PUMPBTCOMM, "Scan failed with errorCode: "+errorCode); + super.onScanFailed(errorCode); + } + + public List collect() + throws ScanFailException { + List ret = new ArrayList<>(); + + if (this.scanFailed != 0) { + throw new ScanFailException(this.scanFailed); + } + + logger.debug(LTag.PUMPBTCOMM, "ScanCollector looking for podID: " + this.podID); + + for (ScanResult result : this.found.values()) { + try { + BleDiscoveredDevice device = new BleDiscoveredDevice(result, this.podID); + ret.add(device); + logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + this.podID); + } catch (DiscoveredInvalidPodException e) { + logger.debug(LTag.PUMPBTCOMM, "ScanCollector: pod not matching" + e.toString()); + // this is not the POD we are looking for + } + } + return Collections.unmodifiableList(ret); + } +} + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index b6a3b8de7e..b97060a907 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -1,15 +1,21 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action +import android.os.AsyncTask import androidx.annotation.StringRes +import androidx.lifecycle.viewModelScope import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager +import kotlinx.coroutines.launch import javax.inject.Inject -class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger, private val injector: HasAndroidInjector) : InitializePodViewModel() { +class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger, + private val injector: HasAndroidInjector, + private val bleManager: BleManager) : InitializePodViewModel() { override fun isPodInAlarm(): Boolean = false // TODO @@ -19,7 +25,14 @@ class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAP override fun doExecuteAction(): PumpEnactResult { // TODO FIRST STEP OF ACTIVATION - aapsLogger.debug(LTag.PUMP, "started activation part 1") + AsyncTask.execute { + try { + bleManager.activateNewPod() + } catch (e: Exception) { + aapsLogger.error(LTag.PUMP, "TEST ACTIVATE Exception" + e.toString()) + } + } + return PumpEnactResult(injector).success(false).comment("not implemented") } From d9cebbbad7a9dce9bf6379a4603d6c0c79bcca1f Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Tue, 23 Feb 2021 21:41:20 +0100 Subject: [PATCH 004/649] mark BleCommand as abstract --- .../pump/omnipod/dash/driver/comm/blecommand/BleCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java index fdcbde4e7c..86cd356ff3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecomm import org.jetbrains.annotations.NotNull; -public class BleCommand { +public abstract class BleCommand { private final byte[] data; public BleCommand(@NotNull BleCommandType type) { From 1ca69ec414d32e6f71aaa31df3361e2727a32c1c Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Wed, 24 Feb 2021 11:49:24 +0100 Subject: [PATCH 005/649] Ble updates - stop Thread.sleep()ing and use CountDownLatches for connection and service discovery state - prepare BleIO for reading/writing - define CharacteristicType for the CMD/DATA characteristics - prepare BlePacket for DATA packets(the equivalent of BleCommand) --- .../dash/driver/comm/BleCommCallbacks.java | 48 ++++++++ .../pump/omnipod/dash/driver/comm/BleIO.java | 76 ++++++++++++ .../omnipod/dash/driver/comm/BleManager.java | 113 +++++------------- .../dash/driver/comm/CharacteristicType.java | 35 ++++++ .../dash/driver/comm/ServiceDiscoverer.java | 74 ++++++++++++ .../{blecommand => command}/BleCommand.java | 2 +- .../BleCommandHello.java | 2 +- .../BleCommandType.java | 2 +- .../CouldNotSendBleCmdException.java | 4 - .../exceptions/CouldNotSendBleException.java | 3 + .../dash/driver/comm/packet/BlePacket.java | 4 + 11 files changed, 276 insertions(+), 87 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{blecommand => command}/BleCommand.java (96%) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{blecommand => command}/BleCommandHello.java (95%) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{blecommand => command}/BleCommandType.java (97%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java index 235cd5434d..aa8044266f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java @@ -1,7 +1,55 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; +import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothGattCallback; +import android.bluetooth.BluetoothProfile; + +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; public class BleCommCallbacks extends BluetoothGattCallback { + private final CountDownLatch serviceDiscoveryComplete; + private final CountDownLatch connected; + private final AAPSLogger aapsLogger; + private final Map> incomingPackets; + + public BleCommCallbacks(AAPSLogger aapsLogger, Map> incomingPackets) { + this.serviceDiscoveryComplete = new CountDownLatch(1); + this.connected = new CountDownLatch(1); + this.aapsLogger = aapsLogger; + this.incomingPackets = incomingPackets; + } + + + @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + super.onConnectionStateChange(gatt, status, newState); + this.aapsLogger.debug(LTag.PUMPBTCOMM,"OnConnectionStateChange discovered with status/state"+status+"/"+newState); + if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { + this.connected.countDown(); + } + } + + @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { + super.onServicesDiscovered(gatt, status); + this.aapsLogger.debug(LTag.PUMPBTCOMM,"OnServicesDiscovered with status"+status); + if (status == gatt.GATT_SUCCESS) { + this.serviceDiscoveryComplete.countDown(); + } + } + + public void waitForConnection(int timeout_ms) + throws InterruptedException { + this.connected.await(timeout_ms, TimeUnit.MILLISECONDS); + } + + public void waitForServiceDiscovery(int timeout_ms) + throws InterruptedException { + this.serviceDiscoveryComplete.await(timeout_ms, TimeUnit.MILLISECONDS); + } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java new file mode 100644 index 0000000000..40c76d5de2 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java @@ -0,0 +1,76 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; + +import java.util.Map; +import java.util.concurrent.BlockingQueue; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; + + +public class BleIO { + private static final int DEFAULT_IO_TIMEOUT_MS = 1000; + + private final AAPSLogger aapsLogger; + private final Map chars; + private final Map> incomingPackets; + private final BluetoothGatt gatt; + + + public BleIO(AAPSLogger aapsLogger, Map chars, Map> incomingPackets, BluetoothGatt gatt) { + this.aapsLogger = aapsLogger; + this.chars = chars; + this.incomingPackets = incomingPackets; + this.gatt = gatt; + } + + /*** + * + * @param characteristic where to read from(CMD or DATA) + * @return a byte array with the received data + */ + public byte[] receiveData(CharacteristicType characteristic) { + return null; + } + + /*** + * + * @param characteristic where to write to(CMD or DATA) + * @param packet the data to send + * @throws CouldNotSendBleException + */ + public void sendAndConfirmData(CharacteristicType characteristic, byte[] packet) + throws CouldNotSendBleException { + aapsLogger.debug(LTag.PUMPBTCOMM, "BleIO: Sending data on " + characteristic.name() + " :: " +packet.toString()); + BluetoothGattCharacteristic ch = chars.get(characteristic); + boolean set = ch.setValue(packet); + if (!set) { + throw new CouldNotSendBleException("setValue"); + } + boolean sent = this.gatt.writeCharacteristic(ch); + if (!sent) { + throw new CouldNotSendBleException("writeCharacteristic"); + } + // TODO: wait for confirmation callback + } + + /** + * Called before sending a new message. + * The incoming queues should be empty, so we log when they are not. + */ + public void flushIncomingQueues() { + + } + + /** + * Enable intentions on the characteristics. + * This will signal the pod it can start sending back data + */ + public void readyToRead() + throws CouldNotSendBleException { + + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java index c8a14ed336..fdacd4e395 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java @@ -3,40 +3,34 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattService; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; import android.content.Context; -import java.math.BigInteger; -import java.util.UUID; +import java.util.Collections; +import java.util.EnumMap; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; import javax.inject.Inject; import javax.inject.Singleton; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand.BleCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand.BleCommandHello; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand.BleCommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleCmdException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.FailedToConnectException; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner; @Singleton public class BleManager implements OmnipodDashCommunicationManager { private static final int CONNECT_TIMEOUT_MS = 5000; - private static final int DISCOVER_SERVICES_TIMEOUT_MS = 5000; - private static final String SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f"; - private static final String CMD_CHARACTERISTIC_UUID = "1a7e-2441-e3ed-4464-8b7e-751e03d0dc5f"; - private static final String DATA_CHARACTERISTIC_UUID = "1a7e-2442-e3ed-4464-8b7e-751e03d0dc5f"; private static final int CONTROLLER_ID = 4242; // TODO read from preferences or somewhere else. + private static BleManager instance = null; private final Context context; private final BluetoothAdapter bluetoothAdapter; @@ -44,9 +38,7 @@ public class BleManager implements OmnipodDashCommunicationManager { @Inject AAPSLogger aapsLogger; private String podAddress; private BluetoothGatt gatt; - - private BluetoothGattCharacteristic cmdCharacteristic; - private BluetoothGattCharacteristic dataCharacteristic; + private BleIO bleio; @Inject public BleManager(Context context) { @@ -66,13 +58,6 @@ public class BleManager implements OmnipodDashCommunicationManager { return ret; } - private static UUID uuidFromString(String s) { - return new UUID( - new BigInteger(s.replace("-", "").substring(0, 16), 16).longValue(), - new BigInteger(s.replace("-", "").substring(16), 16).longValue() - ); - } - public void activateNewPod() throws InterruptedException, ScanFailException, @@ -82,78 +67,46 @@ public class BleManager implements OmnipodDashCommunicationManager { PodScanner podScanner = new PodScanner(this.aapsLogger, this.bluetoothAdapter); this.podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).getScanResult().getDevice().getAddress(); // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - this.connect(); - // do the dance: send SP0, SP1, etc - // get and save LTK + this.connect_(); } - public void connect() + public void connect_() throws FailedToConnectException, - CouldNotSendBleException { + CouldNotSendBleException, + InterruptedException { // TODO: locking? BluetoothDevice podDevice = this.bluetoothAdapter.getRemoteDevice(this.podAddress); - BluetoothGattCallback bleCommCallback = new BleCommCallbacks(); + + Map> incomingPackets = new EnumMap>(CharacteristicType.class); + incomingPackets.put(CharacteristicType.CMD, new LinkedBlockingDeque<>()); + incomingPackets.put(CharacteristicType.DATA, new LinkedBlockingDeque<>()); + incomingPackets = Collections.unmodifiableMap(incomingPackets); + + BleCommCallbacks bleCommCallbacks = new BleCommCallbacks(aapsLogger, incomingPackets); aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to " + this.podAddress); - gatt = podDevice.connectGatt(this.context, true, bleCommCallback, BluetoothDevice.TRANSPORT_LE); - - try { - Thread.sleep(CONNECT_TIMEOUT_MS); - } catch (InterruptedException e) { - // we get interrupted on successful connection - // TODO: interrupt this thread onConnect() + boolean autoConnect = true; + if (BuildConfig.DEBUG) { + autoConnect = false; + // TODO: remove this in the future + // it's easier to start testing from scratch on each run. } + gatt = podDevice.connectGatt(this.context, autoConnect, bleCommCallbacks, BluetoothDevice.TRANSPORT_LE); + + bleCommCallbacks.waitForConnection(CONNECT_TIMEOUT_MS); int connectionState = this.bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT); aapsLogger.debug(LTag.PUMPBTCOMM, "GATT connection state: " + connectionState); if (connectionState != BluetoothProfile.STATE_CONNECTED) { throw new FailedToConnectException(this.podAddress); } - this.discoverServicesAndSayHello(gatt); - } + ServiceDiscoverer discoverer = new ServiceDiscoverer(this.aapsLogger, gatt, bleCommCallbacks); + Map chars = discoverer.discoverServices(); - private void discoverServicesAndSayHello(BluetoothGatt gatt) - throws FailedToConnectException, - CouldNotSendBleException { - gatt.discoverServices(); - try { - Thread.sleep(CONNECT_TIMEOUT_MS); - } catch (InterruptedException e) { - // we get interrupted on successfull connection - // TODO: interrupt this thread onConnect() - } - - BluetoothGattService service = gatt.getService(uuidFromString(SERVICE_UUID)); - if (service == null) { - throw new ServiceNotFoundException(SERVICE_UUID); - } - BluetoothGattCharacteristic cmdChar = service.getCharacteristic(uuidFromString(CMD_CHARACTERISTIC_UUID)); - if (cmdChar == null) { - throw new CharacteristicNotFoundException(CMD_CHARACTERISTIC_UUID); - } - BluetoothGattCharacteristic dataChar = service.getCharacteristic(uuidFromString(DATA_CHARACTERISTIC_UUID)); - if (dataChar == null) { - throw new CharacteristicNotFoundException(DATA_CHARACTERISTIC_UUID); - } - this.cmdCharacteristic = cmdChar; - this.dataCharacteristic = dataChar; - - BleCommand hello = new BleCommandHello(CONTROLLER_ID); - if (!this.sendCmd(hello.asByteArray())) { - throw new CouldNotSendBleCmdException(); - } - aapsLogger.debug(LTag.PUMPBTCOMM, "saying hello to the pod" + hello.asByteArray()); - - } - - private boolean sendCmd(byte[] payload) { - // TODO move out of here - this.cmdCharacteristic.setValue(payload); - boolean ret = this.gatt.writeCharacteristic(cmdCharacteristic); - aapsLogger.debug(LTag.PUMPBTCOMM, "Sending command status. data:" + payload.toString() + "status: " + ret); - return ret; + this.bleio = new BleIO(aapsLogger, chars, incomingPackets, gatt); + this.aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod"); + this.bleio.sendAndConfirmData(CharacteristicType.CMD, new BleCommandHello(CONTROLLER_ID).asByteArray()); } } - diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java new file mode 100644 index 0000000000..cdc4bdb46b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java @@ -0,0 +1,35 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; + +import java.math.BigInteger; +import java.util.UUID; + +public enum CharacteristicType { + CMD("1a7e-2441-e3ed-4464-8b7e-751e03d0dc5f"), + DATA("1a7e-2442-e3ed-4464-8b7e-751e03d0dc5f"); + + public final String value; + + CharacteristicType(String value) { + this.value = value; + } + + public static CharacteristicType byValue(byte value) { + for (CharacteristicType type : values()) { + if (type.value.equals(value)) { + return type; + } + } + throw new IllegalArgumentException("Unknown Characteristic Type: " + value); + } + + public String getValue() { + return this.value; + } + + public UUID getUUID() { + return new UUID( + new BigInteger(this.value.replace("-", "").substring(0, 16), 16).longValue(), + new BigInteger(this.value.replace("-", "").substring(16), 16).longValue() + ); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java new file mode 100644 index 0000000000..c30cfce8e9 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java @@ -0,0 +1,74 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattService; + +import java.math.BigInteger; +import java.util.Collections; +import java.util.EnumMap; +import java.util.Map; +import java.util.UUID; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException; + +public class ServiceDiscoverer { + private static final String SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f"; + private static final int DISCOVER_SERVICES_TIMEOUT_MS = 5000; + + private final BluetoothGatt gatt; + private final BleCommCallbacks bleCallbacks; + private final AAPSLogger logger; + private Map chars; + + public ServiceDiscoverer(AAPSLogger logger, BluetoothGatt gatt, BleCommCallbacks bleCallbacks) { + this.gatt = gatt; + this.bleCallbacks = bleCallbacks; + this.logger = logger; + } + + private static UUID uuidFromString(String s) { + return new UUID( + new BigInteger(s.replace("-", "").substring(0, 16), 16).longValue(), + new BigInteger(s.replace("-", "").substring(16), 16).longValue() + ); + } + + /*** + * This is first step after connection establishment + */ + public Map discoverServices() + throws InterruptedException, + ServiceNotFoundException, + CharacteristicNotFoundException { + + logger.debug(LTag.PUMPBTCOMM, "Discovering services"); + gatt.discoverServices(); + this.bleCallbacks.waitForServiceDiscovery(DISCOVER_SERVICES_TIMEOUT_MS); + logger.debug(LTag.PUMPBTCOMM, "Services discovered"); + + BluetoothGattService service = gatt.getService( + uuidFromString(SERVICE_UUID)); + if (service == null) { + throw new ServiceNotFoundException(SERVICE_UUID); + } + BluetoothGattCharacteristic cmdChar = service.getCharacteristic(CharacteristicType.CMD.getUUID()); + if (cmdChar == null) { + throw new CharacteristicNotFoundException(CharacteristicType.CMD.getValue()); + } + BluetoothGattCharacteristic dataChar = service.getCharacteristic(CharacteristicType.DATA.getUUID()); + if (dataChar == null) { + throw new CharacteristicNotFoundException(CharacteristicType.DATA.getValue()); + } + Map chars = new EnumMap(CharacteristicType.class); + chars.put(CharacteristicType.CMD, cmdChar); + chars.put(CharacteristicType.DATA, dataChar); + this.chars = Collections.unmodifiableMap(chars); + return this.chars; + } + +} + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java similarity index 96% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java index 86cd356ff3..4af111d633 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommand.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command; import org.jetbrains.annotations.NotNull; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java similarity index 95% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java index 3bcabacc28..56659f45e5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandHello.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command; import java.nio.ByteBuffer; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java similarity index 97% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java index 4bd71a357d..38225bf799 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/blecommand/BleCommandType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.blecommand; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command; public enum BleCommandType { RTS((byte) 0x00), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java deleted file mode 100644 index ae2d1e4be4..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleCmdException.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class CouldNotSendBleCmdException extends CouldNotSendBleException { -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java index 8bca9c732d..6bd30f5ff8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java @@ -1,4 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; public class CouldNotSendBleException extends Exception { + public CouldNotSendBleException(String msg) { + super(msg); + } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java new file mode 100644 index 0000000000..54babad049 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet; + +public class BlePacket { +} From b4d769844c61aae8744afe5111c34b865f18c6f6 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Wed, 24 Feb 2021 13:00:08 +0100 Subject: [PATCH 006/649] ble-io: implement confirmation for writes and make sure there is only one one IO operation in progress. In theory, we could have parallel IO operations on each characteristic, but I'm not sure yet if we really need to support that. implement reads enable notifications. Use BlockingQueue for write confirmations --- .../dash/driver/comm/BleCommCallbacks.java | 55 ------- .../pump/omnipod/dash/driver/comm/BleIO.java | 76 --------- .../omnipod/dash/driver/comm/BleManager.java | 25 ++- .../dash/driver/comm/CharacteristicType.java | 6 +- .../dash/driver/comm/ServiceDiscoverer.java | 1 + .../comm/callbacks/BleCommCallbacks.java | 147 ++++++++++++++++++ .../CharacteristicWriteConfirmation.java | 11 ++ .../DescriptorWriteConfirmation.java | 11 ++ .../comm/exceptions/BleIOBusyException.java | 4 + ...uldNotConfirmDescriptorWriteException.java | 12 ++ .../comm/exceptions/CouldNotConfirmWrite.java | 13 ++ .../CouldNotEnableNotifications.java | 9 ++ .../DescriptorNotFoundException.java | 4 + .../omnipod/dash/driver/comm/io/BleIO.java | 140 +++++++++++++++++ .../omnipod/dash/driver/comm/io/IOState.java | 7 + 15 files changed, 381 insertions(+), 140 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java deleted file mode 100644 index aa8044266f..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleCommCallbacks.java +++ /dev/null @@ -1,55 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; - -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCallback; -import android.bluetooth.BluetoothProfile; - -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; - -public class BleCommCallbacks extends BluetoothGattCallback { - private final CountDownLatch serviceDiscoveryComplete; - private final CountDownLatch connected; - private final AAPSLogger aapsLogger; - private final Map> incomingPackets; - - public BleCommCallbacks(AAPSLogger aapsLogger, Map> incomingPackets) { - this.serviceDiscoveryComplete = new CountDownLatch(1); - this.connected = new CountDownLatch(1); - this.aapsLogger = aapsLogger; - this.incomingPackets = incomingPackets; - } - - - @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - super.onConnectionStateChange(gatt, status, newState); - this.aapsLogger.debug(LTag.PUMPBTCOMM,"OnConnectionStateChange discovered with status/state"+status+"/"+newState); - if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { - this.connected.countDown(); - } - } - - @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { - super.onServicesDiscovered(gatt, status); - this.aapsLogger.debug(LTag.PUMPBTCOMM,"OnServicesDiscovered with status"+status); - if (status == gatt.GATT_SUCCESS) { - this.serviceDiscoveryComplete.countDown(); - } - } - - public void waitForConnection(int timeout_ms) - throws InterruptedException { - this.connected.await(timeout_ms, TimeUnit.MILLISECONDS); - } - - public void waitForServiceDiscovery(int timeout_ms) - throws InterruptedException { - this.serviceDiscoveryComplete.await(timeout_ms, TimeUnit.MILLISECONDS); - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java deleted file mode 100644 index 40c76d5de2..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleIO.java +++ /dev/null @@ -1,76 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; - -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCharacteristic; - -import java.util.Map; -import java.util.concurrent.BlockingQueue; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; - - -public class BleIO { - private static final int DEFAULT_IO_TIMEOUT_MS = 1000; - - private final AAPSLogger aapsLogger; - private final Map chars; - private final Map> incomingPackets; - private final BluetoothGatt gatt; - - - public BleIO(AAPSLogger aapsLogger, Map chars, Map> incomingPackets, BluetoothGatt gatt) { - this.aapsLogger = aapsLogger; - this.chars = chars; - this.incomingPackets = incomingPackets; - this.gatt = gatt; - } - - /*** - * - * @param characteristic where to read from(CMD or DATA) - * @return a byte array with the received data - */ - public byte[] receiveData(CharacteristicType characteristic) { - return null; - } - - /*** - * - * @param characteristic where to write to(CMD or DATA) - * @param packet the data to send - * @throws CouldNotSendBleException - */ - public void sendAndConfirmData(CharacteristicType characteristic, byte[] packet) - throws CouldNotSendBleException { - aapsLogger.debug(LTag.PUMPBTCOMM, "BleIO: Sending data on " + characteristic.name() + " :: " +packet.toString()); - BluetoothGattCharacteristic ch = chars.get(characteristic); - boolean set = ch.setValue(packet); - if (!set) { - throw new CouldNotSendBleException("setValue"); - } - boolean sent = this.gatt.writeCharacteristic(ch); - if (!sent) { - throw new CouldNotSendBleException("writeCharacteristic"); - } - // TODO: wait for confirmation callback - } - - /** - * Called before sending a new message. - * The incoming queues should be empty, so we log when they are not. - */ - public void flushIncomingQueues() { - - } - - /** - * Enable intentions on the characteristics. - * This will signal the pod it can start sending back data - */ - public void readyToRead() - throws CouldNotSendBleException { - - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java index fdacd4e395..35164c4cc1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java @@ -13,6 +13,7 @@ import java.util.EnumMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeoutException; import javax.inject.Inject; import javax.inject.Singleton; @@ -20,7 +21,14 @@ import javax.inject.Singleton; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.BleIOBusyException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotEnableNotifications; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DescriptorNotFoundException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.FailedToConnectException; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; @@ -62,18 +70,22 @@ public class BleManager implements OmnipodDashCommunicationManager { throws InterruptedException, ScanFailException, FailedToConnectException, - CouldNotSendBleException { + CouldNotSendBleException, + BleIOBusyException, + TimeoutException, + CouldNotConfirmWrite, CouldNotEnableNotifications, DescriptorNotFoundException, CouldNotConfirmDescriptorWriteException { this.aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation"); PodScanner podScanner = new PodScanner(this.aapsLogger, this.bluetoothAdapter); this.podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).getScanResult().getDevice().getAddress(); // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - this.connect_(); + this.connect(); } - public void connect_() + public void connect() throws FailedToConnectException, CouldNotSendBleException, - InterruptedException { + InterruptedException, + BleIOBusyException, TimeoutException, CouldNotConfirmWrite, CouldNotEnableNotifications, DescriptorNotFoundException, CouldNotConfirmDescriptorWriteException { // TODO: locking? BluetoothDevice podDevice = this.bluetoothAdapter.getRemoteDevice(this.podAddress); @@ -105,8 +117,9 @@ public class BleManager implements OmnipodDashCommunicationManager { ServiceDiscoverer discoverer = new ServiceDiscoverer(this.aapsLogger, gatt, bleCommCallbacks); Map chars = discoverer.discoverServices(); - this.bleio = new BleIO(aapsLogger, chars, incomingPackets, gatt); + this.bleio = new BleIO(aapsLogger, chars, incomingPackets, gatt, bleCommCallbacks); this.aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod"); - this.bleio.sendAndConfirmData(CharacteristicType.CMD, new BleCommandHello(CONTROLLER_ID).asByteArray()); + this.bleio.sendAndConfirmPacket(CharacteristicType.CMD, new BleCommandHello(CONTROLLER_ID).asByteArray()); + this.bleio.readyToRead(); } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java index cdc4bdb46b..73bcc9de61 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java @@ -4,8 +4,8 @@ import java.math.BigInteger; import java.util.UUID; public enum CharacteristicType { - CMD("1a7e-2441-e3ed-4464-8b7e-751e03d0dc5f"), - DATA("1a7e-2442-e3ed-4464-8b7e-751e03d0dc5f"); + CMD("1a7e2441-e3ed-4464-8b7e-751e03d0dc5f"), + DATA("1a7e2442-e3ed-4464-8b7e-751e03d0dc5f"); public final String value; @@ -13,7 +13,7 @@ public enum CharacteristicType { this.value = value; } - public static CharacteristicType byValue(byte value) { + public static CharacteristicType byValue(String value) { for (CharacteristicType type : values()) { if (type.value.equals(value)) { return type; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java index c30cfce8e9..13828db4d0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java @@ -12,6 +12,7 @@ import java.util.UUID; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException; import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java new file mode 100644 index 0000000000..28a202606e --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java @@ -0,0 +1,147 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCallback; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; +import android.bluetooth.BluetoothProfile; + +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite; + +public class BleCommCallbacks extends BluetoothGattCallback { + private final static int WRITE_CONFIRM_TIMEOUT_MS = 10; // the other thread should be waiting for the exchange + + private final CountDownLatch serviceDiscoveryComplete; + private final CountDownLatch connected; + private final AAPSLogger aapsLogger; + private final Map> incomingPackets; + private final BlockingQueue writeQueue; + private final BlockingQueue descriptorWriteQueue; + + public BleCommCallbacks(AAPSLogger aapsLogger, Map> incomingPackets) { + this.serviceDiscoveryComplete = new CountDownLatch(1); + this.connected = new CountDownLatch(1); + this.aapsLogger = aapsLogger; + this.incomingPackets = incomingPackets; + this.writeQueue = new LinkedBlockingQueue<>(1); + this.descriptorWriteQueue = new LinkedBlockingQueue<>(1); + } + + @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { + super.onConnectionStateChange(gatt, status, newState); + this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnConnectionStateChange discovered with status/state" + status + "/" + newState); + if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { + this.connected.countDown(); + } + } + + @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { + super.onServicesDiscovered(gatt, status); + this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnServicesDiscovered with status" + status); + if (status == BluetoothGatt.GATT_SUCCESS) { + this.serviceDiscoveryComplete.countDown(); + } + } + + public void waitForConnection(int timeout_ms) + throws InterruptedException { + this.connected.await(timeout_ms, TimeUnit.MILLISECONDS); + } + + public void waitForServiceDiscovery(int timeout_ms) + throws InterruptedException { + this.serviceDiscoveryComplete.await(timeout_ms, TimeUnit.MILLISECONDS); + } + + public void confirmWrite(CharacteristicType characteristicType, byte[] expectedPayload, int timeout_ms) throws InterruptedException, TimeoutException, CouldNotConfirmWrite { + CharacteristicWriteConfirmation received = this.writeQueue.poll(timeout_ms, TimeUnit.MILLISECONDS); + if (received == null ) { + throw new TimeoutException(); + } + if (!Arrays.equals(expectedPayload, received.payload)) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload + ". Status: "+received.status); + throw new CouldNotConfirmWrite(expectedPayload, received.payload); + } + this.aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload); + } + + @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { + super.onCharacteristicWrite(gatt, characteristic, status); + byte[] received = null; + + if (status == BluetoothGatt.GATT_SUCCESS) { + received = characteristic.getValue(); + this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite value " + characteristic.getStringValue(0)); + } + + this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite with status/char/value " + + status + "/" + + CharacteristicType.byValue(characteristic.getUuid().toString()) + "/" + + received); + try { + if (this.writeQueue.size() > 0) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Write confirm queue should be empty. found: "+ this.writeQueue.size()); + this.writeQueue.clear(); + } + boolean offered = this.writeQueue.offer(new CharacteristicWriteConfirmation(received, status), WRITE_CONFIRM_TIMEOUT_MS, TimeUnit.MILLISECONDS); + if (!offered) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed write confirmation"); + } + } catch (InterruptedException e) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while sending write confirmation"); + } + } + + @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { + super.onCharacteristicChanged(gatt, characteristic); + + byte[] payload = characteristic.getValue(); + CharacteristicType characteristicType = CharacteristicType.byValue(characteristic.getUuid().toString()); + this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicChanged with char/value " + + characteristicType + "/" + + payload); + this.incomingPackets.get(characteristicType).add(payload); + } + + public void confirmWriteDescriptor(String descriptorUUID, int timeout_ms) throws InterruptedException, CouldNotConfirmDescriptorWriteException { + DescriptorWriteConfirmation confirmed = this.descriptorWriteQueue.poll(timeout_ms, TimeUnit.MILLISECONDS); + if (!descriptorUUID.equals(confirmed.uuid)) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got " + confirmed.uuid + ".Expected: " + descriptorUUID + ". Status: " + confirmed.status); + throw new CouldNotConfirmDescriptorWriteException(confirmed.uuid, descriptorUUID); + } + } + + @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { + super.onDescriptorWrite(gatt, descriptor, status); + String uuid = null; + if (status == BluetoothGatt.GATT_SUCCESS) { + uuid = descriptor.getUuid().toString(); + } + DescriptorWriteConfirmation confirmation = new DescriptorWriteConfirmation(status, uuid); + try { + if (this.descriptorWriteQueue.size() > 0) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Descriptor write queue should be empty, found: "+ this.descriptorWriteQueue.size()); + this.descriptorWriteQueue.clear(); + } + + boolean offered = this.descriptorWriteQueue.offer(confirmation, WRITE_CONFIRM_TIMEOUT_MS, TimeUnit.MILLISECONDS); + if (!offered) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed descriptor write confirmation"); + } + } catch (InterruptedException e) { + this.aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while sending descriptor write confirmation"); + } + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java new file mode 100644 index 0000000000..cf2e8bff77 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks; + +public class CharacteristicWriteConfirmation { + public byte[] payload; + public int status; + + public CharacteristicWriteConfirmation(byte[] payload, int status) { + this.payload = payload; + this.status = status; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java new file mode 100644 index 0000000000..88ae897b1b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks; + +public class DescriptorWriteConfirmation { + public int status; + public String uuid; + + public DescriptorWriteConfirmation(int status, String uuid) { + this.status = status; + this.uuid = uuid; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java new file mode 100644 index 0000000000..53f85c5a6f --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class BleIOBusyException extends Exception{ +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java new file mode 100644 index 0000000000..b2034fd087 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class CouldNotConfirmDescriptorWriteException extends Exception{ + private final String received; + private final String expected; + + public CouldNotConfirmDescriptorWriteException(String received, String expected) { + super(); + this.received = received; + this.expected = expected; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java new file mode 100644 index 0000000000..f422746180 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class CouldNotConfirmWrite extends Exception { + + private final byte[] sent; + private final Object confirmed; + + public CouldNotConfirmWrite(byte[] sent, byte[] confirmed) { + super(); + this.sent = sent; + this.confirmed = confirmed; + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java new file mode 100644 index 0000000000..261490dee5 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType; + +public class CouldNotEnableNotifications extends Exception { + public CouldNotEnableNotifications(CharacteristicType cmd) { + super(cmd.getValue()); + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java new file mode 100644 index 0000000000..d7dc3473eb --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; + +public class DescriptorNotFoundException extends Exception { +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java new file mode 100644 index 0000000000..75490b33e3 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java @@ -0,0 +1,140 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io; + +import android.bluetooth.BluetoothGatt; +import android.bluetooth.BluetoothGattCharacteristic; +import android.bluetooth.BluetoothGattDescriptor; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.BleIOBusyException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotEnableNotifications; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DescriptorNotFoundException; + + +public class BleIO { + private static final int DEFAULT_IO_TIMEOUT_MS = 1000; + + private final AAPSLogger aapsLogger; + private final Map chars; + private final Map> incomingPackets; + private final BluetoothGatt gatt; + private final BleCommCallbacks bleCommCallbacks; + + private IOState state; + + public BleIO(AAPSLogger aapsLogger, Map chars, Map> incomingPackets, BluetoothGatt gatt, BleCommCallbacks bleCommCallbacks) { + this.aapsLogger = aapsLogger; + this.chars = chars; + this.incomingPackets = incomingPackets; + this.gatt = gatt; + this.bleCommCallbacks = bleCommCallbacks; + this.state = IOState.IDLE; + } + + /*** + * + * @param characteristic where to read from(CMD or DATA) + * @return a byte array with the received data + */ + public byte[] receivePacket(CharacteristicType characteristic) throws + BleIOBusyException, + InterruptedException, + TimeoutException { + synchronized (this.state) { + if (this.state != IOState.IDLE) { + throw new BleIOBusyException(); + } + this.state = IOState.READING; + } + byte[] ret = this.incomingPackets.get(characteristic).poll(DEFAULT_IO_TIMEOUT_MS, TimeUnit.MILLISECONDS); + if (ret == null) { + throw new TimeoutException(); + } + synchronized (this.state) { + this.state = IOState.IDLE; + } + return ret; + } + + /*** + * + * @param characteristic where to write to(CMD or DATA) + * @param payload the data to send + * @throws CouldNotSendBleException + */ + public void sendAndConfirmPacket(CharacteristicType characteristic, byte[] payload) + throws CouldNotSendBleException, + BleIOBusyException, + InterruptedException, + CouldNotConfirmWrite, + TimeoutException { + synchronized (this.state) { + if (this.state != IOState.IDLE) { + throw new BleIOBusyException(); + } + this.state = IOState.WRITING; + } + + aapsLogger.debug(LTag.PUMPBTCOMM, "BleIO: Sending data on" + characteristic.name() + "/" + payload.toString()); + BluetoothGattCharacteristic ch = chars.get(characteristic); + boolean set = ch.setValue(payload); + if (!set) { + throw new CouldNotSendBleException("setValue"); + } + boolean sent = this.gatt.writeCharacteristic(ch); + if (!sent) { + throw new CouldNotSendBleException("writeCharacteristic"); + } + this.bleCommCallbacks.confirmWrite(CharacteristicType.CMD, payload, DEFAULT_IO_TIMEOUT_MS); + synchronized (this.state) { + this.state = IOState.IDLE; + } + } + + /** + * Called before sending a new message. + * The incoming queues should be empty, so we log when they are not. + */ + public void flushIncomingQueues() { + + } + + /** + * Enable intentions on the characteristics. + * This will signal the pod it can start sending back data + * @return + */ + public void readyToRead() + throws CouldNotSendBleException, + CouldNotEnableNotifications, + DescriptorNotFoundException, + InterruptedException, CouldNotConfirmDescriptorWriteException { + + for (CharacteristicType type : CharacteristicType.values()) { + BluetoothGattCharacteristic ch = this.chars.get(type); + boolean notificationSet = this.gatt.setCharacteristicNotification(ch, true); + if (!notificationSet) { + throw new CouldNotEnableNotifications(type); + } + List descriptors = ch.getDescriptors(); + if (descriptors.size() != 1) { + throw new DescriptorNotFoundException(); + } + BluetoothGattDescriptor descriptor = descriptors.get(0); + descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); + gatt.writeDescriptor(descriptor); + bleCommCallbacks.confirmWriteDescriptor(descriptor.getUuid().toString(), DEFAULT_IO_TIMEOUT_MS); + } + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java new file mode 100644 index 0000000000..cd9ae12297 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io; + +public enum IOState { + IDLE, + WRITING, + READING; +} From 647793e0b7ef12ac81f23f7455d64b20e3fcae4a Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Wed, 24 Feb 2021 18:07:19 +0100 Subject: [PATCH 007/649] Switch to Kotlin. and small fixes after conversion --- .../omnipod/dash/driver/comm/BleManager.java | 125 --------------- .../omnipod/dash/driver/comm/BleManager.kt | 99 ++++++++++++ .../dash/driver/comm/CharacteristicType.java | 35 ----- .../dash/driver/comm/CharacteristicType.kt | 26 ++++ ...ava => OmnipodDashCommunicationManager.kt} | 5 +- .../dash/driver/comm/ServiceDiscoverer.java | 75 --------- .../dash/driver/comm/ServiceDiscoverer.kt | 47 ++++++ .../comm/callbacks/BleCommCallbacks.java | 147 ------------------ .../driver/comm/callbacks/BleCommCallbacks.kt | 142 +++++++++++++++++ .../CharacteristicWriteConfirmation.java | 11 -- .../CharacteristicWriteConfirmation.kt | 3 + .../DescriptorWriteConfirmation.java | 11 -- .../callbacks/DescriptorWriteConfirmation.kt | 3 + .../dash/driver/comm/command/BleCommand.java | 22 --- .../dash/driver/comm/command/BleCommand.kt | 21 +++ .../driver/comm/command/BleCommandHello.java | 14 -- .../driver/comm/command/BleCommandHello.kt | 10 ++ .../driver/comm/command/BleCommandType.java | 30 ---- .../driver/comm/command/BleCommandType.kt | 17 ++ .../comm/exceptions/BleIOBusyException.java | 4 - .../comm/exceptions/BleIOBusyException.kt | 3 + .../CharacteristicNotFoundException.java | 7 - .../CharacteristicNotFoundException.kt | 3 + ...uldNotConfirmDescriptorWriteException.java | 12 -- ...CouldNotConfirmDescriptorWriteException.kt | 3 + .../comm/exceptions/CouldNotConfirmWrite.java | 13 -- .../comm/exceptions/CouldNotConfirmWrite.kt | 10 ++ .../CouldNotEnableNotifications.java | 9 -- .../exceptions/CouldNotEnableNotifications.kt | 5 + .../exceptions/CouldNotSendBleException.java | 7 - .../exceptions/CouldNotSendBleException.kt | 3 + .../DescriptorNotFoundException.java | 4 - .../exceptions/DescriptorNotFoundException.kt | 3 + .../DiscoveredInvalidPodException.java | 11 -- .../DiscoveredInvalidPodException.kt | 5 + .../exceptions/FailedToConnectException.java | 11 -- .../exceptions/FailedToConnectException.kt | 6 + .../comm/exceptions/ScanFailException.java | 10 -- .../comm/exceptions/ScanFailException.kt | 6 + .../ScanFailFoundTooManyException.java | 20 --- .../ScanFailFoundTooManyException.kt | 15 ++ .../exceptions/ScanFailNotFoundException.java | 4 - .../exceptions/ScanFailNotFoundException.kt | 3 + .../exceptions/ServiceNotFoundException.java | 7 - .../exceptions/ServiceNotFoundException.kt | 3 + .../omnipod/dash/driver/comm/io/BleIO.java | 140 ----------------- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 104 +++++++++++++ .../omnipod/dash/driver/comm/io/IOState.java | 7 - .../omnipod/dash/driver/comm/io/IOState.kt | 5 + .../packet/{BlePacket.java => BlePacket.kt} | 5 +- .../driver/comm/scan/BleDiscoveredDevice.java | 94 ----------- .../driver/comm/scan/BleDiscoveredDevice.kt | 78 ++++++++++ .../dash/driver/comm/scan/PodScanner.java | 62 -------- .../dash/driver/comm/scan/PodScanner.kt | 48 ++++++ .../dash/driver/comm/scan/ScanCollector.java | 66 -------- .../dash/driver/comm/scan/ScanCollector.kt | 51 ++++++ 56 files changed, 726 insertions(+), 964 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{OmnipodDashCommunicationManager.java => OmnipodDashCommunicationManager.kt} (50%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/{BlePacket.java => BlePacket.kt} (59%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java deleted file mode 100644 index 35164c4cc1..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.java +++ /dev/null @@ -1,125 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; -import android.content.Context; - -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.TimeoutException; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.BleIOBusyException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotEnableNotifications; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DescriptorNotFoundException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.FailedToConnectException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner; - -@Singleton -public class BleManager implements OmnipodDashCommunicationManager { - private static final int CONNECT_TIMEOUT_MS = 5000; - private static final int CONTROLLER_ID = 4242; // TODO read from preferences or somewhere else. - - private static BleManager instance = null; - private final Context context; - private final BluetoothAdapter bluetoothAdapter; - private final BluetoothManager bluetoothManager; - @Inject AAPSLogger aapsLogger; - private String podAddress; - private BluetoothGatt gatt; - private BleIO bleio; - - @Inject - public BleManager(Context context) { - this.context = context; - this.bluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); - this.bluetoothAdapter = bluetoothManager.getAdapter(); - } - - public static BleManager getInstance(Context context) { - BleManager ret; - synchronized (BleManager.class) { - if (instance == null) { - instance = new BleManager(context); - } - ret = instance; - } - return ret; - } - - public void activateNewPod() - throws InterruptedException, - ScanFailException, - FailedToConnectException, - CouldNotSendBleException, - BleIOBusyException, - TimeoutException, - CouldNotConfirmWrite, CouldNotEnableNotifications, DescriptorNotFoundException, CouldNotConfirmDescriptorWriteException { - this.aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation"); - PodScanner podScanner = new PodScanner(this.aapsLogger, this.bluetoothAdapter); - this.podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).getScanResult().getDevice().getAddress(); - // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - this.connect(); - } - - public void connect() - throws FailedToConnectException, - CouldNotSendBleException, - InterruptedException, - BleIOBusyException, TimeoutException, CouldNotConfirmWrite, CouldNotEnableNotifications, DescriptorNotFoundException, CouldNotConfirmDescriptorWriteException { - // TODO: locking? - - BluetoothDevice podDevice = this.bluetoothAdapter.getRemoteDevice(this.podAddress); - - Map> incomingPackets = new EnumMap>(CharacteristicType.class); - incomingPackets.put(CharacteristicType.CMD, new LinkedBlockingDeque<>()); - incomingPackets.put(CharacteristicType.DATA, new LinkedBlockingDeque<>()); - incomingPackets = Collections.unmodifiableMap(incomingPackets); - - BleCommCallbacks bleCommCallbacks = new BleCommCallbacks(aapsLogger, incomingPackets); - - aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to " + this.podAddress); - boolean autoConnect = true; - if (BuildConfig.DEBUG) { - autoConnect = false; - // TODO: remove this in the future - // it's easier to start testing from scratch on each run. - } - gatt = podDevice.connectGatt(this.context, autoConnect, bleCommCallbacks, BluetoothDevice.TRANSPORT_LE); - - bleCommCallbacks.waitForConnection(CONNECT_TIMEOUT_MS); - - int connectionState = this.bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT); - aapsLogger.debug(LTag.PUMPBTCOMM, "GATT connection state: " + connectionState); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { - throw new FailedToConnectException(this.podAddress); - } - - ServiceDiscoverer discoverer = new ServiceDiscoverer(this.aapsLogger, gatt, bleCommCallbacks); - Map chars = discoverer.discoverServices(); - - this.bleio = new BleIO(aapsLogger, chars, incomingPackets, gatt, bleCommCallbacks); - this.aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod"); - this.bleio.sendAndConfirmPacket(CharacteristicType.CMD, new BleCommandHello(CONTROLLER_ID).asByteArray()); - this.bleio.readyToRead(); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt new file mode 100644 index 0000000000..630d57c1b9 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt @@ -0,0 +1,99 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm + + +import javax.inject.Singleton +import javax.inject.Inject +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashCommunicationManager +import android.bluetooth.BluetoothAdapter +import android.bluetooth.BluetoothManager +import info.nightscout.androidaps.logging.AAPSLogger +import android.bluetooth.BluetoothGatt +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO +import kotlin.Throws +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.FailedToConnectException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.BleIOBusyException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotEnableNotifications +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DescriptorNotFoundException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner +import android.bluetooth.BluetoothDevice +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager +import android.bluetooth.BluetoothProfile +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ServiceDiscoverer +import android.bluetooth.BluetoothGattCharacteristic +import android.content.Context +import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello +import java.util.* +import java.util.concurrent.BlockingQueue +import java.util.concurrent.LinkedBlockingDeque +import java.util.concurrent.TimeoutException + +@Singleton +class BleManager @Inject constructor(private val context: Context) : OmnipodDashCommunicationManager { + + private val bluetoothAdapter: BluetoothAdapter + private val bluetoothManager: BluetoothManager + + @Inject lateinit var aapsLogger: AAPSLogger + private var podAddress: String? = null + private var gatt: BluetoothGatt? = null + private var bleio: BleIO? = null + @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWrite::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) + fun activateNewPod() { + aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") + val podScanner = PodScanner(aapsLogger, bluetoothAdapter) + podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address + // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; + connect() + } + + @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWrite::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) + fun connect() { + // TODO: locking? + val podDevice = bluetoothAdapter.getRemoteDevice(podAddress) + var incomingPackets: Map> = + mapOf(CharacteristicType.CMD to LinkedBlockingDeque(), + CharacteristicType.DATA to LinkedBlockingDeque()); + val bleCommCallbacks = BleCommCallbacks(aapsLogger, incomingPackets) + aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to " + podAddress) + var autoConnect = true + if (BuildConfig.DEBUG) { + autoConnect = false + // TODO: remove this in the future + // it's easier to start testing from scratch on each run. + } + val gatt = podDevice.connectGatt(context, autoConnect, bleCommCallbacks, BluetoothDevice.TRANSPORT_LE) + this.gatt = gatt + + bleCommCallbacks.waitForConnection(CONNECT_TIMEOUT_MS) + val connectionState = bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT) + aapsLogger.debug(LTag.PUMPBTCOMM, "GATT connection state: $connectionState") + if (connectionState != BluetoothProfile.STATE_CONNECTED) { + throw FailedToConnectException(podAddress) + } + val discoverer = ServiceDiscoverer(aapsLogger, gatt, bleCommCallbacks) + val chars = discoverer.discoverServices() + bleio = BleIO(aapsLogger, chars, incomingPackets, gatt, bleCommCallbacks) + aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod") + bleio!!.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandHello(CONTROLLER_ID).asByteArray()) + bleio!!.readyToRead() + } + + companion object { + + private const val CONNECT_TIMEOUT_MS = 5000 + private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. + } + + init { + bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + bluetoothAdapter = bluetoothManager.adapter + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java deleted file mode 100644 index 73bcc9de61..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.java +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; - -import java.math.BigInteger; -import java.util.UUID; - -public enum CharacteristicType { - CMD("1a7e2441-e3ed-4464-8b7e-751e03d0dc5f"), - DATA("1a7e2442-e3ed-4464-8b7e-751e03d0dc5f"); - - public final String value; - - CharacteristicType(String value) { - this.value = value; - } - - public static CharacteristicType byValue(String value) { - for (CharacteristicType type : values()) { - if (type.value.equals(value)) { - return type; - } - } - throw new IllegalArgumentException("Unknown Characteristic Type: " + value); - } - - public String getValue() { - return this.value; - } - - public UUID getUUID() { - return new UUID( - new BigInteger(this.value.replace("-", "").substring(0, 16), 16).longValue(), - new BigInteger(this.value.replace("-", "").substring(16), 16).longValue() - ); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt new file mode 100644 index 0000000000..600e4ba769 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt @@ -0,0 +1,26 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm + +import java.math.BigInteger +import java.util.* + +enum class CharacteristicType(val value: String) { + CMD("1a7e2441-e3ed-4464-8b7e-751e03d0dc5f"), DATA("1a7e2442-e3ed-4464-8b7e-751e03d0dc5f"); + + val uUID: UUID + get() = UUID( + BigInteger(value.replace("-", "").substring(0, 16), 16).toLong(), + BigInteger(value.replace("-", "").substring(16), 16).toLong() + ) + + companion object { + + @JvmStatic fun byValue(value: String): CharacteristicType { + for (type in values()) { + if (type.value == value) { + return type + } + } + throw IllegalArgumentException("Unknown Characteristic Type: $value") + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt similarity index 50% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt index a53f3e2b34..db95a2046b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt @@ -1,4 +1,3 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm -public interface OmnipodDashCommunicationManager { -} +interface OmnipodDashCommunicationManager \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java deleted file mode 100644 index 13828db4d0..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.java +++ /dev/null @@ -1,75 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm; - -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattService; - -import java.math.BigInteger; -import java.util.Collections; -import java.util.EnumMap; -import java.util.Map; -import java.util.UUID; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException; - -public class ServiceDiscoverer { - private static final String SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f"; - private static final int DISCOVER_SERVICES_TIMEOUT_MS = 5000; - - private final BluetoothGatt gatt; - private final BleCommCallbacks bleCallbacks; - private final AAPSLogger logger; - private Map chars; - - public ServiceDiscoverer(AAPSLogger logger, BluetoothGatt gatt, BleCommCallbacks bleCallbacks) { - this.gatt = gatt; - this.bleCallbacks = bleCallbacks; - this.logger = logger; - } - - private static UUID uuidFromString(String s) { - return new UUID( - new BigInteger(s.replace("-", "").substring(0, 16), 16).longValue(), - new BigInteger(s.replace("-", "").substring(16), 16).longValue() - ); - } - - /*** - * This is first step after connection establishment - */ - public Map discoverServices() - throws InterruptedException, - ServiceNotFoundException, - CharacteristicNotFoundException { - - logger.debug(LTag.PUMPBTCOMM, "Discovering services"); - gatt.discoverServices(); - this.bleCallbacks.waitForServiceDiscovery(DISCOVER_SERVICES_TIMEOUT_MS); - logger.debug(LTag.PUMPBTCOMM, "Services discovered"); - - BluetoothGattService service = gatt.getService( - uuidFromString(SERVICE_UUID)); - if (service == null) { - throw new ServiceNotFoundException(SERVICE_UUID); - } - BluetoothGattCharacteristic cmdChar = service.getCharacteristic(CharacteristicType.CMD.getUUID()); - if (cmdChar == null) { - throw new CharacteristicNotFoundException(CharacteristicType.CMD.getValue()); - } - BluetoothGattCharacteristic dataChar = service.getCharacteristic(CharacteristicType.DATA.getUUID()); - if (dataChar == null) { - throw new CharacteristicNotFoundException(CharacteristicType.DATA.getValue()); - } - Map chars = new EnumMap(CharacteristicType.class); - chars.put(CharacteristicType.CMD, cmdChar); - chars.put(CharacteristicType.DATA, dataChar); - this.chars = Collections.unmodifiableMap(chars); - return this.chars; - } - -} - diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt new file mode 100644 index 0000000000..85694a213a --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm + +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException +import java.math.BigInteger +import java.util.* + +class ServiceDiscoverer(private val logger: AAPSLogger, private val gatt: BluetoothGatt, private val bleCallbacks: BleCommCallbacks) { + + /*** + * This is first step after connection establishment + */ + @Throws(InterruptedException::class, ServiceNotFoundException::class, CharacteristicNotFoundException::class) + fun discoverServices(): Map { + logger.debug(LTag.PUMPBTCOMM, "Discovering services") + gatt.discoverServices() + bleCallbacks.waitForServiceDiscovery(DISCOVER_SERVICES_TIMEOUT_MS) + logger.debug(LTag.PUMPBTCOMM, "Services discovered") + val service = gatt.getService( + uuidFromString(SERVICE_UUID)) + ?: throw ServiceNotFoundException(SERVICE_UUID) + val cmdChar = service.getCharacteristic(CharacteristicType.CMD.uUID) + ?: throw CharacteristicNotFoundException(CharacteristicType.CMD.value) + val dataChar = service.getCharacteristic(CharacteristicType.DATA.uUID) + ?: throw CharacteristicNotFoundException(CharacteristicType.DATA.value) + var chars = mapOf(CharacteristicType.CMD to cmdChar, + CharacteristicType.DATA to dataChar) + return chars + } + + companion object { + private const val SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f" + private const val DISCOVER_SERVICES_TIMEOUT_MS = 5000 + private fun uuidFromString(s: String): UUID { + return UUID( + BigInteger(s.replace("-", "").substring(0, 16), 16).toLong(), + BigInteger(s.replace("-", "").substring(16), 16).toLong() + ) + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java deleted file mode 100644 index 28a202606e..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.java +++ /dev/null @@ -1,147 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks; - -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCallback; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattDescriptor; -import android.bluetooth.BluetoothProfile; - -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite; - -public class BleCommCallbacks extends BluetoothGattCallback { - private final static int WRITE_CONFIRM_TIMEOUT_MS = 10; // the other thread should be waiting for the exchange - - private final CountDownLatch serviceDiscoveryComplete; - private final CountDownLatch connected; - private final AAPSLogger aapsLogger; - private final Map> incomingPackets; - private final BlockingQueue writeQueue; - private final BlockingQueue descriptorWriteQueue; - - public BleCommCallbacks(AAPSLogger aapsLogger, Map> incomingPackets) { - this.serviceDiscoveryComplete = new CountDownLatch(1); - this.connected = new CountDownLatch(1); - this.aapsLogger = aapsLogger; - this.incomingPackets = incomingPackets; - this.writeQueue = new LinkedBlockingQueue<>(1); - this.descriptorWriteQueue = new LinkedBlockingQueue<>(1); - } - - @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - super.onConnectionStateChange(gatt, status, newState); - this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnConnectionStateChange discovered with status/state" + status + "/" + newState); - if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { - this.connected.countDown(); - } - } - - @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { - super.onServicesDiscovered(gatt, status); - this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnServicesDiscovered with status" + status); - if (status == BluetoothGatt.GATT_SUCCESS) { - this.serviceDiscoveryComplete.countDown(); - } - } - - public void waitForConnection(int timeout_ms) - throws InterruptedException { - this.connected.await(timeout_ms, TimeUnit.MILLISECONDS); - } - - public void waitForServiceDiscovery(int timeout_ms) - throws InterruptedException { - this.serviceDiscoveryComplete.await(timeout_ms, TimeUnit.MILLISECONDS); - } - - public void confirmWrite(CharacteristicType characteristicType, byte[] expectedPayload, int timeout_ms) throws InterruptedException, TimeoutException, CouldNotConfirmWrite { - CharacteristicWriteConfirmation received = this.writeQueue.poll(timeout_ms, TimeUnit.MILLISECONDS); - if (received == null ) { - throw new TimeoutException(); - } - if (!Arrays.equals(expectedPayload, received.payload)) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload + ". Status: "+received.status); - throw new CouldNotConfirmWrite(expectedPayload, received.payload); - } - this.aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload); - } - - @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - super.onCharacteristicWrite(gatt, characteristic, status); - byte[] received = null; - - if (status == BluetoothGatt.GATT_SUCCESS) { - received = characteristic.getValue(); - this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite value " + characteristic.getStringValue(0)); - } - - this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite with status/char/value " + - status + "/" + - CharacteristicType.byValue(characteristic.getUuid().toString()) + "/" + - received); - try { - if (this.writeQueue.size() > 0) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Write confirm queue should be empty. found: "+ this.writeQueue.size()); - this.writeQueue.clear(); - } - boolean offered = this.writeQueue.offer(new CharacteristicWriteConfirmation(received, status), WRITE_CONFIRM_TIMEOUT_MS, TimeUnit.MILLISECONDS); - if (!offered) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed write confirmation"); - } - } catch (InterruptedException e) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while sending write confirmation"); - } - } - - @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { - super.onCharacteristicChanged(gatt, characteristic); - - byte[] payload = characteristic.getValue(); - CharacteristicType characteristicType = CharacteristicType.byValue(characteristic.getUuid().toString()); - this.aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicChanged with char/value " + - characteristicType + "/" + - payload); - this.incomingPackets.get(characteristicType).add(payload); - } - - public void confirmWriteDescriptor(String descriptorUUID, int timeout_ms) throws InterruptedException, CouldNotConfirmDescriptorWriteException { - DescriptorWriteConfirmation confirmed = this.descriptorWriteQueue.poll(timeout_ms, TimeUnit.MILLISECONDS); - if (!descriptorUUID.equals(confirmed.uuid)) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got " + confirmed.uuid + ".Expected: " + descriptorUUID + ". Status: " + confirmed.status); - throw new CouldNotConfirmDescriptorWriteException(confirmed.uuid, descriptorUUID); - } - } - - @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { - super.onDescriptorWrite(gatt, descriptor, status); - String uuid = null; - if (status == BluetoothGatt.GATT_SUCCESS) { - uuid = descriptor.getUuid().toString(); - } - DescriptorWriteConfirmation confirmation = new DescriptorWriteConfirmation(status, uuid); - try { - if (this.descriptorWriteQueue.size() > 0) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Descriptor write queue should be empty, found: "+ this.descriptorWriteQueue.size()); - this.descriptorWriteQueue.clear(); - } - - boolean offered = this.descriptorWriteQueue.offer(confirmation, WRITE_CONFIRM_TIMEOUT_MS, TimeUnit.MILLISECONDS); - if (!offered) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed descriptor write confirmation"); - } - } catch (InterruptedException e) { - this.aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while sending descriptor write confirmation"); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt new file mode 100644 index 0000000000..1998d9b307 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -0,0 +1,142 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks + +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCallback +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import android.bluetooth.BluetoothProfile +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType.Companion.byValue +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite +import java.util.* +import java.util.concurrent.BlockingQueue +import java.util.concurrent.CountDownLatch +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException + +class BleCommCallbacks(aapsLogger: AAPSLogger, incomingPackets: Map>) : BluetoothGattCallback() { + + private val serviceDiscoveryComplete: CountDownLatch + private val connected: CountDownLatch + private val aapsLogger: AAPSLogger + private val incomingPackets: Map> + private val writeQueue: BlockingQueue + private val descriptorWriteQueue: BlockingQueue + override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { + super.onConnectionStateChange(gatt, status, newState) + aapsLogger.debug(LTag.PUMPBTCOMM, "OnConnectionStateChange discovered with status/state$status/$newState") + if (newState == BluetoothProfile.STATE_CONNECTED && status == BluetoothGatt.GATT_SUCCESS) { + connected.countDown() + } + } + + override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) { + super.onServicesDiscovered(gatt, status) + aapsLogger.debug(LTag.PUMPBTCOMM, "OnServicesDiscovered with status$status") + if (status == BluetoothGatt.GATT_SUCCESS) { + serviceDiscoveryComplete.countDown() + } + } + + @Throws(InterruptedException::class) fun waitForConnection(timeout_ms: Int) { + connected.await(timeout_ms.toLong(), TimeUnit.MILLISECONDS) + } + + @Throws(InterruptedException::class) fun waitForServiceDiscovery(timeout_ms: Int) { + serviceDiscoveryComplete.await(timeout_ms.toLong(), TimeUnit.MILLISECONDS) + } + + @Throws(InterruptedException::class, TimeoutException::class, CouldNotConfirmWrite::class) + fun confirmWrite(expectedPayload: ByteArray, timeout_ms: Int) { + val received = writeQueue.poll(timeout_ms.toLong(), TimeUnit.MILLISECONDS) + ?: throw TimeoutException() + if (!Arrays.equals(expectedPayload, received.payload)) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload + ". Status: " + received.status) + throw CouldNotConfirmWrite(expectedPayload, received.payload!!) + } + aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload) + } + + override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { + super.onCharacteristicWrite(gatt, characteristic, status) + var received: ByteArray? = null + if (status == BluetoothGatt.GATT_SUCCESS) { + received = characteristic.value + aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite value " + characteristic.getStringValue(0)) + } + aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite with status/char/value " + + status + "/" + + byValue(characteristic.uuid.toString()) + "/" + + received) + try { + if (writeQueue.size > 0) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Write confirm queue should be empty. found: " + writeQueue.size) + writeQueue.clear() + } + val offered = writeQueue.offer(CharacteristicWriteConfirmation(received, status), WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) + if (!offered) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed write confirmation") + } + } catch (e: InterruptedException) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while sending write confirmation") + } + } + + override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) { + super.onCharacteristicChanged(gatt, characteristic) + val payload = characteristic.value + val characteristicType = byValue(characteristic.uuid.toString()) + aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicChanged with char/value " + + characteristicType + "/" + + payload) + incomingPackets[characteristicType]!!.add(payload) + } + + @Throws(InterruptedException::class, CouldNotConfirmDescriptorWriteException::class) + fun confirmWriteDescriptor(descriptorUUID: String, timeout_ms: Int) { + val confirmed = descriptorWriteQueue.poll(timeout_ms.toLong(), TimeUnit.MILLISECONDS) + if (descriptorUUID != confirmed.uuid) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got " + confirmed.uuid + ".Expected: " + descriptorUUID + ". Status: " + confirmed.status) + throw CouldNotConfirmDescriptorWriteException(confirmed.uuid!!, descriptorUUID) + } + } + + override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { + super.onDescriptorWrite(gatt, descriptor, status) + var uuid: String? = null + if (status == BluetoothGatt.GATT_SUCCESS) { + uuid = descriptor.uuid.toString() + } + val confirmation = DescriptorWriteConfirmation(status, uuid) + try { + if (descriptorWriteQueue.size > 0) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Descriptor write queue should be empty, found: " + descriptorWriteQueue.size) + descriptorWriteQueue.clear() + } + val offered = descriptorWriteQueue.offer(confirmation, WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) + if (!offered) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed descriptor write confirmation") + } + } catch (e: InterruptedException) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Interrupted while sending descriptor write confirmation") + } + } + + companion object { + + private const val WRITE_CONFIRM_TIMEOUT_MS = 10 // the other thread should be waiting for the exchange + } + + init { + serviceDiscoveryComplete = CountDownLatch(1) + connected = CountDownLatch(1) + this.aapsLogger = aapsLogger + this.incomingPackets = incomingPackets + writeQueue = LinkedBlockingQueue(1) + descriptorWriteQueue = LinkedBlockingQueue(1) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java deleted file mode 100644 index cf2e8bff77..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks; - -public class CharacteristicWriteConfirmation { - public byte[] payload; - public int status; - - public CharacteristicWriteConfirmation(byte[] payload, int status) { - this.payload = payload; - this.status = status; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt new file mode 100644 index 0000000000..76a5db2f63 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks + +class CharacteristicWriteConfirmation(var payload: ByteArray?, var status: Int) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java deleted file mode 100644 index 88ae897b1b..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks; - -public class DescriptorWriteConfirmation { - public int status; - public String uuid; - - public DescriptorWriteConfirmation(int status, String uuid) { - this.status = status; - this.uuid = uuid; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt new file mode 100644 index 0000000000..c975393d7c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks + +class DescriptorWriteConfirmation(var status: Int, var uuid: String?) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java deleted file mode 100644 index 4af111d633..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command; - -import org.jetbrains.annotations.NotNull; - -public abstract class BleCommand { - private final byte[] data; - - public BleCommand(@NotNull BleCommandType type) { - this.data = new byte[]{type.getValue()}; - } - - public BleCommand(@NotNull BleCommandType type, @NotNull byte[] payload) { - int n = payload.length + 1; - this.data = new byte[n]; - this.data[0] = type.getValue(); - System.arraycopy(payload, 0, data, 1, payload.length); - } - - public byte[] asByteArray() { - return this.data; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt new file mode 100644 index 0000000000..d5483f3d37 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command + +abstract class BleCommand { + + private val data: ByteArray + + constructor(type: BleCommandType) { + data = byteArrayOf(type.value) + } + + constructor(type: BleCommandType, payload: ByteArray) { + val n = payload.size + 1 + data = ByteArray(n) + data[0] = type.value + System.arraycopy(payload, 0, data, 1, payload.size) + } + + fun asByteArray(): ByteArray { + return data + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java deleted file mode 100644 index 56659f45e5..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command; - -import java.nio.ByteBuffer; - -public class BleCommandHello extends BleCommand { - public BleCommandHello(int controllerId) { - super(BleCommandType.HELLO, - ByteBuffer.allocate(6) - .put((byte) 1) // TODO find the meaning of this constant - .put((byte) 4) // TODO find the meaning of this constant - .putInt(controllerId).array() - ); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt new file mode 100644 index 0000000000..03414989b2 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command + +import java.nio.ByteBuffer + +class BleCommandHello(controllerId: Int) : BleCommand(BleCommandType.HELLO, + ByteBuffer.allocate(6) + .put(1.toByte()) // TODO find the meaning of this constant + .put(4.toByte()) // TODO find the meaning of this constant + .putInt(controllerId).array() +) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java deleted file mode 100644 index 38225bf799..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.java +++ /dev/null @@ -1,30 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command; - -public enum BleCommandType { - RTS((byte) 0x00), - CTS((byte) 0x01), - NACK((byte) 0x02), - ABORT((byte) 0x03), - SUCCESS((byte) 0x04), - FAIL((byte) 0x05), - HELLO((byte) 0x06); - - public final byte value; - - BleCommandType(byte value) { - this.value = value; - } - - public static BleCommandType byValue(byte value) { - for (BleCommandType type : values()) { - if (type.value == value) { - return type; - } - } - throw new IllegalArgumentException("Unknown BleCommandType: " + value); - } - - public byte getValue() { - return this.value; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt new file mode 100644 index 0000000000..7dd91d00e1 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command + +enum class BleCommandType(val value: Byte) { + RTS(0x00.toByte()), CTS(0x01.toByte()), NACK(0x02.toByte()), ABORT(0x03.toByte()), SUCCESS(0x04.toByte()), FAIL(0x05.toByte()), HELLO(0x06.toByte()); + + companion object { + + fun byValue(value: Byte): BleCommandType { + for (type in values()) { + if (type.value == value) { + return type + } + } + throw IllegalArgumentException("Unknown BleCommandType: $value") + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java deleted file mode 100644 index 53f85c5a6f..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class BleIOBusyException extends Exception{ -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt new file mode 100644 index 0000000000..6029d66998 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class BleIOBusyException : Exception() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java deleted file mode 100644 index 1405d93f32..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class CharacteristicNotFoundException extends FailedToConnectException { - public CharacteristicNotFoundException(String cmdCharacteristicUuid) { - super("characteristic not found: " + cmdCharacteristicUuid); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt new file mode 100644 index 0000000000..730b6eeda0 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class CharacteristicNotFoundException(cmdCharacteristicUuid: String) : FailedToConnectException("characteristic not found: $cmdCharacteristicUuid") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java deleted file mode 100644 index b2034fd087..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.java +++ /dev/null @@ -1,12 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class CouldNotConfirmDescriptorWriteException extends Exception{ - private final String received; - private final String expected; - - public CouldNotConfirmDescriptorWriteException(String received, String expected) { - super(); - this.received = received; - this.expected = expected; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt new file mode 100644 index 0000000000..0b49f74970 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class CouldNotConfirmDescriptorWriteException(private val received: String, private val expected: String) : Exception() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java deleted file mode 100644 index f422746180..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class CouldNotConfirmWrite extends Exception { - - private final byte[] sent; - private final Object confirmed; - - public CouldNotConfirmWrite(byte[] sent, byte[] confirmed) { - super(); - this.sent = sent; - this.confirmed = confirmed; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt new file mode 100644 index 0000000000..cb815ce34c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class CouldNotConfirmWrite(private val sent: ByteArray, confirmed: ByteArray) : Exception() { + + private val confirmed: Any + + init { + this.confirmed = confirmed + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java deleted file mode 100644 index 261490dee5..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.java +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType; - -public class CouldNotEnableNotifications extends Exception { - public CouldNotEnableNotifications(CharacteristicType cmd) { - super(cmd.getValue()); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt new file mode 100644 index 0000000000..7564ab32e1 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType + +class CouldNotEnableNotifications(cmd: CharacteristicType) : Exception(cmd.value) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java deleted file mode 100644 index 6bd30f5ff8..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class CouldNotSendBleException extends Exception { - public CouldNotSendBleException(String msg) { - super(msg); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt new file mode 100644 index 0000000000..63abcb9a68 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class CouldNotSendBleException(msg: String?) : Exception(msg) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java deleted file mode 100644 index d7dc3473eb..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class DescriptorNotFoundException extends Exception { -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt new file mode 100644 index 0000000000..202fcaf3b1 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class DescriptorNotFoundException : Exception() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java deleted file mode 100644 index 9de20faf07..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -import android.os.ParcelUuid; - -import java.util.List; - -public class DiscoveredInvalidPodException extends Exception { - public DiscoveredInvalidPodException(String message, List serviceUUIds) { - super(message + " service UUIDs: " + serviceUUIds); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt new file mode 100644 index 0000000000..9b8ff7488d --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +import android.os.ParcelUuid + +class DiscoveredInvalidPodException(message: String, serviceUUIds: List) : Exception("$message service UUIDs: $serviceUUIds") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java deleted file mode 100644 index dd4cf724ed..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class FailedToConnectException extends Exception { - public FailedToConnectException() { - super(); - } - - public FailedToConnectException(String message) { - super(message); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt new file mode 100644 index 0000000000..c720724ceb --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +open class FailedToConnectException : Exception { + constructor() : super() {} + constructor(message: String?) : super(message) {} +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java deleted file mode 100644 index f99fbe32d4..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.java +++ /dev/null @@ -1,10 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class ScanFailException extends Exception { - public ScanFailException() { - } - - public ScanFailException(int errorCode) { - super("errorCode" + errorCode); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt new file mode 100644 index 0000000000..6c6dcc2f49 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +open class ScanFailException : Exception { + constructor() {} + constructor(errorCode: Int) : super("errorCode$errorCode") {} +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java deleted file mode 100644 index 7fc00ae2df..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.java +++ /dev/null @@ -1,20 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.BleDiscoveredDevice; - -public class ScanFailFoundTooManyException extends ScanFailException { - private final List devices; - - public ScanFailFoundTooManyException(List devices) { - super(); - this.devices = new ArrayList<>(devices); - } - - public List getDiscoveredDevices() { - return Collections.unmodifiableList(this.devices); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt new file mode 100644 index 0000000000..d83b6643e8 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.BleDiscoveredDevice +import java.util.* + +class ScanFailFoundTooManyException(devices: List?) : ScanFailException() { + + private val devices: List + val discoveredDevices: List + get() = Collections.unmodifiableList(devices) + + init { + this.devices = ArrayList(devices) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java deleted file mode 100644 index 9bf2284db3..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class ScanFailNotFoundException extends ScanFailException { -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt new file mode 100644 index 0000000000..9466ea9b52 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class ScanFailNotFoundException : ScanFailException() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java deleted file mode 100644 index 51bfa5b8ef..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions; - -public class ServiceNotFoundException extends FailedToConnectException { - public ServiceNotFoundException(String serviceUuid) { - super("service not found: " + serviceUuid); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt new file mode 100644 index 0000000000..dc792f5825 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class ServiceNotFoundException(serviceUuid: String) : FailedToConnectException("service not found: $serviceUuid") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java deleted file mode 100644 index 75490b33e3..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.java +++ /dev/null @@ -1,140 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io; - -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattDescriptor; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.BleIOBusyException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotEnableNotifications; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DescriptorNotFoundException; - - -public class BleIO { - private static final int DEFAULT_IO_TIMEOUT_MS = 1000; - - private final AAPSLogger aapsLogger; - private final Map chars; - private final Map> incomingPackets; - private final BluetoothGatt gatt; - private final BleCommCallbacks bleCommCallbacks; - - private IOState state; - - public BleIO(AAPSLogger aapsLogger, Map chars, Map> incomingPackets, BluetoothGatt gatt, BleCommCallbacks bleCommCallbacks) { - this.aapsLogger = aapsLogger; - this.chars = chars; - this.incomingPackets = incomingPackets; - this.gatt = gatt; - this.bleCommCallbacks = bleCommCallbacks; - this.state = IOState.IDLE; - } - - /*** - * - * @param characteristic where to read from(CMD or DATA) - * @return a byte array with the received data - */ - public byte[] receivePacket(CharacteristicType characteristic) throws - BleIOBusyException, - InterruptedException, - TimeoutException { - synchronized (this.state) { - if (this.state != IOState.IDLE) { - throw new BleIOBusyException(); - } - this.state = IOState.READING; - } - byte[] ret = this.incomingPackets.get(characteristic).poll(DEFAULT_IO_TIMEOUT_MS, TimeUnit.MILLISECONDS); - if (ret == null) { - throw new TimeoutException(); - } - synchronized (this.state) { - this.state = IOState.IDLE; - } - return ret; - } - - /*** - * - * @param characteristic where to write to(CMD or DATA) - * @param payload the data to send - * @throws CouldNotSendBleException - */ - public void sendAndConfirmPacket(CharacteristicType characteristic, byte[] payload) - throws CouldNotSendBleException, - BleIOBusyException, - InterruptedException, - CouldNotConfirmWrite, - TimeoutException { - synchronized (this.state) { - if (this.state != IOState.IDLE) { - throw new BleIOBusyException(); - } - this.state = IOState.WRITING; - } - - aapsLogger.debug(LTag.PUMPBTCOMM, "BleIO: Sending data on" + characteristic.name() + "/" + payload.toString()); - BluetoothGattCharacteristic ch = chars.get(characteristic); - boolean set = ch.setValue(payload); - if (!set) { - throw new CouldNotSendBleException("setValue"); - } - boolean sent = this.gatt.writeCharacteristic(ch); - if (!sent) { - throw new CouldNotSendBleException("writeCharacteristic"); - } - this.bleCommCallbacks.confirmWrite(CharacteristicType.CMD, payload, DEFAULT_IO_TIMEOUT_MS); - synchronized (this.state) { - this.state = IOState.IDLE; - } - } - - /** - * Called before sending a new message. - * The incoming queues should be empty, so we log when they are not. - */ - public void flushIncomingQueues() { - - } - - /** - * Enable intentions on the characteristics. - * This will signal the pod it can start sending back data - * @return - */ - public void readyToRead() - throws CouldNotSendBleException, - CouldNotEnableNotifications, - DescriptorNotFoundException, - InterruptedException, CouldNotConfirmDescriptorWriteException { - - for (CharacteristicType type : CharacteristicType.values()) { - BluetoothGattCharacteristic ch = this.chars.get(type); - boolean notificationSet = this.gatt.setCharacteristicNotification(ch, true); - if (!notificationSet) { - throw new CouldNotEnableNotifications(type); - } - List descriptors = ch.getDescriptors(); - if (descriptors.size() != 1) { - throw new DescriptorNotFoundException(); - } - BluetoothGattDescriptor descriptor = descriptors.get(0); - descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE); - gatt.writeDescriptor(descriptor); - bleCommCallbacks.confirmWriteDescriptor(descriptor.getUuid().toString(), DEFAULT_IO_TIMEOUT_MS); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt new file mode 100644 index 0000000000..7dfe2a44b4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -0,0 +1,104 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io + +import android.bluetooth.BluetoothGatt +import android.bluetooth.BluetoothGattCharacteristic +import android.bluetooth.BluetoothGattDescriptor +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* +import java.util.concurrent.BlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.TimeoutException + +class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map, private val incomingPackets: Map>, private val gatt: BluetoothGatt, private val bleCommCallbacks: BleCommCallbacks) { + + private var state: IOState + + /*** + * + * @param characteristic where to read from(CMD or DATA) + * @return a byte array with the received data + */ + @Throws(BleIOBusyException::class, InterruptedException::class, TimeoutException::class) + fun receivePacket(characteristic: CharacteristicType): ByteArray { + synchronized(state) { + if (state != IOState.IDLE) { + throw BleIOBusyException() + } + state = IOState.READING + } + val ret = incomingPackets[characteristic]!!.poll(DEFAULT_IO_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) + ?: throw TimeoutException() + synchronized(state) { state = IOState.IDLE } + return ret + } + + /*** + * + * @param characteristic where to write to(CMD or DATA) + * @param payload the data to send + * @throws CouldNotSendBleException + */ + @Throws(CouldNotSendBleException::class, BleIOBusyException::class, InterruptedException::class, CouldNotConfirmWrite::class, TimeoutException::class) + fun sendAndConfirmPacket(characteristic: CharacteristicType, payload: ByteArray) { + synchronized(state) { + if (state != IOState.IDLE) { + throw BleIOBusyException() + } + state = IOState.WRITING + } + aapsLogger.debug(LTag.PUMPBTCOMM, "BleIO: Sending data on" + characteristic.name + "/" + payload.toString()) + val ch = chars[characteristic] + val set = ch!!.setValue(payload) + if (!set) { + throw CouldNotSendBleException("setValue") + } + val sent = gatt.writeCharacteristic(ch) + if (!sent) { + throw CouldNotSendBleException("writeCharacteristic") + } + bleCommCallbacks.confirmWrite(payload, DEFAULT_IO_TIMEOUT_MS) + synchronized(state) { state = IOState.IDLE } + } + + /** + * Called before sending a new message. + * The incoming queues should be empty, so we log when they are not. + */ + fun flushIncomingQueues() {} + + /** + * Enable intentions on the characteristics. + * This will signal the pod it can start sending back data + * @return + */ + @Throws(CouldNotSendBleException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, InterruptedException::class, CouldNotConfirmDescriptorWriteException::class) + fun readyToRead() { + for (type in CharacteristicType.values()) { + val ch = chars[type] + val notificationSet = gatt.setCharacteristicNotification(ch, true) + if (!notificationSet) { + throw CouldNotEnableNotifications(type) + } + val descriptors = ch!!.descriptors + if (descriptors.size != 1) { + throw DescriptorNotFoundException() + } + val descriptor = descriptors[0] + descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE + gatt.writeDescriptor(descriptor) + bleCommCallbacks.confirmWriteDescriptor(descriptor.uuid.toString(), DEFAULT_IO_TIMEOUT_MS) + } + } + + companion object { + + private const val DEFAULT_IO_TIMEOUT_MS = 1000 + } + + init { + state = IOState.IDLE + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java deleted file mode 100644 index cd9ae12297..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io; - -public enum IOState { - IDLE, - WRITING, - READING; -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.kt new file mode 100644 index 0000000000..4ef49f6586 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/IOState.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io + +enum class IOState { + IDLE, WRITING, READING +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt similarity index 59% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index 54babad049..6e8e7de891 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -1,4 +1,3 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet -public class BlePacket { -} +class BlePacket \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java deleted file mode 100644 index d4c0a19ef8..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.java +++ /dev/null @@ -1,94 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan; - -import android.bluetooth.le.ScanRecord; -import android.bluetooth.le.ScanResult; -import android.os.ParcelUuid; - -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException; - -public class BleDiscoveredDevice { - private final ScanResult scanResult; - private final long podID; - private final int sequenceNo; - private final long lotNo; - - public BleDiscoveredDevice(ScanResult scanResult, long searchPodID) - throws DiscoveredInvalidPodException { - - this.scanResult = scanResult; - this.podID = searchPodID; - - this.validateServiceUUIDs(); - this.validatePodID(); - this.lotNo = this.parseLotNo(); - this.sequenceNo = this.parseSeqNo(); - } - - private static String extractUUID16(ParcelUuid uuid) { - return uuid.toString().substring(4, 8); - } - - private void validateServiceUUIDs() - throws DiscoveredInvalidPodException { - ScanRecord scanRecord = scanResult.getScanRecord(); - List serviceUUIDs = scanRecord.getServiceUuids(); - - if (serviceUUIDs.size() != 9) { - throw new DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUUIDs.size(), serviceUUIDs); - } - if (!extractUUID16(serviceUUIDs.get(0)).equals("4024")) { - // this is the service that we filtered for - throw new DiscoveredInvalidPodException("The first exposed service UUID should be 4024, got " + extractUUID16(serviceUUIDs.get(0)), serviceUUIDs); - } - // TODO understand what is serviceUUIDs[1]. 0x2470. Alarms? - if (!extractUUID16(serviceUUIDs.get(2)).equals("000a")) { - // constant? - throw new DiscoveredInvalidPodException("The third exposed service UUID should be 000a, got " + serviceUUIDs.get(2), serviceUUIDs); - } - } - - private void validatePodID() - throws DiscoveredInvalidPodException { - ScanRecord scanRecord = scanResult.getScanRecord(); - List serviceUUIDs = scanRecord.getServiceUuids(); - String hexPodID = extractUUID16(serviceUUIDs.get(3)) + extractUUID16(serviceUUIDs.get(4)); - Long podID = Long.parseLong(hexPodID, 16); - if (this.podID != podID) { - throw new DiscoveredInvalidPodException("This is not the POD we are looking for. " + this.podID + " found: " + podID, serviceUUIDs); - } - } - - private long parseLotNo() { - ScanRecord scanRecord = scanResult.getScanRecord(); - List serviceUUIDs = scanRecord.getServiceUuids(); - String lotSeq = extractUUID16(serviceUUIDs.get(5)) + - extractUUID16(serviceUUIDs.get(6)) + - extractUUID16(serviceUUIDs.get(7)); - - return Long.parseLong(lotSeq.substring(0, 10), 16); - } - - private int parseSeqNo() { - ScanRecord scanRecord = scanResult.getScanRecord(); - List serviceUUIDs = scanRecord.getServiceUuids(); - String lotSeq = extractUUID16(serviceUUIDs.get(7)) + - extractUUID16(serviceUUIDs.get(8)); - - return Integer.parseInt(lotSeq.substring(2), 16); - } - - public ScanResult getScanResult() { - return this.scanResult; - } - - @Override public String toString() { - return "BleDiscoveredDevice{" + - "scanResult=" + scanResult + - ", podID=" + podID + - ", sequenceNo=" + sequenceNo + - ", lotNo=" + lotNo + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt new file mode 100644 index 0000000000..dba4b8d8b5 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -0,0 +1,78 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan + +import android.bluetooth.le.ScanResult +import android.os.ParcelUuid +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException + +class BleDiscoveredDevice(val scanResult: ScanResult, private val podID: Long) { + + private val sequenceNo: Int + private val lotNo: Long + @Throws(DiscoveredInvalidPodException::class) private fun validateServiceUUIDs() { + val scanRecord = scanResult.scanRecord + ?: throw DiscoveredInvalidPodException("Scan record is null") + val serviceUUIDs = scanRecord.serviceUuids + if (serviceUUIDs.size != 9) { + throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUUIDs.size, serviceUUIDs) + } + if (extractUUID16(serviceUUIDs[0]) != "4024") { + // this is the service that we filtered for + throw DiscoveredInvalidPodException("The first exposed service UUID should be 4024, got " + extractUUID16(serviceUUIDs[0]), serviceUUIDs) + } + // TODO understand what is serviceUUIDs[1]. 0x2470. Alarms? + if (extractUUID16(serviceUUIDs[2]) != "000a") { + // constant? + throw DiscoveredInvalidPodException("The third exposed service UUID should be 000a, got " + serviceUUIDs[2], serviceUUIDs) + } + } + + @Throws(DiscoveredInvalidPodException::class) private fun validatePodID() { + val scanRecord = scanResult.scanRecord + val serviceUUIDs = scanRecord.serviceUuids + val hexPodID = extractUUID16(serviceUUIDs[3]) + extractUUID16(serviceUUIDs[4]) + val podID = hexPodID.toLong(16) + if (this.podID != podID) { + throw DiscoveredInvalidPodException("This is not the POD we are looking for. " + this.podID + " found: " + podID, serviceUUIDs) + } + } + + private fun parseLotNo(): Long { + val scanRecord = scanResult.scanRecord + val serviceUUIDs = scanRecord.serviceUuids + val lotSeq = extractUUID16(serviceUUIDs[5]) + + extractUUID16(serviceUUIDs[6]) + + extractUUID16(serviceUUIDs[7]) + return lotSeq.substring(0, 10).toLong(16) + } + + private fun parseSeqNo(): Int { + val scanRecord = scanResult.scanRecord + val serviceUUIDs = scanRecord.serviceUuids + val lotSeq = extractUUID16(serviceUUIDs[7]) + + extractUUID16(serviceUUIDs[8]) + return lotSeq.substring(2).toInt(16) + } + + override fun toString(): String { + return "BleDiscoveredDevice{" + + "scanResult=" + scanResult + + ", podID=" + podID + + ", sequenceNo=" + sequenceNo + + ", lotNo=" + lotNo + + '}' + } + + companion object { + + private fun extractUUID16(uuid: ParcelUuid): String { + return uuid.toString().substring(4, 8) + } + } + + init { + validateServiceUUIDs() + validatePodID() + lotNo = parseLotNo() + sequenceNo = parseSeqNo() + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java deleted file mode 100644 index c3953f75d1..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.java +++ /dev/null @@ -1,62 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.le.BluetoothLeScanner; -import android.bluetooth.le.ScanFilter; -import android.bluetooth.le.ScanSettings; -import android.os.ParcelUuid; - -import java.util.Arrays; -import java.util.List; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailFoundTooManyException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailNotFoundException; - -public class PodScanner { - public static final String SCAN_FOR_SERVICE_UUID = "00004024-0000-1000-8000-00805F9B34FB"; - public static final long POD_ID_NOT_ACTIVATED = 4294967294L; - private static final int SCAN_DURATION_MS = 5000; - - private final BluetoothAdapter bluetoothAdapter; - private final AAPSLogger logger; - - public PodScanner(AAPSLogger logger, BluetoothAdapter bluetoothAdapter) { - this.bluetoothAdapter = bluetoothAdapter; - this.logger = logger; - } - - public BleDiscoveredDevice scanForPod(String serviceUUID, long podID) - throws InterruptedException, ScanFailException { - BluetoothLeScanner scanner = this.bluetoothAdapter.getBluetoothLeScanner(); - - ScanFilter filter = new ScanFilter.Builder() - .setServiceUuid(ParcelUuid.fromString(serviceUUID)) - .build(); - - ScanSettings scanSettings = new ScanSettings.Builder() - .setLegacy(false) - .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) - .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) - .build(); - - ScanCollector scanCollector = new ScanCollector(this.logger, podID); - this.logger.debug(LTag.PUMPBTCOMM, "Scanning with filters: "+ filter.toString() + " settings" + scanSettings.toString()); - scanner.startScan(Arrays.asList(filter), scanSettings, scanCollector); - - Thread.sleep(SCAN_DURATION_MS); - - scanner.flushPendingScanResults(scanCollector); - scanner.stopScan(scanCollector); - - List collected = scanCollector.collect(); - if (collected.size() == 0) { - throw new ScanFailNotFoundException(); - } else if (collected.size() > 1) { - throw new ScanFailFoundTooManyException(collected); - } - return collected.get(0); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt new file mode 100644 index 0000000000..829faaa405 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt @@ -0,0 +1,48 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan + +import android.bluetooth.BluetoothAdapter +import android.bluetooth.le.ScanFilter +import android.bluetooth.le.ScanSettings +import android.os.ParcelUuid +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailFoundTooManyException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailNotFoundException +import java.util.* + +class PodScanner(private val logger: AAPSLogger, private val bluetoothAdapter: BluetoothAdapter) { + + @Throws(InterruptedException::class, ScanFailException::class) + fun scanForPod(serviceUUID: String?, podID: Long): BleDiscoveredDevice { + val scanner = bluetoothAdapter.bluetoothLeScanner + val filter = ScanFilter.Builder() + .setServiceUuid(ParcelUuid.fromString(serviceUUID)) + .build() + val scanSettings = ScanSettings.Builder() + .setLegacy(false) + .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) + .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) + .build() + val scanCollector = ScanCollector(logger, podID) + logger.debug(LTag.PUMPBTCOMM, "Scanning with filters: $filter settings$scanSettings") + scanner.startScan(Arrays.asList(filter), scanSettings, scanCollector) + Thread.sleep(SCAN_DURATION_MS.toLong()) + scanner.flushPendingScanResults(scanCollector) + scanner.stopScan(scanCollector) + val collected = scanCollector.collect() + if (collected.size == 0) { + throw ScanFailNotFoundException() + } else if (collected.size > 1) { + throw ScanFailFoundTooManyException(collected) + } + return collected[0] + } + + companion object { + + const val SCAN_FOR_SERVICE_UUID = "00004024-0000-1000-8000-00805F9B34FB" + const val POD_ID_NOT_ACTIVATED = 4294967294L + private const val SCAN_DURATION_MS = 5000 + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java deleted file mode 100644 index 9121b0f5a4..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.java +++ /dev/null @@ -1,66 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan; - -import android.bluetooth.le.ScanCallback; -import android.bluetooth.le.ScanResult; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException; - -public class ScanCollector extends ScanCallback { - private final AAPSLogger logger; - private final long podID; - // there could be different threads calling the onScanResult callback - private final ConcurrentHashMap found; - private int scanFailed; - - public ScanCollector(AAPSLogger logger, long podID) { - this.podID = podID; - this.logger = logger; - this.found = new ConcurrentHashMap(); - } - - @Override - public void onScanResult(int callbackType, ScanResult result) { - // callbackType will be ALL - this.logger.debug(LTag.PUMPBTCOMM, "Scan found: "+result.toString()); - this.found.put(result.getDevice().getAddress(), result); - } - - @Override - public void onScanFailed(int errorCode) { - this.scanFailed = errorCode; - this.logger.warn(LTag.PUMPBTCOMM, "Scan failed with errorCode: "+errorCode); - super.onScanFailed(errorCode); - } - - public List collect() - throws ScanFailException { - List ret = new ArrayList<>(); - - if (this.scanFailed != 0) { - throw new ScanFailException(this.scanFailed); - } - - logger.debug(LTag.PUMPBTCOMM, "ScanCollector looking for podID: " + this.podID); - - for (ScanResult result : this.found.values()) { - try { - BleDiscoveredDevice device = new BleDiscoveredDevice(result, this.podID); - ret.add(device); - logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + this.podID); - } catch (DiscoveredInvalidPodException e) { - logger.debug(LTag.PUMPBTCOMM, "ScanCollector: pod not matching" + e.toString()); - // this is not the POD we are looking for - } - } - return Collections.unmodifiableList(ret); - } -} - diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt new file mode 100644 index 0000000000..d37f714854 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt @@ -0,0 +1,51 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan + +import android.bluetooth.le.ScanCallback +import android.bluetooth.le.ScanResult +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException +import java.util.* +import java.util.concurrent.ConcurrentHashMap + +class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : ScanCallback() { + + // there could be different threads calling the onScanResult callback + private val found: ConcurrentHashMap + private var scanFailed = 0 + override fun onScanResult(callbackType: Int, result: ScanResult) { + // callbackType will be ALL + logger.debug(LTag.PUMPBTCOMM, "Scan found: $result") + found[result.device.address] = result + } + + override fun onScanFailed(errorCode: Int) { + scanFailed = errorCode + logger.warn(LTag.PUMPBTCOMM, "Scan failed with errorCode: $errorCode") + super.onScanFailed(errorCode) + } + + @Throws(ScanFailException::class) fun collect(): List { + val ret: MutableList = ArrayList() + if (scanFailed != 0) { + throw ScanFailException(scanFailed) + } + logger.debug(LTag.PUMPBTCOMM, "ScanCollector looking for podID: " + podID) + for (result in found.values) { + try { + val device = BleDiscoveredDevice(result, podID) + ret.add(device) + logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + podID) + } catch (e: DiscoveredInvalidPodException) { + logger.debug(LTag.PUMPBTCOMM, "ScanCollector: pod not matching$e") + // this is not the POD we are looking for + } + } + return Collections.unmodifiableList(ret) + } + + init { + found = ConcurrentHashMap() + } +} \ No newline at end of file From 2a14d60beed923a71f435efea9624a7f2f867232 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Wed, 24 Feb 2021 20:12:29 +0100 Subject: [PATCH 008/649] kotlin a bit more idiomatic after conversion from Java --- .../omnipod/dash/driver/comm/BleManager.kt | 65 ++++++------------- .../dash/driver/comm/CharacteristicType.kt | 12 ++-- .../dash/driver/comm/ServiceDiscoverer.kt | 19 +++--- .../driver/comm/callbacks/BleCommCallbacks.kt | 58 ++++++++--------- .../CharacteristicWriteConfirmation.kt | 6 +- .../driver/comm/command/BleCommandType.kt | 11 +--- .../comm/exceptions/CouldNotConfirmWrite.kt | 9 +-- .../ScanFailFoundTooManyException.kt | 8 +-- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 8 +-- .../dash/driver/comm/scan/PodScanner.kt | 2 +- .../dash/driver/comm/scan/ScanCollector.kt | 7 +- 11 files changed, 78 insertions(+), 127 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt index 630d57c1b9..a227adab18 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt @@ -1,68 +1,49 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm - -import javax.inject.Singleton -import javax.inject.Inject -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashCommunicationManager import android.bluetooth.BluetoothAdapter -import android.bluetooth.BluetoothManager -import info.nightscout.androidaps.logging.AAPSLogger -import android.bluetooth.BluetoothGatt -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO -import kotlin.Throws -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.FailedToConnectException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotSendBleException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.BleIOBusyException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotEnableNotifications -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DescriptorNotFoundException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner import android.bluetooth.BluetoothDevice -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager +import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ServiceDiscoverer -import android.bluetooth.BluetoothGattCharacteristic import android.content.Context +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner import java.util.* import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException +import javax.inject.Inject +import javax.inject.Singleton @Singleton -class BleManager @Inject constructor(private val context: Context) : OmnipodDashCommunicationManager { +class BleManager @Inject constructor(private val context: Context, private val aapsLogger: AAPSLogger) : OmnipodDashCommunicationManager { - private val bluetoothAdapter: BluetoothAdapter - private val bluetoothManager: BluetoothManager + private val bluetoothManager: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager + private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter - @Inject lateinit var aapsLogger: AAPSLogger - private var podAddress: String? = null - private var gatt: BluetoothGatt? = null - private var bleio: BleIO? = null @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWrite::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) fun activateNewPod() { aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") val podScanner = PodScanner(aapsLogger, bluetoothAdapter) - podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address + val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - connect() + connect(podAddress) } @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWrite::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - fun connect() { + private fun connect(podAddress: String) { // TODO: locking? val podDevice = bluetoothAdapter.getRemoteDevice(podAddress) - var incomingPackets: Map> = + val incomingPackets: Map> = mapOf(CharacteristicType.CMD to LinkedBlockingDeque(), CharacteristicType.DATA to LinkedBlockingDeque()); val bleCommCallbacks = BleCommCallbacks(aapsLogger, incomingPackets) - aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to " + podAddress) + aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to $podAddress") var autoConnect = true if (BuildConfig.DEBUG) { autoConnect = false @@ -70,8 +51,6 @@ class BleManager @Inject constructor(private val context: Context) : OmnipodDash // it's easier to start testing from scratch on each run. } val gatt = podDevice.connectGatt(context, autoConnect, bleCommCallbacks, BluetoothDevice.TRANSPORT_LE) - this.gatt = gatt - bleCommCallbacks.waitForConnection(CONNECT_TIMEOUT_MS) val connectionState = bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT) aapsLogger.debug(LTag.PUMPBTCOMM, "GATT connection state: $connectionState") @@ -80,10 +59,10 @@ class BleManager @Inject constructor(private val context: Context) : OmnipodDash } val discoverer = ServiceDiscoverer(aapsLogger, gatt, bleCommCallbacks) val chars = discoverer.discoverServices() - bleio = BleIO(aapsLogger, chars, incomingPackets, gatt, bleCommCallbacks) + val bleIO = BleIO(aapsLogger, chars, incomingPackets, gatt, bleCommCallbacks) aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod") - bleio!!.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandHello(CONTROLLER_ID).asByteArray()) - bleio!!.readyToRead() + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandHello(CONTROLLER_ID).asByteArray()) + bleIO.readyToRead() } companion object { @@ -92,8 +71,4 @@ class BleManager @Inject constructor(private val context: Context) : OmnipodDash private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } - init { - bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager - bluetoothAdapter = bluetoothManager.adapter - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt index 600e4ba769..a68ccba448 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt @@ -14,13 +14,9 @@ enum class CharacteristicType(val value: String) { companion object { - @JvmStatic fun byValue(value: String): CharacteristicType { - for (type in values()) { - if (type.value == value) { - return type - } - } - throw IllegalArgumentException("Unknown Characteristic Type: $value") - } + @JvmStatic + fun byValue(value: String): CharacteristicType = + values().firstOrNull { it.value == value } + ?: throw IllegalArgumentException("Unknown Characteristic Type: $value") } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt index 85694a213a..ccf7298a6e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt @@ -22,26 +22,25 @@ class ServiceDiscoverer(private val logger: AAPSLogger, private val gatt: Blueto gatt.discoverServices() bleCallbacks.waitForServiceDiscovery(DISCOVER_SERVICES_TIMEOUT_MS) logger.debug(LTag.PUMPBTCOMM, "Services discovered") - val service = gatt.getService( - uuidFromString(SERVICE_UUID)) + val service = gatt.getService(SERVICE_UUID.toUuid()) ?: throw ServiceNotFoundException(SERVICE_UUID) val cmdChar = service.getCharacteristic(CharacteristicType.CMD.uUID) ?: throw CharacteristicNotFoundException(CharacteristicType.CMD.value) - val dataChar = service.getCharacteristic(CharacteristicType.DATA.uUID) + val dataChar = service.getCharacteristic(CharacteristicType.DATA.uUID) // TODO: this is never used ?: throw CharacteristicNotFoundException(CharacteristicType.DATA.value) var chars = mapOf(CharacteristicType.CMD to cmdChar, CharacteristicType.DATA to dataChar) return chars } + + private fun String.toUuid(): UUID = UUID( + BigInteger(replace("-", "").substring(0, 16), 16).toLong(), + BigInteger(replace("-", "").substring(16), 16).toLong() + ) + companion object { private const val SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f" private const val DISCOVER_SERVICES_TIMEOUT_MS = 5000 - private fun uuidFromString(s: String): UUID { - return UUID( - BigInteger(s.replace("-", "").substring(0, 16), 16).toLong(), - BigInteger(s.replace("-", "").substring(16), 16).toLong() - ) - } } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index 1998d9b307..e6d9dd545e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -11,21 +11,19 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Characte import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType.Companion.byValue import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite -import java.util.* import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException -class BleCommCallbacks(aapsLogger: AAPSLogger, incomingPackets: Map>) : BluetoothGattCallback() { +class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingPackets: Map>) : BluetoothGattCallback() { + + private val serviceDiscoveryComplete: CountDownLatch = CountDownLatch(1) + private val connected: CountDownLatch = CountDownLatch(1) + private val writeQueue: BlockingQueue = LinkedBlockingQueue(1) + private val descriptorWriteQueue: BlockingQueue = LinkedBlockingQueue(1) - private val serviceDiscoveryComplete: CountDownLatch - private val connected: CountDownLatch - private val aapsLogger: AAPSLogger - private val incomingPackets: Map> - private val writeQueue: BlockingQueue - private val descriptorWriteQueue: BlockingQueue override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) { super.onConnectionStateChange(gatt, status, newState) aapsLogger.debug(LTag.PUMPBTCOMM, "OnConnectionStateChange discovered with status/state$status/$newState") @@ -42,42 +40,53 @@ class BleCommCallbacks(aapsLogger: AAPSLogger, incomingPackets: Map confirmWritePayload(expectedPayload, received) + is CharacteristicWriteConfirmationError -> + aapsLogger.debug(LTag.PUMPBTCOMM, "Could not confirm write: status was ${received.status}") + } + + } + + private fun confirmWritePayload(expectedPayload: ByteArray, received: CharacteristicWriteConfirmationPayload) { + if (!expectedPayload.contentEquals(received.payload)) { aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload + ". Status: " + received.status) - throw CouldNotConfirmWrite(expectedPayload, received.payload!!) + throw CouldNotConfirmWrite(expectedPayload, received.payload) } aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload) } override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { super.onCharacteristicWrite(gatt, characteristic, status) - var received: ByteArray? = null - if (status == BluetoothGatt.GATT_SUCCESS) { - received = characteristic.value + val writeConfirmation = if (status == BluetoothGatt.GATT_SUCCESS) { aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite value " + characteristic.getStringValue(0)) + CharacteristicWriteConfirmationPayload(characteristic.value, status) + } else { + CharacteristicWriteConfirmationError(status) } aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite with status/char/value " + - status + "/" + - byValue(characteristic.uuid.toString()) + "/" + - received) + status + "/" + byValue(characteristic.uuid.toString()) + "/" + characteristic.value) try { if (writeQueue.size > 0) { aapsLogger.warn(LTag.PUMPBTCOMM, "Write confirm queue should be empty. found: " + writeQueue.size) writeQueue.clear() } - val offered = writeQueue.offer(CharacteristicWriteConfirmation(received, status), WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) + val offered = writeQueue.offer(writeConfirmation, WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) if (!offered) { aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed write confirmation") } @@ -130,13 +139,4 @@ class BleCommCallbacks(aapsLogger: AAPSLogger, incomingPackets: Map?) : ScanFailException() { +class ScanFailFoundTooManyException(devices: List) : ScanFailException() { - private val devices: List + private val devices: List = ArrayList(devices) val discoveredDevices: List get() = Collections.unmodifiableList(devices) - - init { - this.devices = ArrayList(devices) - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index 7dfe2a44b4..397520820c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -14,7 +14,7 @@ import java.util.concurrent.TimeoutException class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map, private val incomingPackets: Map>, private val gatt: BluetoothGatt, private val bleCommCallbacks: BleCommCallbacks) { - private var state: IOState + private var state: IOState = IOState.IDLE /*** * @@ -29,7 +29,7 @@ class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map 1) { throw ScanFailFoundTooManyException(collected) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt index d37f714854..1164815970 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt @@ -12,7 +12,7 @@ import java.util.concurrent.ConcurrentHashMap class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : ScanCallback() { // there could be different threads calling the onScanResult callback - private val found: ConcurrentHashMap + private val found: ConcurrentHashMap = ConcurrentHashMap() private var scanFailed = 0 override fun onScanResult(callbackType: Int, result: ScanResult) { // callbackType will be ALL @@ -31,7 +31,7 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S if (scanFailed != 0) { throw ScanFailException(scanFailed) } - logger.debug(LTag.PUMPBTCOMM, "ScanCollector looking for podID: " + podID) + logger.debug(LTag.PUMPBTCOMM, "ScanCollector looking for podID: $podID") for (result in found.values) { try { val device = BleDiscoveredDevice(result, podID) @@ -45,7 +45,4 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S return Collections.unmodifiableList(ret) } - init { - found = ConcurrentHashMap() - } } \ No newline at end of file From f2fed8adc4c3c77fda7ab450373864df1a67bb9d Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Thu, 25 Feb 2021 09:31:50 +0100 Subject: [PATCH 009/649] Implement more suggestions after the switch to Kotlin --- .../omnipod/dash/driver/comm/BleManager.kt | 7 ++- .../driver/comm/callbacks/BleCommCallbacks.kt | 43 ++++++++++--------- .../CharacteristicWriteConfirmation.kt | 4 +- .../callbacks/DescriptorWriteConfirmation.kt | 6 ++- .../dash/driver/comm/command/BleCommand.kt | 6 +-- ...CouldNotConfirmDescriptorWriteException.kt | 5 ++- .../comm/exceptions/CouldNotConfirmWrite.kt | 3 -- .../CouldNotConfirmWriteException.kt | 6 +++ .../DiscoveredInvalidPodException.kt | 5 ++- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 2 +- .../driver/comm/scan/BleDiscoveredDevice.kt | 8 ++-- 11 files changed, 54 insertions(+), 41 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt index a227adab18..16d6153b58 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt @@ -13,7 +13,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner -import java.util.* import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException @@ -26,7 +25,7 @@ class BleManager @Inject constructor(private val context: Context, private val a private val bluetoothManager: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter - @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWrite::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) + @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) fun activateNewPod() { aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") val podScanner = PodScanner(aapsLogger, bluetoothAdapter) @@ -35,7 +34,7 @@ class BleManager @Inject constructor(private val context: Context, private val a connect(podAddress) } - @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWrite::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) + @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) private fun connect(podAddress: String) { // TODO: locking? val podDevice = bluetoothAdapter.getRemoteDevice(podAddress) @@ -61,7 +60,7 @@ class BleManager @Inject constructor(private val context: Context, private val a val chars = discoverer.discoverServices() val bleIO = BleIO(aapsLogger, chars, incomingPackets, gatt, bleCommCallbacks) aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod") - bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandHello(CONTROLLER_ID).asByteArray()) + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandHello(CONTROLLER_ID).data) bleIO.readyToRead() } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index e6d9dd545e..daf3db26a4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType.Companion.byValue import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWrite +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWriteException import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.LinkedBlockingQueue @@ -50,23 +50,21 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP serviceDiscoveryComplete.await(timeout_ms.toLong(), TimeUnit.MILLISECONDS) } - @Throws(InterruptedException::class, TimeoutException::class, CouldNotConfirmWrite::class) + @Throws(InterruptedException::class, TimeoutException::class, CouldNotConfirmWriteException::class) fun confirmWrite(expectedPayload: ByteArray, timeout_ms: Int) { val received: CharacteristicWriteConfirmation = writeQueue.poll(timeout_ms.toLong(), TimeUnit.MILLISECONDS) ?: throw TimeoutException() when (received) { is CharacteristicWriteConfirmationPayload -> confirmWritePayload(expectedPayload, received) - is CharacteristicWriteConfirmationError -> - aapsLogger.debug(LTag.PUMPBTCOMM, "Could not confirm write: status was ${received.status}") + is CharacteristicWriteConfirmationError -> throw CouldNotConfirmWriteException(received.status) } - } private fun confirmWritePayload(expectedPayload: ByteArray, received: CharacteristicWriteConfirmationPayload) { if (!expectedPayload.contentEquals(received.payload)) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload + ". Status: " + received.status) - throw CouldNotConfirmWrite(expectedPayload, received.payload) + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload) + throw CouldNotConfirmWriteException(expectedPayload, received.payload) } aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload) } @@ -74,8 +72,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { super.onCharacteristicWrite(gatt, characteristic, status) val writeConfirmation = if (status == BluetoothGatt.GATT_SUCCESS) { - aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite value " + characteristic.getStringValue(0)) - CharacteristicWriteConfirmationPayload(characteristic.value, status) + CharacteristicWriteConfirmationPayload(characteristic.value) } else { CharacteristicWriteConfirmationError(status) } @@ -107,26 +104,33 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP @Throws(InterruptedException::class, CouldNotConfirmDescriptorWriteException::class) fun confirmWriteDescriptor(descriptorUUID: String, timeout_ms: Int) { - val confirmed = descriptorWriteQueue.poll(timeout_ms.toLong(), TimeUnit.MILLISECONDS) - if (descriptorUUID != confirmed.uuid) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got " + confirmed.uuid + ".Expected: " + descriptorUUID + ". Status: " + confirmed.status) - throw CouldNotConfirmDescriptorWriteException(confirmed.uuid!!, descriptorUUID) + val confirmed: DescriptorWriteConfirmation = descriptorWriteQueue.poll(timeout_ms.toLong(), TimeUnit.MILLISECONDS) + ?: throw TimeoutException() + when (confirmed) { + is DescriptorWriteConfirmationError -> throw CouldNotConfirmWriteException(confirmed.status) + is DescriptorWriteConfirmationUUID -> if (confirmed.uuid != descriptorUUID) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got ${confirmed.uuid}. Expected: ${descriptorUUID}") + throw CouldNotConfirmDescriptorWriteException(descriptorUUID, confirmed.uuid) + } else { + aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed descriptor write : " + confirmed.uuid) + } } } override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { super.onDescriptorWrite(gatt, descriptor, status) - var uuid: String? = null - if (status == BluetoothGatt.GATT_SUCCESS) { - uuid = descriptor.uuid.toString() + val writeConfirmation = if (status == BluetoothGatt.GATT_SUCCESS) { + aapsLogger.debug(LTag.PUMPBTCOMM, "OnDescriptor value " + descriptor.value) + DescriptorWriteConfirmationUUID(descriptor.uuid.toString()) + } else { + DescriptorWriteConfirmationError(status) } - val confirmation = DescriptorWriteConfirmation(status, uuid) try { if (descriptorWriteQueue.size > 0) { aapsLogger.warn(LTag.PUMPBTCOMM, "Descriptor write queue should be empty, found: " + descriptorWriteQueue.size) descriptorWriteQueue.clear() } - val offered = descriptorWriteQueue.offer(confirmation, WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) + val offered = descriptorWriteQueue.offer(writeConfirmation, WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) if (!offered) { aapsLogger.warn(LTag.PUMPBTCOMM, "Received delayed descriptor write confirmation") } @@ -136,7 +140,6 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP } companion object { - - private const val WRITE_CONFIRM_TIMEOUT_MS = 10 // the other thread should be waiting for the exchange + private const val WRITE_CONFIRM_TIMEOUT_MS = 10 // the confirmation queue should be empty anyway } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt index f863fa29ec..31e3595050 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt @@ -2,6 +2,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbac sealed class CharacteristicWriteConfirmation -class CharacteristicWriteConfirmationPayload(val payload: ByteArray, val status: Int) : CharacteristicWriteConfirmation() +data class CharacteristicWriteConfirmationPayload(val payload: ByteArray) : CharacteristicWriteConfirmation() -class CharacteristicWriteConfirmationError(val status: Int) : CharacteristicWriteConfirmation() \ No newline at end of file +data class CharacteristicWriteConfirmationError(val status: Int) : CharacteristicWriteConfirmation() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt index c975393d7c..3c7b4f4f9f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt @@ -1,3 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks -class DescriptorWriteConfirmation(var status: Int, var uuid: String?) \ No newline at end of file +sealed class DescriptorWriteConfirmation + +data class DescriptorWriteConfirmationUUID(val uuid: String): DescriptorWriteConfirmation() + +data class DescriptorWriteConfirmationError(val status: Int): DescriptorWriteConfirmation() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt index d5483f3d37..47389b0a05 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command abstract class BleCommand { - private val data: ByteArray + val data: ByteArray constructor(type: BleCommandType) { data = byteArrayOf(type.value) @@ -14,8 +14,4 @@ abstract class BleCommand { data[0] = type.value System.arraycopy(payload, 0, data, 1, payload.size) } - - fun asByteArray(): ByteArray { - return data - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt index 0b49f74970..2bc86e92a7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt @@ -1,3 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class CouldNotConfirmDescriptorWriteException(private val received: String, private val expected: String) : Exception() \ No newline at end of file +class CouldNotConfirmDescriptorWriteException(override val message: String?) : Exception(message) { + constructor(sent: String, confirmed: String): this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") + constructor(status: Int): this("Could not confirm write. Write status: ${status}") +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt deleted file mode 100644 index ab972d4344..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWrite.kt +++ /dev/null @@ -1,3 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions - -class CouldNotConfirmWrite(private val sent: ByteArray, private val confirmed: ByteArray?) : Exception() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt new file mode 100644 index 0000000000..a3c15bfb05 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class CouldNotConfirmWriteException(override val message: String?) : Exception(message) { + constructor(sent: ByteArray, confirmed: ByteArray): this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") + constructor(status: Int): this("Could not confirm write. Write status: ${status}") +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt index 9b8ff7488d..f7f6b08630 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt @@ -2,4 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import android.os.ParcelUuid -class DiscoveredInvalidPodException(message: String, serviceUUIds: List) : Exception("$message service UUIDs: $serviceUUIds") \ No newline at end of file +class DiscoveredInvalidPodException: Exception { + constructor(message: String) : super(message) {} + constructor(message: String, serviceUUIds: List) : super("$message service UUIDs: $serviceUUIds"){} +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index 397520820c..39cca93aea 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -41,7 +41,7 @@ class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map Date: Thu, 25 Feb 2021 19:19:06 +0100 Subject: [PATCH 010/649] ble: address review comments: renames and removed unused vars --- .../dash/driver/comm/CharacteristicType.kt | 2 +- .../dash/driver/comm/ServiceDiscoverer.kt | 5 ++- .../driver/comm/command/BleCommandType.kt | 1 + .../driver/comm/scan/BleDiscoveredDevice.kt | 32 +++++++++---------- .../dash/driver/comm/scan/ScanCollector.kt | 1 - 5 files changed, 20 insertions(+), 21 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt index a68ccba448..c241a6f43b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt @@ -6,7 +6,7 @@ import java.util.* enum class CharacteristicType(val value: String) { CMD("1a7e2441-e3ed-4464-8b7e-751e03d0dc5f"), DATA("1a7e2442-e3ed-4464-8b7e-751e03d0dc5f"); - val uUID: UUID + val uuid: UUID get() = UUID( BigInteger(value.replace("-", "").substring(0, 16), 16).toLong(), BigInteger(value.replace("-", "").substring(16), 16).toLong() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt index ccf7298a6e..997a3ee1cf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt @@ -4,7 +4,6 @@ import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException @@ -24,9 +23,9 @@ class ServiceDiscoverer(private val logger: AAPSLogger, private val gatt: Blueto logger.debug(LTag.PUMPBTCOMM, "Services discovered") val service = gatt.getService(SERVICE_UUID.toUuid()) ?: throw ServiceNotFoundException(SERVICE_UUID) - val cmdChar = service.getCharacteristic(CharacteristicType.CMD.uUID) + val cmdChar = service.getCharacteristic(CharacteristicType.CMD.uuid) ?: throw CharacteristicNotFoundException(CharacteristicType.CMD.value) - val dataChar = service.getCharacteristic(CharacteristicType.DATA.uUID) // TODO: this is never used + val dataChar = service.getCharacteristic(CharacteristicType.DATA.uuid) // TODO: this is never used ?: throw CharacteristicNotFoundException(CharacteristicType.DATA.value) var chars = mapOf(CharacteristicType.CMD to cmdChar, CharacteristicType.DATA to dataChar) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt index ad3cb86fe2..9fb461b02d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt @@ -5,6 +5,7 @@ enum class BleCommandType(val value: Byte) { companion object { + @JvmStatic fun byValue(value: Byte): BleCommandType = BleCommandType.values().firstOrNull { it.value == value } ?: throw IllegalArgumentException("Unknown BleCommandType: $value") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt index af6275cd6a..64e04630a0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -4,7 +4,7 @@ import android.bluetooth.le.ScanResult import android.os.ParcelUuid import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException -class BleDiscoveredDevice(val scanResult: ScanResult, private val podID: Long) { +class BleDiscoveredDevice(val scanResult: ScanResult, private val podId: Long) { private val sequenceNo: Int private val lotNo: Long @@ -12,29 +12,29 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podID: Long) { private fun validateServiceUUIDs() { val scanRecord = scanResult.scanRecord ?: throw DiscoveredInvalidPodException("Scan record is null"); - val serviceUUIDs = scanRecord.serviceUuids - if (serviceUUIDs.size != 9) { - throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUUIDs.size, serviceUUIDs) + val serviceUuids = scanRecord.serviceUuids + if (serviceUuids.size != 9) { + throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUuids.size, serviceUuids) } - if (extractUUID16(serviceUUIDs[0]) != "4024") { + if (extractUUID16(serviceUuids[0]) != MAIN_SERVICE_UUID) { // this is the service that we filtered for - throw DiscoveredInvalidPodException("The first exposed service UUID should be 4024, got " + extractUUID16(serviceUUIDs[0]), serviceUUIDs) + throw DiscoveredInvalidPodException("The first exposed service UUID should be 4024, got " + extractUUID16(serviceUuids[0]), serviceUuids) } // TODO understand what is serviceUUIDs[1]. 0x2470. Alarms? - if (extractUUID16(serviceUUIDs[2]) != "000a") { + if (extractUUID16(serviceUuids[2]) != "000a") { // constant? - throw DiscoveredInvalidPodException("The third exposed service UUID should be 000a, got " + serviceUUIDs[2], serviceUUIDs) + throw DiscoveredInvalidPodException("The third exposed service UUID should be 000a, got " + serviceUuids[2], serviceUuids) } } @Throws(DiscoveredInvalidPodException::class) - private fun validatePodID() { + private fun validatePodId() { val scanRecord = scanResult.scanRecord val serviceUUIDs = scanRecord.serviceUuids - val hexPodID = extractUUID16(serviceUUIDs[3]) + extractUUID16(serviceUUIDs[4]) - val podID = hexPodID.toLong(16) - if (this.podID != podID) { - throw DiscoveredInvalidPodException("This is not the POD we are looking for. " + this.podID + " found: " + podID, serviceUUIDs) + val hexPodId = extractUUID16(serviceUUIDs[3]) + extractUUID16(serviceUUIDs[4]) + val podId = hexPodId.toLong(16) + if (this.podId != podId) { + throw DiscoveredInvalidPodException("This is not the POD we are looking for. " + this.podId + " found: " + this.podId, serviceUUIDs) } } @@ -58,14 +58,14 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podID: Long) { override fun toString(): String { return "BleDiscoveredDevice{" + "scanResult=" + scanResult + - ", podID=" + podID + + ", podID=" + podId + ", sequenceNo=" + sequenceNo + ", lotNo=" + lotNo + '}' } companion object { - + const val MAIN_SERVICE_UUID = "4024"; private fun extractUUID16(uuid: ParcelUuid): String { return uuid.toString().substring(4, 8) } @@ -73,7 +73,7 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podID: Long) { init { validateServiceUUIDs() - validatePodID() + validatePodId() lotNo = parseLotNo() sequenceNo = parseSeqNo() } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt index 1164815970..0030c755eb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt @@ -21,7 +21,6 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S } override fun onScanFailed(errorCode: Int) { - scanFailed = errorCode logger.warn(LTag.PUMPBTCOMM, "Scan failed with errorCode: $errorCode") super.onScanFailed(errorCode) } From 566d8f172bbec89adf766ddc5ddc5cd967f64df9 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Thu, 25 Feb 2021 23:11:18 +0100 Subject: [PATCH 011/649] make automatic kotlin conversion build - untested, still not idiomatic --- .../driver/pod/command/DeactivateCommand.java | 41 --- .../driver/pod/command/DeactivateCommand.kt | 42 +++ .../driver/pod/command/GetVersionCommand.java | 42 --- .../driver/pod/command/GetVersionCommand.kt | 45 +++ .../pod/command/ProgramAlertsCommand.java | 66 ----- .../pod/command/ProgramAlertsCommand.kt | 63 +++++ .../pod/command/ProgramBasalCommand.java | 132 --------- .../driver/pod/command/ProgramBasalCommand.kt | 119 ++++++++ .../pod/command/ProgramBolusCommand.java | 123 --------- .../driver/pod/command/ProgramBolusCommand.kt | 107 ++++++++ .../pod/command/ProgramInsulinCommand.java | 96 ------- .../pod/command/ProgramInsulinCommand.kt | 66 +++++ .../pod/command/ProgramTempBasalCommand.java | 123 --------- .../pod/command/ProgramTempBasalCommand.kt | 94 +++++++ .../pod/command/SetUniqueIdCommand.java | 99 ------- .../driver/pod/command/SetUniqueIdCommand.kt | 91 +++++++ .../pod/command/SilenceAlertsCommand.java | 133 --------- .../pod/command/SilenceAlertsCommand.kt | 111 ++++++++ .../pod/command/StopDeliveryCommand.java | 97 ------- .../driver/pod/command/StopDeliveryCommand.kt | 76 ++++++ .../dash/driver/pod/command/base/Command.java | 7 - .../Command.kt} | 10 +- .../driver/pod/command/base/CommandType.java | 26 -- .../driver/pod/command/base/CommandType.kt | 16 ++ .../command/base/HeaderEnabledCommand.java | 40 --- .../pod/command/base/HeaderEnabledCommand.kt | 29 ++ .../pod/command/base/NonceEnabledCommand.java | 11 - .../pod/command/base/NonceEnabledCommand.kt | 9 + ...{CommandBuilder.java => CommandBuilder.kt} | 11 +- .../builder/HeaderEnabledCommandBuilder.java | 36 --- .../builder/HeaderEnabledCommandBuilder.kt | 32 +++ .../builder/NonceEnabledCommandBuilder.java | 19 -- .../builder/NonceEnabledCommandBuilder.kt | 17 ++ .../program/BasalInsulinProgramElement.java | 58 ---- .../program/BasalInsulinProgramElement.kt | 32 +++ .../BasalShortInsulinProgramElement.java | 34 --- .../BasalShortInsulinProgramElement.kt | 33 +++ .../BolusShortInsulinProgramElement.java | 19 -- .../BolusShortInsulinProgramElement.kt | 9 + .../CurrentBasalInsulinProgramElement.java | 33 --- .../CurrentBasalInsulinProgramElement.kt | 10 + .../command/insulin/program/CurrentSlot.java | 33 --- .../command/insulin/program/CurrentSlot.kt | 10 + .../program/ShortInsulinProgramElement.kt | 5 + .../TempBasalInsulinProgramElement.java | 23 -- .../program/TempBasalInsulinProgramElement.kt | 22 ++ .../program/util/ProgramBasalUtil.java | 257 ------------------ .../insulin/program/util/ProgramBasalUtil.kt | 208 ++++++++++++++ .../program/util/ProgramTempBasalUtil.java | 68 ----- .../program/util/ProgramTempBasalUtil.kt | 62 +++++ .../dash/driver/pod/definition/AlarmType.java | 174 ------------ .../dash/driver/pod/definition/AlarmType.kt | 17 ++ .../pod/definition/AlertConfiguration.java | 61 ----- .../pod/definition/AlertConfiguration.kt | 43 +++ .../dash/driver/pod/definition/AlertSlot.java | 32 --- .../dash/driver/pod/definition/AlertSlot.kt | 17 ++ .../pod/definition/AlertTriggerType.java | 6 - .../driver/pod/definition/AlertTriggerType.kt | 5 + .../driver/pod/definition/BasalProgram.java | 92 ------- .../driver/pod/definition/BasalProgram.kt | 47 ++++ .../pod/definition/BeepRepetitionType.java | 20 -- .../pod/definition/BeepRepetitionType.kt | 13 + .../dash/driver/pod/definition/BeepType.java | 17 -- .../dash/driver/pod/definition/BeepType.kt | 8 + .../driver/pod/definition/DeliveryStatus.java | 26 -- .../driver/pod/definition/DeliveryStatus.kt | 17 ++ .../dash/driver/pod/definition/Encodable.java | 5 - .../dash/driver/pod/definition/Encodable.kt | 6 + .../driver/pod/definition/NakErrorType.java | 49 ---- .../driver/pod/definition/NakErrorType.kt | 17 ++ .../driver/pod/definition/OmnipodEvent.java | 26 -- .../driver/pod/definition/OmnipodEvent.kt | 7 + .../dash/driver/pod/definition/PodStatus.java | 36 --- .../dash/driver/pod/definition/PodStatus.kt | 17 ++ .../pod/definition/ProgramReminder.java | 19 -- .../driver/pod/definition/ProgramReminder.kt | 11 + .../pod/response/ActivationResponseBase.java | 14 - .../pod/response/ActivationResponseBase.kt | 5 + .../AdditionalStatusResponseBase.java | 14 - .../response/AdditionalStatusResponseBase.kt | 5 + .../pod/response/AlarmStatusResponse.java | 240 ---------------- .../pod/response/AlarmStatusResponse.kt | 243 +++++++++++++++++ .../pod/response/DefaultStatusResponse.java | 136 --------- .../pod/response/DefaultStatusResponse.kt | 118 ++++++++ .../dash/driver/pod/response/NakResponse.java | 71 ----- .../dash/driver/pod/response/NakResponse.kt | 69 +++++ .../dash/driver/pod/response/Response.java | 7 - .../dash/driver/pod/response/Response.kt | 7 + .../driver/pod/response/ResponseBase.java | 22 -- .../dash/driver/pod/response/ResponseBase.kt | 7 + .../driver/pod/response/ResponseType.java | 80 ------ .../dash/driver/pod/response/ResponseType.kt | 57 ++++ .../pod/response/SetUniqueIdResponse.java | 155 ----------- .../pod/response/SetUniqueIdResponse.kt | 154 +++++++++++ .../driver/pod/response/VersionResponse.java | 128 --------- .../driver/pod/response/VersionResponse.kt | 109 ++++++++ ...ger.java => OmnipodDashPodStateManager.kt} | 5 +- .../dash/driver/pod/util/MessageUtil.java | 40 --- .../dash/driver/pod/util/MessageUtil.kt | 45 +++ 99 files changed, 2366 insertions(+), 3098 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.java rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/{insulin/program/ShortInsulinProgramElement.java => base/Command.kt} (50%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/{CommandBuilder.java => CommandBuilder.kt} (50%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/{OmnipodDashPodStateManager.java => OmnipodDashPodStateManager.kt} (50%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.java deleted file mode 100644 index 3f6ce6d099..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; - -public final class DeactivateCommand extends NonceEnabledCommand { - private static final short LENGTH = 6; - private static final byte BODY_LENGTH = 4; - - DeactivateCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag, int nonce) { - super(CommandType.DEACTIVATE, uniqueId, sequenceNumber, multiCommandFlag, nonce); - } - - @Override public byte[] getEncoded() { - return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.getValue()) // - .put(BODY_LENGTH) // - .putInt(nonce) // - .array()); - } - - @Override public String toString() { - return "DeactivateCommand{" + - "nonce=" + nonce + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public static final class Builder extends NonceEnabledCommandBuilder { - @Override protected final DeactivateCommand buildCommand() { - return new DeactivateCommand(uniqueId, sequenceNumber, multiCommandFlag, nonce); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt new file mode 100644 index 0000000000..e29fd1de16 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt @@ -0,0 +1,42 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import java.nio.ByteBuffer + +class DeactivateCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, nonce: Int) : NonceEnabledCommand(CommandType.DEACTIVATE, uniqueId, sequenceNumber, multiCommandFlag, nonce) { + + // + // + // + // + // + override val encoded: ByteArray + get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(nonce) // + .array()) + + override fun toString(): String = "DeactivateCommand{" + + "nonce=" + nonce + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + + class Builder : NonceEnabledCommandBuilder() { + + override fun buildCommand(): DeactivateCommand = + DeactivateCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!) // TODO this might crash if not all are set + } + + companion object { + + private const val LENGTH: Short = 6 + private const val BODY_LENGTH: Byte = 4 + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.java deleted file mode 100644 index 4fce0c11a2..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.java +++ /dev/null @@ -1,42 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder; - -public final class GetVersionCommand extends HeaderEnabledCommand { - public static final int DEFAULT_UNIQUE_ID = -1; // FIXME move - - private static final short LENGTH = 6; - private static final byte BODY_LENGTH = 4; - - GetVersionCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag) { - super(CommandType.GET_VERSION, uniqueId, sequenceNumber, multiCommandFlag); - } - - @Override public byte[] getEncoded() { - return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.getValue()) // - .put(BODY_LENGTH) // - .putInt(uniqueId) // - .array()); - } - - @Override public String toString() { - return "GetVersionCommand{" + - "commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public static final class Builder extends HeaderEnabledCommandBuilder { - @Override protected final GetVersionCommand buildCommand() { - return new GetVersionCommand(uniqueId, sequenceNumber, multiCommandFlag); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt new file mode 100644 index 0000000000..bca46f8342 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder +import java.nio.ByteBuffer + +class GetVersionCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean) : HeaderEnabledCommand(CommandType.GET_VERSION, uniqueId, sequenceNumber, multiCommandFlag) { + + // + // + // + // + // + override val encoded: ByteArray + get() = HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // + .put(HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(uniqueId) // + .array()) + + override fun toString(): String { + return "GetVersionCommand{" + + "commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + class Builder : HeaderEnabledCommandBuilder() { + + override fun buildCommand(): GetVersionCommand { + return GetVersionCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag) + } + } + + companion object { + + const val DEFAULT_UNIQUE_ID = -1 // FIXME move + private const val LENGTH: Short = 6 + private const val BODY_LENGTH: Byte = 4 + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.java deleted file mode 100644 index 39e850736a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.java +++ /dev/null @@ -1,66 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration; - -public final class ProgramAlertsCommand extends NonceEnabledCommand { - private final List alertConfigurations; - - ProgramAlertsCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag, List alertConfigurations, int nonce) { - super(CommandType.PROGRAM_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce); - this.alertConfigurations = new ArrayList<>(alertConfigurations); - } - - @Override public byte[] getEncoded() { - ByteBuffer byteBuffer = ByteBuffer.allocate(getLength() + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, getLength(), multiCommandFlag)) // - .put(commandType.getValue()) // - .put(getBodyLength()) // - .putInt(nonce); - for (AlertConfiguration configuration : alertConfigurations) { - byteBuffer.put(configuration.getEncoded()); - } - return appendCrc(byteBuffer.array()); - } - - private short getLength() { - return (short) (alertConfigurations.size() * 6 + 6); - } - - private byte getBodyLength() { - return (byte) (alertConfigurations.size() * 6 + 4); - } - - @Override public String toString() { - return "ProgramAlertsCommand{" + - "alertConfigurations=" + alertConfigurations + - ", nonce=" + nonce + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public static final class Builder extends NonceEnabledCommandBuilder { - private List alertConfigurations; - - public Builder setAlertConfigurations(List alertConfigurations) { - this.alertConfigurations = alertConfigurations; - return this; - } - - @Override protected final ProgramAlertsCommand buildCommand() { - if (this.alertConfigurations == null) { - throw new IllegalArgumentException("alertConfigurations can not be null"); - } - return new ProgramAlertsCommand(uniqueId, sequenceNumber, multiCommandFlag, alertConfigurations, nonce); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt new file mode 100644 index 0000000000..7e8dcb7971 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt @@ -0,0 +1,63 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration +import java.nio.ByteBuffer +import java.util.* + +class ProgramAlertsCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, alertConfigurations: List?, nonce: Int) : NonceEnabledCommand(CommandType.PROGRAM_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { + + private val alertConfigurations: List + + private fun getLength(): Short { + return (alertConfigurations.size * 6 + 6).toShort() + } + + private fun getBodyLength(): Byte { + return (alertConfigurations.size * 6 + 4).toByte() + } + + override val encoded: ByteArray + get() { + val byteBuffer: ByteBuffer = ByteBuffer.allocate(getLength() + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, getLength(), multiCommandFlag)) // + .put(commandType.value) // + .put(getBodyLength()) // + .putInt(nonce) + for (configuration in alertConfigurations) { + byteBuffer.put(configuration.encoded) + } + return appendCrc(byteBuffer.array()) + } + + override fun toString(): String { + return "ProgramAlertsCommand{" + + "alertConfigurations=" + alertConfigurations + + ", nonce=" + nonce + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + class Builder : NonceEnabledCommandBuilder() { + + private var alertConfigurations: List? = null + fun setAlertConfigurations(alertConfigurations: List?): Builder { + this.alertConfigurations = alertConfigurations + return this + } + + override fun buildCommand(): ProgramAlertsCommand { + requireNotNull(alertConfigurations) { "alertConfigurations can not be null" } // !!? + return ProgramAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, alertConfigurations, nonce!!) // TODO this might crash if not all are set + } + } + + init { + this.alertConfigurations = ArrayList(alertConfigurations) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.java deleted file mode 100644 index a79f7b7374..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.java +++ /dev/null @@ -1,132 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.CurrentBasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.CurrentSlot; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder; - -// Always preceded by 0x1a ProgramInsulinCommand -public final class ProgramBasalCommand extends HeaderEnabledCommand { - private final ProgramInsulinCommand interlockCommand; - private final List insulinProgramElements; - private final ProgramReminder programReminder; - private final byte currentInsulinProgramElementIndex; - private final short remainingTenthPulsesInCurrentInsulinProgramElement; - private final int delayUntilNextTenthPulseInUsec; - - ProgramBasalCommand(ProgramInsulinCommand interlockCommand, int uniqueId, short sequenceNumber, boolean multiCommandFlag, List insulinProgramElements, ProgramReminder programReminder, byte currentInsulinProgramElementIndex, short remainingTenthPulsesInCurrentInsulinProgramElement, int delayUntilNextTenthPulseInUsec) { - super(CommandType.PROGRAM_BASAL, uniqueId, sequenceNumber, multiCommandFlag); - - this.interlockCommand = interlockCommand; - this.insulinProgramElements = new ArrayList<>(insulinProgramElements); - this.programReminder = programReminder; - this.currentInsulinProgramElementIndex = currentInsulinProgramElementIndex; - this.remainingTenthPulsesInCurrentInsulinProgramElement = remainingTenthPulsesInCurrentInsulinProgramElement; - this.delayUntilNextTenthPulseInUsec = delayUntilNextTenthPulseInUsec; - } - - short getLength() { - return (short) (insulinProgramElements.size() * 6 + 10); - } - - byte getBodyLength() { - return (byte) (insulinProgramElements.size() * 6 + 8); - } - - @Override public byte[] getEncoded() { - ByteBuffer buffer = ByteBuffer.allocate(getLength()) // - .put(getCommandType().getValue()) // - .put(getBodyLength()) // - .put(programReminder.getEncoded()) // - .put(currentInsulinProgramElementIndex) // - .putShort(remainingTenthPulsesInCurrentInsulinProgramElement) // - .putInt(delayUntilNextTenthPulseInUsec); - for (BasalInsulinProgramElement insulinProgramElement : insulinProgramElements) { - buffer.put(insulinProgramElement.getEncoded()); - } - - byte[] basalCommand = buffer.array(); - byte[] interlockCommand = this.interlockCommand.getEncoded(); - byte[] header = encodeHeader(uniqueId, sequenceNumber, (short) (basalCommand.length + interlockCommand.length), multiCommandFlag); - - return appendCrc(ByteBuffer.allocate(basalCommand.length + interlockCommand.length + header.length) // - .put(header) // - .put(interlockCommand) // - .put(basalCommand) // - .array()); - } - - @Override public String toString() { - return "ProgramBasalCommand{" + - "interlockCommand=" + interlockCommand + - ", insulinProgramElements=" + insulinProgramElements + - ", programReminder=" + programReminder + - ", currentInsulinProgramElementIndex=" + currentInsulinProgramElementIndex + - ", remainingTenthPulsesInCurrentInsulinProgramElement=" + remainingTenthPulsesInCurrentInsulinProgramElement + - ", delayUntilNextTenthPulseInUsec=" + delayUntilNextTenthPulseInUsec + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public static final class Builder extends NonceEnabledCommandBuilder { - private BasalProgram basalProgram; - private ProgramReminder programReminder; - private Date currentTime; - - public Builder setBasalProgram(BasalProgram basalProgram) { - this.basalProgram = basalProgram; - return this; - } - - public Builder setProgramReminder(ProgramReminder programReminder) { - this.programReminder = programReminder; - return this; - } - - public Builder setCurrentTime(Date currentTime) { - this.currentTime = currentTime; - return this; - } - - @Override protected ProgramBasalCommand buildCommand() { - if (basalProgram == null) { - throw new IllegalArgumentException("basalProgram can not be null"); - } - if (programReminder == null) { - throw new IllegalArgumentException("programReminder can not be null"); - } - if (currentTime == null) { - throw new IllegalArgumentException("currentTime can not be null"); - } - - short[] pulsesPerSlot = ProgramBasalUtil.mapBasalProgramToPulsesPerSlot(basalProgram); - CurrentSlot currentSlot = ProgramBasalUtil.calculateCurrentSlot(pulsesPerSlot, currentTime); - short checksum = ProgramBasalUtil.calculateChecksum(pulsesPerSlot, currentSlot); - List longInsulinProgramElements = ProgramBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(ProgramBasalUtil.mapBasalProgramToTenthPulsesPerSlot(basalProgram)); - List shortInsulinProgramElements = ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot); - CurrentBasalInsulinProgramElement currentBasalInsulinProgramElement = ProgramBasalUtil.calculateCurrentLongInsulinProgramElement(longInsulinProgramElements, currentTime); - - ProgramInsulinCommand interlockCommand = new ProgramInsulinCommand(uniqueId, sequenceNumber, multiCommandFlag, nonce, - shortInsulinProgramElements, checksum, currentSlot.getIndex(), currentSlot.getEighthSecondsRemaining(), - currentSlot.getPulsesRemaining(), ProgramInsulinCommand.DeliveryType.BASAL); - - return new ProgramBasalCommand(interlockCommand, uniqueId, sequenceNumber, multiCommandFlag, - longInsulinProgramElements, programReminder, currentBasalInsulinProgramElement.getIndex(), - currentBasalInsulinProgramElement.getRemainingTenthPulses(), currentBasalInsulinProgramElement.getDelayUntilNextTenthPulseInUsec()); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt new file mode 100644 index 0000000000..3d05aada1b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -0,0 +1,119 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramTempBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import java.nio.ByteBuffer +import java.util.* + +// Always preceded by 0x1a ProgramInsulinCommand +class ProgramBasalCommand internal constructor(private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, insulinProgramElements: List?, programReminder: ProgramReminder, currentInsulinProgramElementIndex: Byte, remainingTenthPulsesInCurrentInsulinProgramElement: Short, delayUntilNextTenthPulseInUsec: Int) : HeaderEnabledCommand(CommandType.PROGRAM_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { + + private val insulinProgramElements: List + private val programReminder: ProgramReminder + private val currentInsulinProgramElementIndex: Byte + private val remainingTenthPulsesInCurrentInsulinProgramElement: Short + private val delayUntilNextTenthPulseInUsec: Int + val length: Short + get() = (insulinProgramElements.size * 6 + 10).toShort() + val bodyLength: Byte + get() = (insulinProgramElements.size * 6 + 8).toByte()// + + // + // + // + // + // + // + // + // + // + override val encoded: ByteArray + get() { + val buffer = ByteBuffer.allocate(length.toInt()) // + .put(commandType.value) // + .put(bodyLength) // + .put(programReminder.encoded) // + .put(currentInsulinProgramElementIndex) // + .putShort(remainingTenthPulsesInCurrentInsulinProgramElement) // + .putInt(delayUntilNextTenthPulseInUsec) + for (insulinProgramElement in insulinProgramElements) { + buffer.put(insulinProgramElement.encoded) + } + val basalCommand = buffer.array() + val interlockCommand = interlockCommand.encoded + val header: ByteArray = HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, (basalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + return HeaderEnabledCommand.appendCrc(ByteBuffer.allocate(basalCommand.size + interlockCommand.size + header.size) // + .put(header) // + .put(interlockCommand) // + .put(basalCommand) // + .array()) + } + + override fun toString(): String { + return "ProgramBasalCommand{" + + "interlockCommand=" + interlockCommand + + ", insulinProgramElements=" + insulinProgramElements + + ", programReminder=" + programReminder + + ", currentInsulinProgramElementIndex=" + currentInsulinProgramElementIndex + + ", remainingTenthPulsesInCurrentInsulinProgramElement=" + remainingTenthPulsesInCurrentInsulinProgramElement + + ", delayUntilNextTenthPulseInUsec=" + delayUntilNextTenthPulseInUsec + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + class Builder : NonceEnabledCommandBuilder() { + + private var basalProgram: BasalProgram? = null + private var programReminder: ProgramReminder? = null + private var currentTime: Date? = null + fun setBasalProgram(basalProgram: BasalProgram?): Builder { + this.basalProgram = basalProgram + return this + } + + fun setProgramReminder(programReminder: ProgramReminder?): Builder { + this.programReminder = programReminder + return this + } + + fun setCurrentTime(currentTime: Date?): Builder { + this.currentTime = currentTime + return this + } + + override fun buildCommand(): ProgramBasalCommand { + requireNotNull(basalProgram) { "basalProgram can not be null" } + requireNotNull(programReminder) { "programReminder can not be null" } + requireNotNull(currentTime) { "currentTime can not be null" } + val pulsesPerSlot = ProgramBasalUtil.mapBasalProgramToPulsesPerSlot(basalProgram!!) + val currentSlot = ProgramBasalUtil.calculateCurrentSlot(pulsesPerSlot, currentTime) + val checksum = ProgramBasalUtil.calculateChecksum(pulsesPerSlot, currentSlot) + val longInsulinProgramElements: List = mapTenthPulsesPerSlotToLongInsulinProgramElements(ProgramBasalUtil.mapBasalProgramToTenthPulsesPerSlot(basalProgram!!)) + val shortInsulinProgramElements = ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) + val currentBasalInsulinProgramElement = ProgramBasalUtil.calculateCurrentLongInsulinProgramElement(longInsulinProgramElements, currentTime) + val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, + shortInsulinProgramElements, checksum, currentSlot.index, currentSlot.eighthSecondsRemaining, + currentSlot.pulsesRemaining, ProgramInsulinCommand.DeliveryType.BASAL) + return ProgramBasalCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, + longInsulinProgramElements, programReminder!!, currentBasalInsulinProgramElement.index, + currentBasalInsulinProgramElement.remainingTenthPulses, currentBasalInsulinProgramElement.delayUntilNextTenthPulseInUsec) + } + } + + init { + this.insulinProgramElements = ArrayList(insulinProgramElements) + this.programReminder = programReminder + this.currentInsulinProgramElementIndex = currentInsulinProgramElementIndex + this.remainingTenthPulsesInCurrentInsulinProgramElement = remainingTenthPulsesInCurrentInsulinProgramElement + this.delayUntilNextTenthPulseInUsec = delayUntilNextTenthPulseInUsec + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.java deleted file mode 100644 index 7c1e4a80bd..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.java +++ /dev/null @@ -1,123 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.Collections; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BolusShortInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil; - -// NOT SUPPORTED: extended bolus -public final class ProgramBolusCommand extends HeaderEnabledCommand { - private static final short LENGTH = 15; - private static final byte BODY_LENGTH = 13; - - private final ProgramInsulinCommand interlockCommand; - private final ProgramReminder programReminder; - private final short numberOfTenthPulses; - private final int delayUntilFirstTenthPulseInUsec; - - ProgramBolusCommand(ProgramInsulinCommand interlockCommand, int uniqueId, short sequenceNumber, boolean multiCommandFlag, ProgramReminder programReminder, short numberOfTenthPulses, int delayUntilFirstTenthPulseInUsec) { - super(CommandType.PROGRAM_BOLUS, uniqueId, sequenceNumber, multiCommandFlag); - this.interlockCommand = interlockCommand; - this.programReminder = programReminder; - this.numberOfTenthPulses = numberOfTenthPulses; - this.delayUntilFirstTenthPulseInUsec = delayUntilFirstTenthPulseInUsec; - } - - @Override public byte[] getEncoded() { - byte[] bolusCommand = ByteBuffer.allocate(LENGTH) // - .put(commandType.getValue()) // - .put(BODY_LENGTH) // - .put(programReminder.getEncoded()) // - .putShort(numberOfTenthPulses) // - .putInt(delayUntilFirstTenthPulseInUsec) // - .putShort((short) 0) // Extended bolus pulses - .putInt(0) // Delay between tenth extended pulses in usec - .array(); - - byte[] interlockCommand = this.interlockCommand.getEncoded(); - byte[] header = encodeHeader(uniqueId, sequenceNumber, (short) (bolusCommand.length + interlockCommand.length), multiCommandFlag); - - return appendCrc(ByteBuffer.allocate(header.length + interlockCommand.length + bolusCommand.length) // - .put(header) // - .put(interlockCommand) // - .put(bolusCommand) // - .array()); - } - - @Override public String toString() { - return "ProgramBolusCommand{" + - "interlockCommand=" + interlockCommand + - ", programReminder=" + programReminder + - ", numberOfTenthPulses=" + numberOfTenthPulses + - ", delayUntilFirstTenthPulseInUsec=" + delayUntilFirstTenthPulseInUsec + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public static final class Builder extends NonceEnabledCommandBuilder { - private Double numberOfUnits; - private Byte delayBetweenPulsesInEighthSeconds; - private ProgramReminder programReminder; - - public Builder setNumberOfUnits(double numberOfUnits) { - if (numberOfUnits <= 0.0D) { - throw new IllegalArgumentException("Number of units should be greater than zero"); - } - if ((int) (numberOfUnits * 1000) % 50 != 0) { - throw new IllegalArgumentException("Number of units must be dividable by 0.05"); - } - this.numberOfUnits = ((int) (numberOfUnits * 100)) / 100.0d; - return this; - } - - public Builder setDelayBetweenPulsesInEighthSeconds(byte delayBetweenPulsesInEighthSeconds) { - this.delayBetweenPulsesInEighthSeconds = delayBetweenPulsesInEighthSeconds; - return this; - } - - public Builder setProgramReminder(ProgramReminder programReminder) { - this.programReminder = programReminder; - return this; - } - - @Override protected ProgramBolusCommand buildCommand() { - if (numberOfUnits == null) { - throw new IllegalArgumentException("numberOfUnits can not be null"); - } - if (delayBetweenPulsesInEighthSeconds == null) { - throw new IllegalArgumentException("delayBetweenPulsesInEighthSeconds can not be null"); - } - if (programReminder == null) { - throw new IllegalArgumentException("programReminder can not be null"); - } - - short numberOfPulses = (short) Math.round(numberOfUnits * 20); - short byte10And11 = (short) (numberOfPulses * delayBetweenPulsesInEighthSeconds); - - ProgramInsulinCommand interlockCommand = new ProgramInsulinCommand(uniqueId, sequenceNumber, multiCommandFlag, nonce, - Collections.singletonList(new BolusShortInsulinProgramElement(numberOfPulses)), calculateChecksum((byte) 0x01, byte10And11, numberOfPulses), - (byte) 0x01, byte10And11, (short) numberOfPulses, ProgramInsulinCommand.DeliveryType.BOLUS); - - int delayUntilFirstTenthPulseInUsec = delayBetweenPulsesInEighthSeconds / 8 * 100_000; - - return new ProgramBolusCommand(interlockCommand, uniqueId, sequenceNumber, multiCommandFlag, programReminder, (short) (numberOfPulses * 10), delayUntilFirstTenthPulseInUsec); - } - } - - private static short calculateChecksum(byte numberOfSlots, short byte10And11, short numberOfPulses) { - return MessageUtil.calculateChecksum(ByteBuffer.allocate(7) // - .put(numberOfSlots) // - .putShort(byte10And11) // - .putShort(numberOfPulses) // - .putShort(numberOfPulses) // - .array()); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt new file mode 100644 index 0000000000..70f75a4f11 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -0,0 +1,107 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BolusShortInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil +import java.nio.ByteBuffer + +// NOT SUPPORTED: extended bolus +class ProgramBolusCommand internal constructor(private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val programReminder: ProgramReminder, private val numberOfTenthPulses: Short, // + private val delayUntilFirstTenthPulseInUsec: Int) : HeaderEnabledCommand(CommandType.PROGRAM_BOLUS, uniqueId, sequenceNumber, multiCommandFlag) { + + // + // + // + // + // + // + // + // + // + // Extended bolus pulses + // Delay between tenth extended pulses in usec + override val encoded: ByteArray + get() { + val bolusCommand = ByteBuffer.allocate(LENGTH.toInt()) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .put(programReminder.encoded) // + .putShort(numberOfTenthPulses) // + .putInt(delayUntilFirstTenthPulseInUsec) // + .putShort(0.toShort()) // Extended bolus pulses + .putInt(0) // Delay between tenth extended pulses in usec + .array() + val interlockCommand = interlockCommand.encoded + val header: ByteArray = HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, (bolusCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + return HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + bolusCommand.size) // + .put(header) // + .put(interlockCommand) // + .put(bolusCommand) // + .array()) + } + + override fun toString(): String { + return "ProgramBolusCommand{" + + "interlockCommand=" + interlockCommand + + ", programReminder=" + programReminder + + ", numberOfTenthPulses=" + numberOfTenthPulses + + ", delayUntilFirstTenthPulseInUsec=" + delayUntilFirstTenthPulseInUsec + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + class Builder : NonceEnabledCommandBuilder() { + + private var numberOfUnits: Double? = null + private var delayBetweenPulsesInEighthSeconds: Byte? = null + private var programReminder: ProgramReminder? = null + fun setNumberOfUnits(numberOfUnits: Double): Builder { + require(numberOfUnits > 0.0) { "Number of units should be greater than zero" } + require((numberOfUnits * 1000).toInt() % 50 == 0) { "Number of units must be dividable by 0.05" } + this.numberOfUnits = (numberOfUnits * 100).toInt() / 100.0 + return this + } + + fun setDelayBetweenPulsesInEighthSeconds(delayBetweenPulsesInEighthSeconds: Byte): Builder { + this.delayBetweenPulsesInEighthSeconds = delayBetweenPulsesInEighthSeconds + return this + } + + fun setProgramReminder(programReminder: ProgramReminder?): Builder { + this.programReminder = programReminder + return this + } + + override fun buildCommand(): ProgramBolusCommand { + requireNotNull(numberOfUnits) { "numberOfUnits can not be null" } + requireNotNull(delayBetweenPulsesInEighthSeconds) { "delayBetweenPulsesInEighthSeconds can not be null" } + requireNotNull(programReminder) { "programReminder can not be null" } + val numberOfPulses = Math.round(numberOfUnits!! * 20).toShort() + val byte10And11 = (numberOfPulses * delayBetweenPulsesInEighthSeconds!!).toShort() + val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, listOf(BolusShortInsulinProgramElement(numberOfPulses)), calculateChecksum(0x01.toByte(), byte10And11, numberOfPulses), + 0x01.toByte(), byte10And11, numberOfPulses, ProgramInsulinCommand.DeliveryType.BOLUS) + val delayUntilFirstTenthPulseInUsec = delayBetweenPulsesInEighthSeconds!! / 8 * 100000 + return ProgramBolusCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, programReminder!!, (numberOfPulses * 10).toShort(), delayUntilFirstTenthPulseInUsec) + } + } + + companion object { + + private const val LENGTH: Short = 15 + private const val BODY_LENGTH: Byte = 13 + private fun calculateChecksum(numberOfSlots: Byte, byte10And11: Short, numberOfPulses: Short): Short { + return MessageUtil.calculateChecksum(ByteBuffer.allocate(7) // + .put(numberOfSlots) // + .putShort(byte10And11) // + .putShort(numberOfPulses) // + .putShort(numberOfPulses) // + .array()) + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.java deleted file mode 100644 index ce060000cc..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.java +++ /dev/null @@ -1,96 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement; - -// Always followed by one of: 0x13, 0x16, 0x17 -final class ProgramInsulinCommand extends NonceEnabledCommand { - private final List insulinProgramElements; - private final short checksum; - private final byte byte9; - private final short byte10And11; - private final short byte12And13; - private final DeliveryType deliveryType; - - ProgramInsulinCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag, int nonce, List insulinProgramElements, short checksum, byte byte9, short byte10And11, short byte12And13, DeliveryType deliveryType) { - super(CommandType.PROGRAM_INSULIN, uniqueId, sequenceNumber, multiCommandFlag, nonce); - this.insulinProgramElements = new ArrayList<>(insulinProgramElements); - this.checksum = checksum; - this.byte9 = byte9; - this.byte10And11 = byte10And11; - this.byte12And13 = byte12And13; - this.deliveryType = deliveryType; - } - - public short getLength() { - return (short) (insulinProgramElements.size() * 2 + 14); - } - - public byte getBodyLength() { - return (byte) (insulinProgramElements.size() * 2 + 12); - } - - @Override public byte[] getEncoded() { - ByteBuffer buffer = ByteBuffer.allocate(this.getLength()) // - .put(commandType.getValue()) // - .put(getBodyLength()) // - .putInt(nonce) // - .put(deliveryType.getValue()) // - .putShort(checksum) // - .put(byte9) // BASAL: currentSlot // BOLUS: number of ShortInsulinProgramElements - .putShort(byte10And11) // BASAL: remainingEighthSecondsInCurrentSlot // BOLUS: immediate pulses multiplied by delay between pulses in eighth seconds - .putShort(byte12And13); // BASAL: remainingPulsesInCurrentSlot // BOLUS: immediate pulses - - for (ShortInsulinProgramElement element : insulinProgramElements) { - buffer.put(element.getEncoded()); - } - - return buffer.array(); - } - - enum DeliveryType { - BASAL((byte) 0x00), - TEMP_BASAL((byte) 0x01), - BOLUS((byte) 0x02); - - private final byte value; - - DeliveryType(byte value) { - this.value = value; - } - - public byte getValue() { - return value; - } - } - - public short calculateChecksum(byte[] bytes) { - short sum = 0; - for (byte b : bytes) { - sum += (short) (b & 0xff); - } - return sum; - } - - @Override public String toString() { - return "ProgramInsulinCommand{" + - "insulinProgramElements=" + insulinProgramElements + - ", checksum=" + checksum + - ", byte9=" + byte9 + - ", byte10And11=" + byte10And11 + - ", byte12And13=" + byte12And13 + - ", deliveryType=" + deliveryType + - ", nonce=" + nonce + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt new file mode 100644 index 0000000000..a357013027 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt @@ -0,0 +1,66 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement +import java.nio.ByteBuffer +import java.util.* + +// Always followed by one of: 0x13, 0x16, 0x17 +class ProgramInsulinCommand(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, nonce: Int, insulinProgramElements: List, private val checksum: Short, private val byte9: Byte, private val byte10And11: Short, private val byte12And13: Short, private val deliveryType: DeliveryType) : NonceEnabledCommand(CommandType.PROGRAM_INSULIN, uniqueId, sequenceNumber, multiCommandFlag, nonce) { + + private val insulinProgramElements: List = ArrayList(insulinProgramElements) + + fun getLength(): Short = (insulinProgramElements.size * 2 + 14).toShort() + + fun getBodyLength(): Byte = (insulinProgramElements.size * 2 + 12).toByte() + + enum class DeliveryType(private val value: Byte) { + BASAL(0x00.toByte()), TEMP_BASAL(0x01.toByte()), BOLUS(0x02.toByte()); + + fun getValue(): Byte { + return value + } + } + + fun calculateChecksum(bytes: ByteArray): Short { + var sum: Short = 0 + for (b in bytes) { + sum = ((b.toInt() and 0xff) + sum).toShort() // TODO Adrian: int conversion ok? + } + return sum + } + + override val encoded: ByteArray + get() { + val buffer = ByteBuffer.allocate(getLength().toInt()) // + .put(commandType.value) // + .put(getBodyLength()) // + .putInt(nonce) // + .put(deliveryType.getValue()) // + .putShort(checksum) // + .put(byte9) // BASAL: currentSlot // BOLUS: number of ShortInsulinProgramElements + .putShort(byte10And11) // BASAL: remainingEighthSecondsInCurrentSlot // BOLUS: immediate pulses multiplied by delay between pulses in eighth seconds + .putShort(byte12And13) // BASAL: remainingPulsesInCurrentSlot // BOLUS: immediate pulses + for (element in insulinProgramElements) { + buffer.put(element.encoded) + } + return buffer.array() + } + + override fun toString(): String { + return "ProgramInsulinCommand{" + + "insulinProgramElements=" + insulinProgramElements + + ", checksum=" + checksum + + ", byte9=" + byte9 + + ", byte10And11=" + byte10And11 + + ", byte12And13=" + byte12And13 + + ", deliveryType=" + deliveryType + + ", nonce=" + nonce + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.java deleted file mode 100644 index 9d4f1f547a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.java +++ /dev/null @@ -1,123 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramTempBasalUtil; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder; - -// NOT SUPPORTED: percentage temp basal -public final class ProgramTempBasalCommand extends HeaderEnabledCommand { - private final ProgramInsulinCommand interlockCommand; - private final ProgramReminder programReminder; - private final List insulinProgramElements; - - protected ProgramTempBasalCommand(ProgramInsulinCommand interlockCommand, int uniqueId, short sequenceNumber, boolean multiCommandFlag, - ProgramReminder programReminder, List insulinProgramElements) { - super(CommandType.PROGRAM_TEMP_BASAL, uniqueId, sequenceNumber, multiCommandFlag); - this.interlockCommand = interlockCommand; - this.programReminder = programReminder; - this.insulinProgramElements = new ArrayList<>(insulinProgramElements); - } - - public byte getBodyLength() { - return (byte) (insulinProgramElements.size() * 6 + 8); - } - - public short getLength() { - return (short) (getBodyLength() + 2); - } - - @Override public byte[] getEncoded() { - BasalInsulinProgramElement firstProgramElement = insulinProgramElements.get(0); - - short remainingTenthPulsesInFirstElement; - int delayUntilNextTenthPulseInUsec; - - if (firstProgramElement.getTotalTenthPulses() == 0) { - remainingTenthPulsesInFirstElement = firstProgramElement.getNumberOfSlots(); - delayUntilNextTenthPulseInUsec = ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT; - } else { - remainingTenthPulsesInFirstElement = firstProgramElement.getTotalTenthPulses(); - delayUntilNextTenthPulseInUsec = (int) ((long) firstProgramElement.getNumberOfSlots() * 1_800.0d / remainingTenthPulsesInFirstElement * 1_000_000); - } - - ByteBuffer buffer = ByteBuffer.allocate(getLength()) // - .put(commandType.getValue()) // - .put(getBodyLength()) // - .put(programReminder.getEncoded()) // - .put((byte) 0x00) // Current slot index - .putShort(remainingTenthPulsesInFirstElement) // - .putInt(delayUntilNextTenthPulseInUsec); - - for (BasalInsulinProgramElement element : insulinProgramElements) { - buffer.put(element.getEncoded()); - } - - byte[] tempBasalCommand = buffer.array(); - byte[] interlockCommand = this.interlockCommand.getEncoded(); - byte[] header = encodeHeader(uniqueId, sequenceNumber, (short) (tempBasalCommand.length + interlockCommand.length), multiCommandFlag); - - return appendCrc(ByteBuffer.allocate(header.length + interlockCommand.length + tempBasalCommand.length) // - .put(header) // - .put(interlockCommand) // - .put(tempBasalCommand) // - .array()); - } - - public static class Builder extends NonceEnabledCommandBuilder { - private ProgramReminder programReminder; - private Double rateInUnitsPerHour; - private Short durationInMinutes; - - public Builder setProgramReminder(ProgramReminder programReminder) { - this.programReminder = programReminder; - return this; - } - - public Builder setRateInUnitsPerHour(double rateInUnitsPerHour) { - this.rateInUnitsPerHour = rateInUnitsPerHour; - return this; - } - - public Builder setDurationInMinutes(short durationInMinutes) { - if (durationInMinutes % 30 != 0) { - throw new IllegalArgumentException("durationInMinutes must be dividable by 30"); - } - this.durationInMinutes = durationInMinutes; - return this; - } - - @Override protected ProgramTempBasalCommand buildCommand() { - if (programReminder == null) { - throw new IllegalArgumentException("programReminder can not be null"); - } - if (rateInUnitsPerHour == null) { - throw new IllegalArgumentException("rateInUnitsPerHour can not be null"); - } - if (durationInMinutes == null) { - throw new IllegalArgumentException("durationInMinutes can not be null"); - } - - byte durationInSlots = (byte) (durationInMinutes / 30); - short[] pulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToPulsesPerSlot(durationInSlots, rateInUnitsPerHour); - short[] tenthPulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToTenthPulsesPerSlot(durationInSlots, rateInUnitsPerHour); - - List shortInsulinProgramElements = ProgramTempBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot); - List insulinProgramElements = ProgramTempBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot); - - ProgramInsulinCommand interlockCommand = new ProgramInsulinCommand(uniqueId, sequenceNumber, multiCommandFlag, nonce, shortInsulinProgramElements, - ProgramTempBasalUtil.calculateChecksum(durationInSlots, pulsesPerSlot[0], pulsesPerSlot), durationInSlots, - (short) 0x3840, pulsesPerSlot[0], ProgramInsulinCommand.DeliveryType.TEMP_BASAL); - - return new ProgramTempBasalCommand(interlockCommand, uniqueId, sequenceNumber, multiCommandFlag, programReminder, insulinProgramElements); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt new file mode 100644 index 0000000000..601bf8eb2f --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -0,0 +1,94 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramTempBasalUtil +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import java.nio.ByteBuffer +import java.util.* + +// NOT SUPPORTED: percentage temp basal +class ProgramTempBasalCommand protected constructor(private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, + private val programReminder: ProgramReminder, insulinProgramElements: List) : HeaderEnabledCommand(CommandType.PROGRAM_TEMP_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { + + private val insulinProgramElements: List + fun getBodyLength(): Byte = (insulinProgramElements.size * 6 + 8).toByte() + + fun getLength(): Short = (getBodyLength() + 2).toShort() + + class Builder : NonceEnabledCommandBuilder() { + + private var programReminder: ProgramReminder? = null + private var rateInUnitsPerHour: Double? = null + private var durationInMinutes: Short? = null + fun setProgramReminder(programReminder: ProgramReminder?): Builder { + this.programReminder = programReminder + return this + } + + fun setRateInUnitsPerHour(rateInUnitsPerHour: Double): Builder { + this.rateInUnitsPerHour = rateInUnitsPerHour + return this + } + + fun setDurationInMinutes(durationInMinutes: Short): Builder { + require(durationInMinutes % 30 == 0) { "durationInMinutes must be dividable by 30" } + this.durationInMinutes = durationInMinutes + return this + } + + override fun buildCommand(): ProgramTempBasalCommand { + requireNotNull(programReminder) { "programReminder can not be null" } + requireNotNull(rateInUnitsPerHour) { "rateInUnitsPerHour can not be null" } + requireNotNull(durationInMinutes) { "durationInMinutes can not be null" } + val durationInSlots = (durationInMinutes!! / 30).toByte() + val pulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToPulsesPerSlot(durationInSlots, rateInUnitsPerHour!!) + val tenthPulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToTenthPulsesPerSlot(durationInSlots.toInt(), rateInUnitsPerHour!!) + val shortInsulinProgramElements = ProgramTempBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) + val insulinProgramElements = ProgramTempBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) + val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, shortInsulinProgramElements, + ProgramTempBasalUtil.calculateChecksum(durationInSlots, pulsesPerSlot!![0], pulsesPerSlot), durationInSlots, + 0x3840.toShort(), pulsesPerSlot[0], ProgramInsulinCommand.DeliveryType.TEMP_BASAL) + return ProgramTempBasalCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, programReminder!!, insulinProgramElements) + } + } + + init { + this.insulinProgramElements = ArrayList(insulinProgramElements) + } + + override val encoded: ByteArray + get() { + val firstProgramElement = insulinProgramElements[0] + val remainingTenthPulsesInFirstElement: Short + val delayUntilNextTenthPulseInUsec: Int + if (firstProgramElement.totalTenthPulses.toInt() == 0) { + remainingTenthPulsesInFirstElement = firstProgramElement.numberOfSlots.toShort() + delayUntilNextTenthPulseInUsec = ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT + } else { + remainingTenthPulsesInFirstElement = firstProgramElement.totalTenthPulses + delayUntilNextTenthPulseInUsec = (firstProgramElement.numberOfSlots.toLong() * 1800.0 / remainingTenthPulsesInFirstElement * 1000000).toInt() + } + val buffer = ByteBuffer.allocate(getLength().toInt()) // + .put(commandType.value) // + .put(getBodyLength()) // + .put(programReminder.encoded) // + .put(0x00.toByte()) // Current slot index + .putShort(remainingTenthPulsesInFirstElement) // + .putInt(delayUntilNextTenthPulseInUsec) + for (element in insulinProgramElements) { + buffer.put(element.encoded) + } + val tempBasalCommand = buffer.array() + val interlockCommand = interlockCommand.encoded + val header: ByteArray = HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + return HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) // + .put(header) // + .put(interlockCommand) // + .put(tempBasalCommand) // + .array()) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.java deleted file mode 100644 index d43a5fb4be..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.java +++ /dev/null @@ -1,99 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.Calendar; -import java.util.Date; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder; - -public final class SetUniqueIdCommand extends HeaderEnabledCommand { - private static final int DEFAULT_UNIQUE_ID = -1; - private static final short LENGTH = 21; - private static final byte BODY_LENGTH = 19; - - private final int lotNumber; - private final int podSequenceNumber; - private final Date initializationTime; - - SetUniqueIdCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag, int lotNumber, int podSequenceNumber, Date initializationTime) { - super(CommandType.SET_UNIQUE_ID, uniqueId, sequenceNumber, multiCommandFlag); - this.lotNumber = lotNumber; - this.podSequenceNumber = podSequenceNumber; - this.initializationTime = initializationTime; - } - - @Override public byte[] getEncoded() { - return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.getValue()) // - .put(BODY_LENGTH) // - .putInt(uniqueId) // - .put((byte) 0x14) // FIXME ?? - .put((byte) 0x04) // FIXME ?? - .put(encodeInitializationTime(initializationTime)) // - .putInt(lotNumber) // - .putInt(podSequenceNumber) // - .array()); - } - - private static byte[] encodeInitializationTime(Date date) { - Calendar instance = Calendar.getInstance(); - instance.setTime(date); - - return new byte[]{ // - (byte) (instance.get(Calendar.MONTH) + 1), // - (byte) instance.get(Calendar.DATE), // - (byte) (instance.get(Calendar.YEAR) % 100), // - (byte) instance.get(Calendar.HOUR_OF_DAY), // - (byte) instance.get(Calendar.MINUTE) // - }; - } - - @Override public String toString() { - return "SetUniqueIdCommand{" + - "lotNumber=" + lotNumber + - ", podSequenceNumber=" + podSequenceNumber + - ", initializationTime=" + initializationTime + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public static final class Builder extends HeaderEnabledCommandBuilder { - private Integer lotNumber; - private Integer podSequenceNumber; - private Date initializationTime; - - public Builder setLotNumber(int lotNumber) { - this.lotNumber = lotNumber; - return this; - } - - public Builder setPodSequenceNumber(int podSequenceNumber) { - this.podSequenceNumber = podSequenceNumber; - return this; - } - - public Builder setInitializationTime(Date initializationTime) { - this.initializationTime = initializationTime; - return this; - } - - @Override protected final SetUniqueIdCommand buildCommand() { - if (lotNumber == null) { - throw new IllegalArgumentException("lotNumber can not be null"); - } - if (podSequenceNumber == null) { - throw new IllegalArgumentException("podSequenceNumber can not be null"); - } - if (initializationTime == null) { - throw new IllegalArgumentException("initializationTime can not be null"); - } - return new SetUniqueIdCommand(uniqueId, sequenceNumber, multiCommandFlag, lotNumber, podSequenceNumber, initializationTime); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt new file mode 100644 index 0000000000..7772ecec53 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -0,0 +1,91 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder +import java.nio.ByteBuffer +import java.util.* + +class SetUniqueIdCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val lotNumber: Int, private val podSequenceNumber: Int, private val initializationTime: Date) : HeaderEnabledCommand(CommandType.SET_UNIQUE_ID, uniqueId, sequenceNumber, multiCommandFlag) { + + // + // + // + // + // + // FIXME ?? + // FIXME ?? + // + // + // + override val encoded: ByteArray + get() = HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // + .put(HeaderEnabledCommand.Companion.encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(uniqueId) // + .put(0x14.toByte()) // FIXME ?? + .put(0x04.toByte()) // FIXME ?? + .put(encodeInitializationTime(initializationTime)) // + .putInt(lotNumber) // + .putInt(podSequenceNumber) // + .array()) + + override fun toString(): String { + return "SetUniqueIdCommand{" + + "lotNumber=" + lotNumber + + ", podSequenceNumber=" + podSequenceNumber + + ", initializationTime=" + initializationTime + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + class Builder : HeaderEnabledCommandBuilder() { + + private var lotNumber: Int? = null + private var podSequenceNumber: Int? = null + private var initializationTime: Date? = null + fun setLotNumber(lotNumber: Int): Builder { + this.lotNumber = lotNumber + return this + } + + fun setPodSequenceNumber(podSequenceNumber: Int): Builder { + this.podSequenceNumber = podSequenceNumber + return this + } + + fun setInitializationTime(initializationTime: Date?): Builder { + this.initializationTime = initializationTime + return this + } + + override fun buildCommand(): SetUniqueIdCommand { + requireNotNull(lotNumber) { "lotNumber can not be null" } + requireNotNull(podSequenceNumber) { "podSequenceNumber can not be null" } + requireNotNull(initializationTime) { "initializationTime can not be null" } + return SetUniqueIdCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, lotNumber!!, podSequenceNumber!!, initializationTime!!) + } + } + + companion object { + + private const val DEFAULT_UNIQUE_ID = -1 + private const val LENGTH: Short = 21 + private const val BODY_LENGTH: Byte = 19 + private fun encodeInitializationTime(date: Date): ByteArray { + val instance = Calendar.getInstance() + instance.time = date + return byteArrayOf( // + (instance[Calendar.MONTH] + 1).toByte(), // + instance[Calendar.DATE].toByte(), // + (instance[Calendar.YEAR] % 100).toByte(), // + instance[Calendar.HOUR_OF_DAY].toByte(), // + instance[Calendar.MINUTE].toByte() // + ) + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.java deleted file mode 100644 index 77341967fa..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.java +++ /dev/null @@ -1,133 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.BitSet; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable; - -public final class SilenceAlertsCommand extends NonceEnabledCommand { - private static final short LENGTH = (short) 7; - private static final byte BODY_LENGTH = (byte) 5; - - private final SilenceAlertCommandParameters parameters; - - SilenceAlertsCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag, SilenceAlertCommandParameters parameters, int nonce) { - super(CommandType.SILENCE_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce); - this.parameters = parameters; - } - - @Override public byte[] getEncoded() { - return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.getValue()) // - .put(BODY_LENGTH) // - .putInt(nonce) // - .put(parameters.getEncoded()) // - .array()); - } - - @Override public String toString() { - return "SilenceAlertsCommand{" + - "parameters=" + parameters + - ", nonce=" + nonce + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - private static final class SilenceAlertCommandParameters implements Encodable { - private final boolean silenceAutoOffAlert; - private final boolean silenceMultiCommandAlert; - private final boolean silenceExpirationImminentAlert; - private final boolean silenceUserSetExpirationAlert; - private final boolean silenceLowReservoirAlert; - private final boolean silenceSuspendInProgressAlert; - private final boolean silenceSuspendEndedAlert; - private final boolean silencePodExpirationAlert; - - private SilenceAlertCommandParameters(boolean silenceAutoOffAlert, boolean silenceMultiCommandAlert, boolean silenceExpirationImminentAlert, boolean silenceUserSetExpirationAlert, boolean silenceLowReservoirAlert, boolean silenceSuspendInProgressAlert, boolean silenceSuspendEndedAlert, boolean silencePodExpirationAlert) { - this.silenceAutoOffAlert = silenceAutoOffAlert; - this.silenceMultiCommandAlert = silenceMultiCommandAlert; - this.silenceExpirationImminentAlert = silenceExpirationImminentAlert; - this.silenceUserSetExpirationAlert = silenceUserSetExpirationAlert; - this.silenceLowReservoirAlert = silenceLowReservoirAlert; - this.silenceSuspendInProgressAlert = silenceSuspendInProgressAlert; - this.silenceSuspendEndedAlert = silenceSuspendEndedAlert; - this.silencePodExpirationAlert = silencePodExpirationAlert; - } - - @Override - public byte[] getEncoded() { - BitSet bitSet = new BitSet(8); - bitSet.set(0, this.silenceAutoOffAlert); - bitSet.set(1, this.silenceMultiCommandAlert); - bitSet.set(2, this.silenceExpirationImminentAlert); - bitSet.set(3, this.silenceUserSetExpirationAlert); - bitSet.set(4, this.silenceLowReservoirAlert); - bitSet.set(5, this.silenceSuspendInProgressAlert); - bitSet.set(6, this.silenceSuspendEndedAlert); - bitSet.set(7, this.silencePodExpirationAlert); - return bitSet.toByteArray(); - } - } - - public static class Builder extends NonceEnabledCommandBuilder { - private boolean silenceAutoOffAlert; - private boolean silenceMultiCommandAlert; - private boolean silenceExpirationImminentAlert; - private boolean silenceUserSetExpirationAlert; - private boolean silenceLowReservoirAlert; - private boolean silenceSuspendInProgressAlert; - private boolean silenceSuspendEndedAlert; - private boolean silencePodExpirationAlert; - - public Builder setSilenceAutoOffAlert(boolean silenceAutoOffAlert) { - this.silenceAutoOffAlert = silenceAutoOffAlert; - return this; - } - - public Builder setSilenceMultiCommandAlert(boolean silenceMultiCommandAlert) { - this.silenceMultiCommandAlert = silenceMultiCommandAlert; - return this; - } - - public Builder setSilenceExpirationImminentAlert(boolean silenceExpirationImminentAlert) { - this.silenceExpirationImminentAlert = silenceExpirationImminentAlert; - return this; - } - - public Builder setSilenceUserSetExpirationAlert(boolean silenceUserSetExpirationAlert) { - this.silenceUserSetExpirationAlert = silenceUserSetExpirationAlert; - return this; - } - - public Builder setSilenceLowReservoirAlert(boolean silenceLowReservoirAlert) { - this.silenceLowReservoirAlert = silenceLowReservoirAlert; - return this; - } - - public Builder setSilenceSuspendInProgressAlert(boolean silenceSuspendInProgressAlert) { - this.silenceSuspendInProgressAlert = silenceSuspendInProgressAlert; - return this; - } - - public Builder setSilenceSuspendEndedAlert(boolean silenceSuspendEndedAlert) { - this.silenceSuspendEndedAlert = silenceSuspendEndedAlert; - return this; - } - - public Builder setSilencePodExpirationAlert(boolean silencePodExpirationAlert) { - this.silencePodExpirationAlert = silencePodExpirationAlert; - return this; - } - - @Override protected final SilenceAlertsCommand buildCommand() { - return new SilenceAlertsCommand(uniqueId, sequenceNumber, multiCommandFlag, new SilenceAlertCommandParameters(silenceAutoOffAlert, silenceMultiCommandAlert, silenceExpirationImminentAlert, silenceUserSetExpirationAlert, silenceLowReservoirAlert, silenceSuspendInProgressAlert, silenceSuspendEndedAlert, silencePodExpirationAlert), nonce); - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt new file mode 100644 index 0000000000..78149ba1c4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -0,0 +1,111 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import java.nio.ByteBuffer +import java.util.* + +class SilenceAlertsCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val parameters: SilenceAlertCommandParameters, nonce: Int) : NonceEnabledCommand(CommandType.SILENCE_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { + + override val encoded: ByteArray + get() = + HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // + .put(HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(nonce) // + .put(parameters.encoded) // + .array()) + + override fun toString(): String { + return "SilenceAlertsCommand{" + + "parameters=" + parameters + + ", nonce=" + nonce + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + class SilenceAlertCommandParameters(private val silenceAutoOffAlert: Boolean, private val silenceMultiCommandAlert: Boolean, private val silenceExpirationImminentAlert: Boolean, private val silenceUserSetExpirationAlert: Boolean, private val silenceLowReservoirAlert: Boolean, private val silenceSuspendInProgressAlert: Boolean, private val silenceSuspendEndedAlert: Boolean, private val silencePodExpirationAlert: Boolean) : Encodable { + + override val encoded: ByteArray + get() { + val bitSet = BitSet(8) + bitSet[0] = silenceAutoOffAlert + bitSet[1] = silenceMultiCommandAlert + bitSet[2] = silenceExpirationImminentAlert + bitSet[3] = silenceUserSetExpirationAlert + bitSet[4] = silenceLowReservoirAlert + bitSet[5] = silenceSuspendInProgressAlert + bitSet[6] = silenceSuspendEndedAlert + bitSet[7] = silencePodExpirationAlert + return bitSet.toByteArray() + } + } + + class Builder : NonceEnabledCommandBuilder() { + + private var silenceAutoOffAlert = false + private var silenceMultiCommandAlert = false + private var silenceExpirationImminentAlert = false + private var silenceUserSetExpirationAlert = false + private var silenceLowReservoirAlert = false + private var silenceSuspendInProgressAlert = false + private var silenceSuspendEndedAlert = false + private var silencePodExpirationAlert = false + fun setSilenceAutoOffAlert(silenceAutoOffAlert: Boolean): Builder { + this.silenceAutoOffAlert = silenceAutoOffAlert + return this + } + + fun setSilenceMultiCommandAlert(silenceMultiCommandAlert: Boolean): Builder { + this.silenceMultiCommandAlert = silenceMultiCommandAlert + return this + } + + fun setSilenceExpirationImminentAlert(silenceExpirationImminentAlert: Boolean): Builder { + this.silenceExpirationImminentAlert = silenceExpirationImminentAlert + return this + } + + fun setSilenceUserSetExpirationAlert(silenceUserSetExpirationAlert: Boolean): Builder { + this.silenceUserSetExpirationAlert = silenceUserSetExpirationAlert + return this + } + + fun setSilenceLowReservoirAlert(silenceLowReservoirAlert: Boolean): Builder { + this.silenceLowReservoirAlert = silenceLowReservoirAlert + return this + } + + fun setSilenceSuspendInProgressAlert(silenceSuspendInProgressAlert: Boolean): Builder { + this.silenceSuspendInProgressAlert = silenceSuspendInProgressAlert + return this + } + + fun setSilenceSuspendEndedAlert(silenceSuspendEndedAlert: Boolean): Builder { + this.silenceSuspendEndedAlert = silenceSuspendEndedAlert + return this + } + + fun setSilencePodExpirationAlert(silencePodExpirationAlert: Boolean): Builder { + this.silencePodExpirationAlert = silencePodExpirationAlert + return this + } + + override fun buildCommand(): SilenceAlertsCommand { + return SilenceAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, SilenceAlertCommandParameters(silenceAutoOffAlert, silenceMultiCommandAlert, silenceExpirationImminentAlert, silenceUserSetExpirationAlert, silenceLowReservoirAlert, silenceSuspendInProgressAlert, silenceSuspendEndedAlert, silencePodExpirationAlert), nonce!!) + } + } + + companion object { + + private const val LENGTH = 7.toShort() + private const val BODY_LENGTH = 5.toByte() + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.java deleted file mode 100644 index 9c539c3b4a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.java +++ /dev/null @@ -1,97 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import java.nio.ByteBuffer; -import java.util.BitSet; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable; - -public final class StopDeliveryCommand extends NonceEnabledCommand { - private static final short LENGTH = 7; - private static final byte BODY_LENGTH = 5; - - private final DeliveryType deliveryType; - private final BeepType beepType; - - StopDeliveryCommand(int uniqueId, short sequenceNumber, boolean multiCommandFlag, DeliveryType deliveryType, BeepType beepType, int nonce) { - super(CommandType.STOP_DELIVERY, uniqueId, sequenceNumber, multiCommandFlag, nonce); - this.deliveryType = deliveryType; - this.beepType = beepType; - } - - @Override public byte[] getEncoded() { - return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.getValue()) // - .put(BODY_LENGTH) // - .putInt(nonce) // - .put((byte) ((beepType.getValue() << 4) | deliveryType.getEncoded()[0])) // - .array()); - } - - @Override public String toString() { - return "StopDeliveryCommand{" + - "deliveryType=" + deliveryType + - ", beepType=" + beepType + - ", nonce=" + nonce + - ", commandType=" + commandType + - ", uniqueId=" + uniqueId + - ", sequenceNumber=" + sequenceNumber + - ", multiCommandFlag=" + multiCommandFlag + - '}'; - } - - public enum DeliveryType implements Encodable { - BASAL(true, false, false), - TEMP_BASAL(false, true, false), - BOLUS(false, false, true), - ALL(true, true, true); - - private final boolean basal; - private final boolean tempBasal; - private final boolean bolus; - - DeliveryType(boolean basal, boolean tempBasal, boolean bolus) { - this.basal = basal; - this.tempBasal = tempBasal; - this.bolus = bolus; - } - - @Override public byte[] getEncoded() { - BitSet bitSet = new BitSet(8); - bitSet.set(0, this.basal); - bitSet.set(1, this.tempBasal); - bitSet.set(2, this.bolus); - return bitSet.toByteArray(); - } - } - - public static final class Builder extends NonceEnabledCommandBuilder { - private DeliveryType deliveryType; - private BeepType beepType = BeepType.LONG_SINGLE_BEEP; - - public Builder setDeliveryType(DeliveryType deliveryType) { - this.deliveryType = deliveryType; - return this; - } - - public Builder setBeepType(BeepType beepType) { - this.beepType = beepType; - return this; - } - - @Override protected final StopDeliveryCommand buildCommand() { - if (deliveryType == null) { - throw new IllegalArgumentException("deliveryType can not be null"); - } - if (beepType == null) { - throw new IllegalArgumentException("beepType can not be null"); - } - return new StopDeliveryCommand(uniqueId, sequenceNumber, multiCommandFlag, deliveryType, beepType, nonce); - } - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt new file mode 100644 index 0000000000..95828da199 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -0,0 +1,76 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import java.nio.ByteBuffer +import java.util.* + +class StopDeliveryCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val deliveryType: DeliveryType, private val beepType: BeepType, nonce: Int) : NonceEnabledCommand(CommandType.STOP_DELIVERY, uniqueId, sequenceNumber, multiCommandFlag, nonce) { + + override val encoded: ByteArray + get() { + return HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // + .put(HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(nonce) // + .put((beepType.value.toInt() shl 4 or deliveryType.encoded[0].toInt()).toByte()) // TODO bitstuff + .array()) + } + + override fun toString(): String { + return "StopDeliveryCommand{" + + "deliveryType=" + deliveryType + + ", beepType=" + beepType + + ", nonce=" + nonce + + ", commandType=" + commandType + + ", uniqueId=" + uniqueId + + ", sequenceNumber=" + sequenceNumber + + ", multiCommandFlag=" + multiCommandFlag + + '}' + } + + enum class DeliveryType(private val basal: Boolean, private val tempBasal: Boolean, private val bolus: Boolean) : Encodable { + BASAL(true, false, false), TEMP_BASAL(false, true, false), BOLUS(false, false, true), ALL(true, true, true); + + override val encoded: ByteArray + get() { + val bitSet = BitSet(8) + bitSet[0] = basal + bitSet[1] = tempBasal + bitSet[2] = bolus + return bitSet.toByteArray() + } + } + + class Builder : NonceEnabledCommandBuilder() { + + private var deliveryType: DeliveryType? = null + private var beepType: BeepType? = BeepType.LONG_SINGLE_BEEP + fun setDeliveryType(deliveryType: DeliveryType?): Builder { + this.deliveryType = deliveryType + return this + } + + fun setBeepType(beepType: BeepType?): Builder { + this.beepType = beepType + return this + } + + override fun buildCommand(): StopDeliveryCommand { + requireNotNull(deliveryType) { "deliveryType can not be null" } + requireNotNull(beepType) { "beepType can not be null" } + return StopDeliveryCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, deliveryType!!, beepType!!, nonce!!) + } + } + + companion object { + + private const val LENGTH: Short = 7 + private const val BODY_LENGTH: Byte = 5 + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.java deleted file mode 100644 index 27f311c394..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable; - -public interface Command extends Encodable { - CommandType getCommandType(); -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt similarity index 50% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt index 04a5c39864..4675d5199b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt @@ -1,6 +1,8 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable -public interface ShortInsulinProgramElement extends Encodable { -} +interface Command : Encodable { + + val commandType: CommandType +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.java deleted file mode 100644 index bd785e573d..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.java +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base; - -public enum CommandType { - SET_UNIQUE_ID((byte) 0x03), - GET_VERSION((byte) 0x07), - GET_STATUS((byte) 0x0e), - SILENCE_ALERTS((byte) 0x11), - PROGRAM_BASAL((byte) 0x13), // Always preceded by 0x1a - PROGRAM_TEMP_BASAL((byte) 0x16), // Always preceded by 0x1a - PROGRAM_BOLUS((byte) 0x17), // Always preceded by 0x1a - PROGRAM_ALERTS((byte) 0x19), - PROGRAM_INSULIN((byte) 0x1a), // Always followed by one of: 0x13, 0x16, 0x17 - DEACTIVATE((byte) 0x1c), - PROGRAM_BEEPS((byte) 0x1e), - STOP_DELIVERY((byte) 0x1f); - - byte value; - - CommandType(byte value) { - this.value = value; - } - - public byte getValue() { - return value; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt new file mode 100644 index 0000000000..c3715b32cf --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base + +enum class CommandType(var value: Byte) { + SET_UNIQUE_ID(0x03.toByte()), + GET_VERSION(0x07.toByte()), + GET_STATUS(0x0e.toByte()), + SILENCE_ALERTS(0x11.toByte()), + PROGRAM_BASAL(0x13.toByte()), // Always preceded by 0x1a + PROGRAM_TEMP_BASAL(0x16.toByte()), // Always preceded by 0x1a + PROGRAM_BOLUS(0x17.toByte()), // Always preceded by 0x1a + PROGRAM_ALERTS(0x19.toByte()), + PROGRAM_INSULIN(0x1a.toByte()), // Always followed by one of: 0x13, 0x16, 0x17 + DEACTIVATE(0x1c.toByte()), + PROGRAM_BEEPS(0x1e.toByte()), + STOP_DELIVERY(0x1f.toByte()); +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.java deleted file mode 100644 index 0a4cc03007..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.java +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base; - -import java.nio.ByteBuffer; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil; - -public abstract class HeaderEnabledCommand implements Command { - protected static final short HEADER_LENGTH = 6; - - protected final CommandType commandType; - protected final int uniqueId; - protected final short sequenceNumber; - protected final boolean multiCommandFlag; - - protected HeaderEnabledCommand(CommandType commandType, int uniqueId, short sequenceNumber, boolean multiCommandFlag) { - this.commandType = commandType; - this.uniqueId = uniqueId; - this.sequenceNumber = sequenceNumber; - this.multiCommandFlag = multiCommandFlag; - } - - @Override public CommandType getCommandType() { - return commandType; - } - - protected static byte[] appendCrc(byte[] command) { - return ByteBuffer.allocate(command.length + 2) // - .put(command) // - .putShort(MessageUtil.createCrc(command)) // - .array(); - } - - protected static byte[] encodeHeader(int uniqueId, short sequenceNumber, short length, boolean multiCommandFlag) { - return ByteBuffer.allocate(6) // - .putInt(uniqueId) // - .putShort((short) (((sequenceNumber & 0x0f) << 10) | length | ((multiCommandFlag ? 1 : 0) << 15))) // - .array(); - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.kt new file mode 100644 index 0000000000..10e91285a3 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/HeaderEnabledCommand.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil +import java.nio.ByteBuffer + +abstract class HeaderEnabledCommand protected constructor( + override val commandType: CommandType, + protected val uniqueId: Int, + protected val sequenceNumber: Short, + protected val multiCommandFlag: Boolean +) : Command { + + companion object { + + internal fun appendCrc(command: ByteArray): ByteArray = + ByteBuffer.allocate(command.size + 2) // + .put(command) // + .putShort(MessageUtil.createCrc(command)) // + .array() + + internal fun encodeHeader(uniqueId: Int, sequenceNumber: Short, length: Short, multiCommandFlag: Boolean): ByteArray = + ByteBuffer.allocate(6) // + .putInt(uniqueId) // + .putShort((sequenceNumber.toInt() and 0x0f shl 10 or length.toInt() or ((if (multiCommandFlag) 1 else 0) shl 15)).toShort()) // + .array() + + internal const val HEADER_LENGTH: Short = 6 + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.java deleted file mode 100644 index 744f7eb1e9..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base; - -public abstract class NonceEnabledCommand extends HeaderEnabledCommand { - protected final int nonce; - - protected NonceEnabledCommand(CommandType commandType, int uniqueId, short sequenceNumber, boolean multiCommandFlag, int nonce) { - super(commandType, uniqueId, sequenceNumber, multiCommandFlag); - this.nonce = nonce; - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt new file mode 100644 index 0000000000..ef905673e9 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base + +abstract class NonceEnabledCommand protected constructor( + commandType: CommandType, + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + protected val nonce: Int +) : HeaderEnabledCommand(commandType, uniqueId, sequenceNumber, multiCommandFlag) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt similarity index 50% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt index 3b4ca66ca0..1798f08ca8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt @@ -1,7 +1,8 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command; +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command -public interface CommandBuilder { - R build(); -} +interface CommandBuilder { + + fun build(): R +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.java deleted file mode 100644 index 30dc425cb8..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.java +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command; - -public abstract class HeaderEnabledCommandBuilder, R extends Command> implements CommandBuilder { - protected Integer uniqueId; - protected Short sequenceNumber; - protected boolean multiCommandFlag = false; - - public R build() { - if (uniqueId == null) { - throw new IllegalArgumentException("uniqueId can not be null"); - } - if (sequenceNumber == null) { - throw new IllegalArgumentException("sequenceNumber can not be null"); - } - return buildCommand(); - } - - public final T setUniqueId(int uniqueId) { - this.uniqueId = uniqueId; - return (T) this; - } - - public final T setSequenceNumber(short sequenceNumber) { - this.sequenceNumber = sequenceNumber; - return (T) this; - } - - public final T setMultiCommandFlag(boolean multiCommandFlag) { - this.multiCommandFlag = multiCommandFlag; - return (T) this; - } - - protected abstract R buildCommand(); -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt new file mode 100644 index 0000000000..21969aa5f5 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command + +abstract class HeaderEnabledCommandBuilder, R : Command> : CommandBuilder { + + protected var uniqueId: Int? = null + protected var sequenceNumber: Short? = null + protected var multiCommandFlag = false + override fun build(): R { + requireNotNull(uniqueId) { "uniqueId can not be null" } + requireNotNull(sequenceNumber) { "sequenceNumber can not be null" } + return buildCommand() + } + + fun setUniqueId(uniqueId: Int): T { + this.uniqueId = uniqueId + return this as T + } + + fun setSequenceNumber(sequenceNumber: Short): T { + this.sequenceNumber = sequenceNumber + return this as T + } + + fun setMultiCommandFlag(multiCommandFlag: Boolean): T { + this.multiCommandFlag = multiCommandFlag + return this as T + } + + protected abstract fun buildCommand(): R +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.java deleted file mode 100644 index 806eda8965..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.java +++ /dev/null @@ -1,19 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command; - -public abstract class NonceEnabledCommandBuilder, R extends Command> extends HeaderEnabledCommandBuilder { - protected Integer nonce; - - public final R build() { - if (nonce == null) { - throw new IllegalArgumentException("nonce can not be null"); - } - return super.build(); - } - - public final T setNonce(int nonce) { - this.nonce = nonce; - return (T) this; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt new file mode 100644 index 0000000000..64bd7eb4e6 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command + +abstract class NonceEnabledCommandBuilder, R : Command> : HeaderEnabledCommandBuilder() { + + protected var nonce: Int? = null + override fun build(): R { + requireNotNull(nonce) { "nonce can not be null" } + return super.build() + } + + fun setNonce(nonce: Int): T { + this.nonce = nonce + return this as T + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.java deleted file mode 100644 index 4ddcc6347a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.java +++ /dev/null @@ -1,58 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; - -import java.nio.ByteBuffer; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable; - -import static info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT; - -public class BasalInsulinProgramElement implements Encodable { - private final byte startSlotIndex; - private final byte numberOfSlots; - private final short totalTenthPulses; - - public BasalInsulinProgramElement(byte startSlotIndex, byte numberOfSlots, short totalTenthPulses) { - this.startSlotIndex = startSlotIndex; - this.numberOfSlots = numberOfSlots; - this.totalTenthPulses = totalTenthPulses; - } - - @Override public byte[] getEncoded() { - return ByteBuffer.allocate(6) // - .putShort(totalTenthPulses) // - .putInt(totalTenthPulses == 0 ? Integer.MIN_VALUE | getDelayBetweenTenthPulsesInUsec() : getDelayBetweenTenthPulsesInUsec()) // - .array(); - } - - public byte getStartSlotIndex() { - return startSlotIndex; - } - - public byte getNumberOfSlots() { - return numberOfSlots; - } - - public short getDurationInSeconds() { - return (short) (numberOfSlots * 1_800); - } - - public short getTotalTenthPulses() { - return totalTenthPulses; - } - - public int getDelayBetweenTenthPulsesInUsec() { - if (totalTenthPulses == 0) { - return MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT; - } - return (int) (((long) MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT * numberOfSlots) / (double) totalTenthPulses); - } - - @Override public String toString() { - return "LongInsulinProgramElement{" + - "startSlotIndex=" + startSlotIndex + - ", numberOfSlots=" + numberOfSlots + - ", totalTenthPulses=" + totalTenthPulses + - ", delayBetweenTenthPulsesInUsec=" + getDelayBetweenTenthPulsesInUsec() + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt new file mode 100644 index 0000000000..7121b43a08 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import java.nio.ByteBuffer + +open class BasalInsulinProgramElement(val startSlotIndex: Byte, val numberOfSlots: Byte, val totalTenthPulses: Short) : Encodable { + + // + // + // + override val encoded: ByteArray + get() = ByteBuffer.allocate(6) // + .putShort(totalTenthPulses) // + .putInt(if (totalTenthPulses.toInt() == 0) Int.MIN_VALUE or delayBetweenTenthPulsesInUsec else delayBetweenTenthPulsesInUsec) // + .array() + val durationInSeconds: Short + get() = (numberOfSlots * 1800).toShort() + val delayBetweenTenthPulsesInUsec: Int + get() = if (totalTenthPulses.toInt() == 0) { + ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT + } else (ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT.toLong() * numberOfSlots / totalTenthPulses.toDouble()).toInt() + + override fun toString(): String { + return "LongInsulinProgramElement{" + + "startSlotIndex=" + startSlotIndex + + ", numberOfSlots=" + numberOfSlots + + ", totalTenthPulses=" + totalTenthPulses + + ", delayBetweenTenthPulsesInUsec=" + delayBetweenTenthPulsesInUsec + + '}' + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.java deleted file mode 100644 index 9a8983f8f3..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.java +++ /dev/null @@ -1,34 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; - -import java.nio.ByteBuffer; - -public class BasalShortInsulinProgramElement implements ShortInsulinProgramElement { - private final byte numberOfSlots; // 4 bits - private final short pulsesPerSlot; // 10 bits - private final boolean extraAlternatePulse; - - public BasalShortInsulinProgramElement(byte numberOfSlots, short pulsesPerSlot, boolean extraAlternatePulse) { - this.numberOfSlots = numberOfSlots; - this.pulsesPerSlot = pulsesPerSlot; - this.extraAlternatePulse = extraAlternatePulse; - } - - @Override public byte[] getEncoded() { - byte firstByte = (byte) ((((numberOfSlots - 1) & 0x0f) << 4) // - | ((extraAlternatePulse ? 1 : 0) << 3) // - | ((pulsesPerSlot >>> 8) & 0x03)); - - return ByteBuffer.allocate(2) // - .put(firstByte) // - .put((byte) (pulsesPerSlot & 0xff)) // - .array(); - } - - @Override public String toString() { - return "ShortInsulinProgramElement{" + - "numberOfSlotsMinusOne=" + numberOfSlots + - ", pulsesPerSlot=" + pulsesPerSlot + - ", extraAlternatePulse=" + extraAlternatePulse + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt new file mode 100644 index 0000000000..691c444ff2 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +import java.nio.ByteBuffer +import kotlin.experimental.and + +class BasalShortInsulinProgramElement(// 4 bits + private val numberOfSlots: Byte, // 10 bits + private val pulsesPerSlot: Short, // + private val extraAlternatePulse: Boolean) : ShortInsulinProgramElement { + + // + // + // + // + override val encoded: ByteArray + get() { + val firstByte = (numberOfSlots - 1 and 0x0f shl 4 // + or ((if (extraAlternatePulse) 1 else 0) shl 3) // + or (pulsesPerSlot.toInt() ushr 8 and 0x03)).toByte() + return ByteBuffer.allocate(2) // + .put(firstByte) // + .put((pulsesPerSlot and 0xff).toByte()) // + .array() + } + + override fun toString(): String { + return "ShortInsulinProgramElement{" + + "numberOfSlotsMinusOne=" + numberOfSlots + + ", pulsesPerSlot=" + pulsesPerSlot + + ", extraAlternatePulse=" + extraAlternatePulse + + '}' + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java deleted file mode 100644 index 0c23171639..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.java +++ /dev/null @@ -1,19 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; - -import java.nio.ByteBuffer; - -public class BolusShortInsulinProgramElement implements ShortInsulinProgramElement { - private short numberOfPulses; - - public BolusShortInsulinProgramElement(short numberOfPulses) { - this.numberOfPulses = numberOfPulses; - } - - public short getNumberOfPulses() { - return numberOfPulses; - } - - @Override public byte[] getEncoded() { - return ByteBuffer.allocate(2).putShort(numberOfPulses).array(); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt new file mode 100644 index 0000000000..65938313ed --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +import java.nio.ByteBuffer + +class BolusShortInsulinProgramElement(private val numberOfPulses: Short) : ShortInsulinProgramElement { + + override val encoded: ByteArray + get() = ByteBuffer.allocate(2).putShort(numberOfPulses).array() +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.java deleted file mode 100644 index fb7bcd3215..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.java +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; - -public class CurrentBasalInsulinProgramElement { - private final byte index; - private final int delayUntilNextTenthPulseInUsec; - private final short remainingTenthPulses; - - public CurrentBasalInsulinProgramElement(byte index, int delayUntilNextTenthPulseInUsec, short remainingTenthPulses) { - this.index = index; - this.delayUntilNextTenthPulseInUsec = delayUntilNextTenthPulseInUsec; - this.remainingTenthPulses = remainingTenthPulses; - } - - public byte getIndex() { - return index; - } - - public int getDelayUntilNextTenthPulseInUsec() { - return delayUntilNextTenthPulseInUsec; - } - - public short getRemainingTenthPulses() { - return remainingTenthPulses; - } - - @Override public String toString() { - return "CurrentLongInsulinProgramElement{" + - "index=" + index + - ", delayUntilNextTenthPulseInUsec=" + delayUntilNextTenthPulseInUsec + - ", remainingTenthPulses=" + remainingTenthPulses + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt new file mode 100644 index 0000000000..87fe2b083b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +class CurrentBasalInsulinProgramElement(val index: Byte, val delayUntilNextTenthPulseInUsec: Int, val remainingTenthPulses: Short) { + + override fun toString(): String = "CurrentLongInsulinProgramElement{" + + "index=" + index + + ", delayUntilNextTenthPulseInUsec=" + delayUntilNextTenthPulseInUsec + + ", remainingTenthPulses=" + remainingTenthPulses + + '}' +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.java deleted file mode 100644 index 1468370b01..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.java +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; - -public class CurrentSlot { - private final byte index; - private final short eighthSecondsRemaining; - private final short pulsesRemaining; - - public CurrentSlot(byte index, short eighthSecondsRemaining, short pulsesRemaining) { - this.index = index; - this.eighthSecondsRemaining = eighthSecondsRemaining; - this.pulsesRemaining = pulsesRemaining; - } - - public byte getIndex() { - return index; - } - - public short getEighthSecondsRemaining() { - return eighthSecondsRemaining; - } - - public short getPulsesRemaining() { - return pulsesRemaining; - } - - @Override public String toString() { - return "CurrentSlot{" + - "index=" + index + - ", eighthSecondsRemaining=" + eighthSecondsRemaining + - ", pulsesRemaining=" + pulsesRemaining + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt new file mode 100644 index 0000000000..d8667fe04c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +class CurrentSlot(val index: Byte, val eighthSecondsRemaining: Short, val pulsesRemaining: Short) { + + override fun toString(): String = "CurrentSlot{" + + "index=" + index + + ", eighthSecondsRemaining=" + eighthSecondsRemaining + + ", pulsesRemaining=" + pulsesRemaining + + '}' +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt new file mode 100644 index 0000000000..b5f01ec3df --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable + +interface ShortInsulinProgramElement : Encodable \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.java deleted file mode 100644 index b43b148ea3..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.java +++ /dev/null @@ -1,23 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program; - -import java.nio.ByteBuffer; - -public class TempBasalInsulinProgramElement extends BasalInsulinProgramElement { - public TempBasalInsulinProgramElement(byte startSlotIndex, byte numberOfSlots, short totalTenthPulses) { - super(startSlotIndex, numberOfSlots, totalTenthPulses); - } - - @Override public byte[] getEncoded() { - ByteBuffer buffer = ByteBuffer.allocate(6); - if (getTotalTenthPulses() == 0) { - int i = ((int) ((((double) getDurationInSeconds()) * 1_000_000.0d) / ((double) getNumberOfSlots()))) | Integer.MIN_VALUE; - buffer.putShort(getNumberOfSlots()) // - .putInt(i); - } else { - buffer.putShort(getTotalTenthPulses()) // - .putInt(getDelayBetweenTenthPulsesInUsec()); - } - return buffer.array(); - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt new file mode 100644 index 0000000000..fc22bef671 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program + +import java.nio.ByteBuffer + +class TempBasalInsulinProgramElement(startSlotIndex: Byte, numberOfSlots: Byte, totalTenthPulses: Short) : BasalInsulinProgramElement(startSlotIndex, numberOfSlots, totalTenthPulses) { + + // + // + override val encoded: ByteArray + get() { + val buffer = ByteBuffer.allocate(6) + if (totalTenthPulses.toInt() == 0) { + val i = (durationInSeconds.toDouble() * 1000000.0 / numberOfSlots.toDouble()).toInt() or Int.MIN_VALUE + buffer.putShort(numberOfSlots.toShort()) // + .putInt(i) + } else { + buffer.putShort(totalTenthPulses) // + .putInt(delayBetweenTenthPulsesInUsec) + } + return buffer.array() + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.java deleted file mode 100644 index 0c02799d02..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.java +++ /dev/null @@ -1,257 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalShortInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.CurrentBasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.CurrentSlot; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil; - -public final class ProgramBasalUtil { - public static final int MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT = 1_800_000_000; - - public static final byte NUMBER_OF_BASAL_SLOTS = 48; - public static final byte MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT = 16; - - private ProgramBasalUtil() { - } - - public interface BasalInsulinProgramElementFactory { - T create(byte startSlotIndex, byte numberOfSlots, short totalTenthPulses); - } - - public static List mapTenthPulsesPerSlotToLongInsulinProgramElements(short[] tenthPulsesPerSlot) { - return mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot, BasalInsulinProgramElement::new); - } - - public static List mapTenthPulsesPerSlotToLongInsulinProgramElements(short[] tenthPulsesPerSlot, BasalInsulinProgramElementFactory insulinProgramElementFactory) { - if (tenthPulsesPerSlot.length > NUMBER_OF_BASAL_SLOTS) { - throw new IllegalArgumentException("Basal program must contain at most 48 slots"); - } - - List elements = new ArrayList<>(); - long previousTenthPulsesPerSlot = 0; - byte numberOfSlotsInCurrentElement = 0; - byte startSlotIndex = 0; - - for (int i = 0; i < tenthPulsesPerSlot.length; i++) { - if (i == 0) { - previousTenthPulsesPerSlot = tenthPulsesPerSlot[i]; - numberOfSlotsInCurrentElement = 1; - } else if (previousTenthPulsesPerSlot != tenthPulsesPerSlot[i] || (numberOfSlotsInCurrentElement + 1) * previousTenthPulsesPerSlot > 65_534) { - elements.add(insulinProgramElementFactory.create(startSlotIndex, numberOfSlotsInCurrentElement, (short) (previousTenthPulsesPerSlot * numberOfSlotsInCurrentElement))); - - previousTenthPulsesPerSlot = tenthPulsesPerSlot[i]; - numberOfSlotsInCurrentElement = 1; - startSlotIndex += numberOfSlotsInCurrentElement; - } else { - numberOfSlotsInCurrentElement++; - } - } - elements.add(insulinProgramElementFactory.create(startSlotIndex, numberOfSlotsInCurrentElement, (short) (previousTenthPulsesPerSlot * numberOfSlotsInCurrentElement))); - - return elements; - } - - public static List mapPulsesPerSlotToShortInsulinProgramElements(short[] pulsesPerSlot) { - if (pulsesPerSlot.length > NUMBER_OF_BASAL_SLOTS) { - throw new IllegalArgumentException("Basal program must contain at most 48 slots"); - } - - List elements = new ArrayList<>(); - boolean extraAlternatePulse = false; - short previousPulsesPerSlot = 0; - byte numberOfSlotsInCurrentElement = 0; - byte currentTotalNumberOfSlots = 0; - - while (currentTotalNumberOfSlots < pulsesPerSlot.length) { - if (currentTotalNumberOfSlots == 0) { - // First slot - - previousPulsesPerSlot = pulsesPerSlot[0]; - currentTotalNumberOfSlots++; - numberOfSlotsInCurrentElement = 1; - } else if (pulsesPerSlot[currentTotalNumberOfSlots] == previousPulsesPerSlot) { - // Subsequent slot in element (same pulses per slot as previous slot) - - if (numberOfSlotsInCurrentElement < MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT) { - numberOfSlotsInCurrentElement++; - } else { - elements.add(new BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)); - previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots]; - numberOfSlotsInCurrentElement = 1; - extraAlternatePulse = false; - } - - currentTotalNumberOfSlots++; - } else if (numberOfSlotsInCurrentElement == 1 && pulsesPerSlot[currentTotalNumberOfSlots] == previousPulsesPerSlot + 1) { - // Second slot of segment with extra alternate pulse - - boolean expectAlternatePulseForNextSegment = false; - currentTotalNumberOfSlots++; - numberOfSlotsInCurrentElement++; - extraAlternatePulse = true; - while (currentTotalNumberOfSlots < pulsesPerSlot.length) { - // Loop rest alternate pulse segment - - if (pulsesPerSlot[currentTotalNumberOfSlots] == previousPulsesPerSlot + (expectAlternatePulseForNextSegment ? 1 : 0)) { - // Still in alternate pulse segment - - currentTotalNumberOfSlots++; - expectAlternatePulseForNextSegment = !expectAlternatePulseForNextSegment; - - if (numberOfSlotsInCurrentElement < MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT) { - numberOfSlotsInCurrentElement++; - } else { - // End of alternate pulse segment (no slots left in element) - - elements.add(new BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)); - previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots]; - numberOfSlotsInCurrentElement = 1; - extraAlternatePulse = false; - break; - } - } else { - // End of alternate pulse segment (new number of pulses per slot) - - elements.add(new BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)); - previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots]; - numberOfSlotsInCurrentElement = 1; - extraAlternatePulse = false; - currentTotalNumberOfSlots++; - break; - } - } - } else if (previousPulsesPerSlot != pulsesPerSlot[currentTotalNumberOfSlots]) { - // End of segment (new number of pulses per slot) - elements.add(new BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)); - - previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots]; - currentTotalNumberOfSlots++; - extraAlternatePulse = false; - numberOfSlotsInCurrentElement = 1; - } else { - throw new IllegalStateException("Reached illegal point in mapBasalProgramToShortInsulinProgramElements"); - } - } - - elements.add(new BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)); - - return elements; - } - - public static short[] mapBasalProgramToTenthPulsesPerSlot(BasalProgram basalProgram) { - short[] tenthPulsesPerSlot = new short[NUMBER_OF_BASAL_SLOTS]; - for (BasalProgram.Segment segment : basalProgram.getSegments()) { - for (int i = segment.getStartSlotIndex(); i < segment.getEndSlotIndex(); i++) { - tenthPulsesPerSlot[i] = (short) (roundToHalf(segment.getPulsesPerHour() / 2.0d) * 10); - } - } - - return tenthPulsesPerSlot; - } - - private static double roundToHalf(double d) { - return (double) (short) ((short) (int) (d * 10.0d) / 5 * 5) / 10.0d; - } - - public static short[] mapBasalProgramToPulsesPerSlot(BasalProgram basalProgram) { - short[] pulsesPerSlot = new short[NUMBER_OF_BASAL_SLOTS]; - for (BasalProgram.Segment segment : basalProgram.getSegments()) { - boolean remainingPulse = false; - for (int i = segment.getStartSlotIndex(); i < segment.getEndSlotIndex(); i++) { - pulsesPerSlot[i] = (short) (segment.getPulsesPerHour() / 2); - if (segment.getPulsesPerHour() % 2 == 1) { // Do extra alternate pulse - if (remainingPulse) { - pulsesPerSlot[i] += 1; - } - remainingPulse = !remainingPulse; - } - } - } - - return pulsesPerSlot; - } - - public static CurrentSlot calculateCurrentSlot(short[] pulsesPerSlot, Date currentTime) { - Calendar instance = Calendar.getInstance(); - instance.setTime(currentTime); - - int hourOfDay = instance.get(Calendar.HOUR_OF_DAY); - int minuteOfHour = instance.get(Calendar.MINUTE); - int secondOfMinute = instance.get(Calendar.SECOND); - - byte index = (byte) ((hourOfDay * 60 + minuteOfHour) / 30); - int secondOfDay = secondOfMinute + hourOfDay * 3_600 + minuteOfHour * 60; - - short secondsRemaining = (short) ((index + 1) * 1_800 - secondOfDay); - short pulsesRemaining = (short) ((double) pulsesPerSlot[index] * secondsRemaining / 1_800); - - return new CurrentSlot(index, (short) (secondsRemaining * 8), pulsesRemaining); - } - - public static CurrentBasalInsulinProgramElement calculateCurrentLongInsulinProgramElement(List elements, Date currentTime) { - Calendar instance = Calendar.getInstance(); - instance.setTime(currentTime); - - int hourOfDay = instance.get(Calendar.HOUR_OF_DAY); - int minuteOfHour = instance.get(Calendar.MINUTE); - int secondOfMinute = instance.get(Calendar.SECOND); - - int secondOfDay = secondOfMinute + hourOfDay * 3_600 + minuteOfHour * 60; - int startSlotIndex = 0; - - byte index = 0; - for (BasalInsulinProgramElement element : elements) { - int startTimeInSeconds = startSlotIndex * 1_800; - int endTimeInSeconds = startTimeInSeconds + element.getNumberOfSlots() * 1_800; - - if (secondOfDay >= startTimeInSeconds && secondOfDay < endTimeInSeconds) { - long totalNumberOfTenThousandthPulsesInSlot = element.getTotalTenthPulses() * 1_000; - if (totalNumberOfTenThousandthPulsesInSlot == 0) { - totalNumberOfTenThousandthPulsesInSlot = element.getNumberOfSlots() * 1_000; - } - - int durationInSeconds = endTimeInSeconds - startTimeInSeconds; - int secondsPassedInCurrentSlot = secondOfDay - startTimeInSeconds; - long remainingTenThousandthPulses = (long) ((durationInSeconds - secondsPassedInCurrentSlot) / (double) durationInSeconds * totalNumberOfTenThousandthPulsesInSlot); - int delayBetweenTenthPulsesInUsec = (int) (durationInSeconds * 1_000_000L * 1_000 / totalNumberOfTenThousandthPulsesInSlot); - int secondsRemaining = secondsPassedInCurrentSlot % 1_800; - int delayUntilNextTenthPulseInUsec = delayBetweenTenthPulsesInUsec; - for (int i = 0; i < secondsRemaining; i++) { - delayUntilNextTenthPulseInUsec = delayUntilNextTenthPulseInUsec - 1_000_000; - while (delayUntilNextTenthPulseInUsec <= 0) { - delayUntilNextTenthPulseInUsec += delayBetweenTenthPulsesInUsec; - } - } - short remainingTenthPulses = (short) ((remainingTenThousandthPulses % 1_000 != 0 ? 1 : 0) + remainingTenThousandthPulses / 1_000); - - return new CurrentBasalInsulinProgramElement(index, delayUntilNextTenthPulseInUsec, remainingTenthPulses); - } - - index++; - startSlotIndex += element.getNumberOfSlots(); - } - throw new IllegalStateException("Could not determine current long insulin program element"); - } - - public static short calculateChecksum(short[] pulsesPerSlot, CurrentSlot currentSlot) { - ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + 2 + NUMBER_OF_BASAL_SLOTS * 2) // - .put(currentSlot.getIndex()) // - .putShort(currentSlot.getPulsesRemaining()) // - .putShort(currentSlot.getEighthSecondsRemaining()); - - for (short pulses : pulsesPerSlot) { - buffer.putShort(pulses); - } - - return MessageUtil.calculateChecksum(buffer.array()); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt new file mode 100644 index 0000000000..d16dc83b27 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt @@ -0,0 +1,208 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalShortInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.CurrentBasalInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.CurrentSlot +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil +import java.nio.ByteBuffer +import java.util.* + +object ProgramBasalUtil { + + const val MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT = 1800000000 + private const val NUMBER_OF_BASAL_SLOTS: Byte = 48 + private const val MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT: Byte = 16 + + fun mapTenthPulsesPerSlotToLongInsulinProgramElements( + tenthPulsesPerSlot: ShortArray?, + insulinProgramElementFactory: (Byte, Byte, Short) -> BasalInsulinProgramElement = ::BasalInsulinProgramElement + ): List { + require(tenthPulsesPerSlot!!.size <= NUMBER_OF_BASAL_SLOTS) { "Basal program must contain at most 48 slots" } + val elements: MutableList = ArrayList() + var previousTenthPulsesPerSlot: Short = 0 + var numberOfSlotsInCurrentElement: Byte = 0 + var startSlotIndex: Byte = 0 + for (i in tenthPulsesPerSlot.indices) { + if (i == 0) { + previousTenthPulsesPerSlot = tenthPulsesPerSlot[i] + numberOfSlotsInCurrentElement = 1 + } else if (previousTenthPulsesPerSlot != tenthPulsesPerSlot[i] || (numberOfSlotsInCurrentElement + 1) * previousTenthPulsesPerSlot > 65534) { + elements.add(insulinProgramElementFactory(startSlotIndex, numberOfSlotsInCurrentElement, (previousTenthPulsesPerSlot * numberOfSlotsInCurrentElement).toShort())) + previousTenthPulsesPerSlot = tenthPulsesPerSlot[i] + numberOfSlotsInCurrentElement = 1 + startSlotIndex = (numberOfSlotsInCurrentElement + startSlotIndex).toByte() + } else { + numberOfSlotsInCurrentElement++ + } + } + elements.add(insulinProgramElementFactory(startSlotIndex, numberOfSlotsInCurrentElement, (previousTenthPulsesPerSlot * numberOfSlotsInCurrentElement).toShort())) + return elements + } + + fun mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot: ShortArray?): List { + require(pulsesPerSlot!!.size <= NUMBER_OF_BASAL_SLOTS) { "Basal program must contain at most 48 slots" } + val elements: MutableList = ArrayList() + var extraAlternatePulse = false + var previousPulsesPerSlot: Short = 0 + var numberOfSlotsInCurrentElement: Byte = 0 + var currentTotalNumberOfSlots: Byte = 0 + while (currentTotalNumberOfSlots < pulsesPerSlot.size) { + if (currentTotalNumberOfSlots.toInt() == 0) { + // First slot + previousPulsesPerSlot = pulsesPerSlot[0] + currentTotalNumberOfSlots++ + numberOfSlotsInCurrentElement = 1 + } else if (pulsesPerSlot[currentTotalNumberOfSlots.toInt()] == previousPulsesPerSlot) { + // Subsequent slot in element (same pulses per slot as previous slot) + if (numberOfSlotsInCurrentElement < MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT) { + numberOfSlotsInCurrentElement++ + } else { + elements.add(BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)) + previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots.toInt()] + numberOfSlotsInCurrentElement = 1 + extraAlternatePulse = false + } + currentTotalNumberOfSlots++ + } else if (numberOfSlotsInCurrentElement.toInt() == 1 && pulsesPerSlot[currentTotalNumberOfSlots.toInt()].toInt() == previousPulsesPerSlot + 1) { + // Second slot of segment with extra alternate pulse + var expectAlternatePulseForNextSegment = false + currentTotalNumberOfSlots++ + numberOfSlotsInCurrentElement++ + extraAlternatePulse = true + while (currentTotalNumberOfSlots < pulsesPerSlot.size) { + // Loop rest alternate pulse segment + if (pulsesPerSlot[currentTotalNumberOfSlots.toInt()].toInt() == previousPulsesPerSlot + (if (expectAlternatePulseForNextSegment) 1 else 0)) { + // Still in alternate pulse segment + currentTotalNumberOfSlots++ + expectAlternatePulseForNextSegment = !expectAlternatePulseForNextSegment + if (numberOfSlotsInCurrentElement < MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT) { + numberOfSlotsInCurrentElement++ + } else { + // End of alternate pulse segment (no slots left in element) + elements.add(BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)) + previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots.toInt()] + numberOfSlotsInCurrentElement = 1 + extraAlternatePulse = false + break + } + } else { + // End of alternate pulse segment (new number of pulses per slot) + elements.add(BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)) + previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots.toInt()] + numberOfSlotsInCurrentElement = 1 + extraAlternatePulse = false + currentTotalNumberOfSlots++ + break + } + } + } else if (previousPulsesPerSlot != pulsesPerSlot[currentTotalNumberOfSlots.toInt()]) { + // End of segment (new number of pulses per slot) + elements.add(BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)) + previousPulsesPerSlot = pulsesPerSlot[currentTotalNumberOfSlots.toInt()] + currentTotalNumberOfSlots++ + extraAlternatePulse = false + numberOfSlotsInCurrentElement = 1 + } else { + throw IllegalStateException("Reached illegal point in mapBasalProgramToShortInsulinProgramElements") + } + } + elements.add(BasalShortInsulinProgramElement(numberOfSlotsInCurrentElement, previousPulsesPerSlot, extraAlternatePulse)) + return elements + } + + fun mapBasalProgramToTenthPulsesPerSlot(basalProgram: BasalProgram): ShortArray { + val tenthPulsesPerSlot = ShortArray(NUMBER_OF_BASAL_SLOTS.toInt()) + for (segment in basalProgram.segments) { + for (i in segment.startSlotIndex until segment.endSlotIndex) { + tenthPulsesPerSlot[i] = (roundToHalf(segment.getPulsesPerHour() / 2.0) * 10).toInt().toShort() // TODO Adrian: int conversion ok? + } + } + return tenthPulsesPerSlot + } + + private fun roundToHalf(d: Double): Double { + return ((d * 10.0).toInt().toShort() / 5 * 5).toShort().toDouble() / 10.0 + } + + fun mapBasalProgramToPulsesPerSlot(basalProgram: BasalProgram): ShortArray { + val pulsesPerSlot = ShortArray(NUMBER_OF_BASAL_SLOTS.toInt()) + for (segment in basalProgram.segments) { + var remainingPulse = false + for (i in segment.startSlotIndex until segment.endSlotIndex) { + pulsesPerSlot[i] = (segment.getPulsesPerHour() / 2).toShort() + if (segment.getPulsesPerHour() % 2 == 1) { // Do extra alternate pulse + if (remainingPulse) { + pulsesPerSlot[i] = (pulsesPerSlot[i] + 1).toShort() + } + remainingPulse = !remainingPulse + } + } + } + return pulsesPerSlot + } + + fun calculateCurrentSlot(pulsesPerSlot: ShortArray?, currentTime: Date?): CurrentSlot { + val instance = Calendar.getInstance() + instance.time = currentTime + val hourOfDay = instance[Calendar.HOUR_OF_DAY] + val minuteOfHour = instance[Calendar.MINUTE] + val secondOfMinute = instance[Calendar.SECOND] + val index = ((hourOfDay * 60 + minuteOfHour) / 30).toByte() + val secondOfDay = secondOfMinute + hourOfDay * 3600 + minuteOfHour * 60 + val secondsRemaining = ((index + 1) * 1800 - secondOfDay).toShort() + val pulsesRemaining = (pulsesPerSlot!![index.toInt()].toDouble() * secondsRemaining / 1800).toShort() + return CurrentSlot(index, (secondsRemaining * 8).toShort(), pulsesRemaining) + } + + fun calculateCurrentLongInsulinProgramElement(elements: List, currentTime: Date?): CurrentBasalInsulinProgramElement { + val instance = Calendar.getInstance() + instance.time = currentTime + val hourOfDay = instance[Calendar.HOUR_OF_DAY] + val minuteOfHour = instance[Calendar.MINUTE] + val secondOfMinute = instance[Calendar.SECOND] + val secondOfDay = secondOfMinute + hourOfDay * 3600 + minuteOfHour * 60 + var startSlotIndex = 0 + var index: Byte = 0 + for (element in elements) { + val startTimeInSeconds = startSlotIndex * 1800 + val endTimeInSeconds = startTimeInSeconds + element.numberOfSlots * 1800 + if (secondOfDay in startTimeInSeconds until endTimeInSeconds) { // TODO Adrian Range check ok + var totalNumberOfTenThousandthPulsesInSlot = (element.totalTenthPulses * 1000).toLong() + if (totalNumberOfTenThousandthPulsesInSlot == 0L) { + totalNumberOfTenThousandthPulsesInSlot = (element.numberOfSlots * 1000).toLong() + } + val durationInSeconds = endTimeInSeconds - startTimeInSeconds + val secondsPassedInCurrentSlot = secondOfDay - startTimeInSeconds + val remainingTenThousandthPulses = ((durationInSeconds - secondsPassedInCurrentSlot) / durationInSeconds.toDouble() * totalNumberOfTenThousandthPulsesInSlot).toLong() + val delayBetweenTenthPulsesInUsec = (durationInSeconds * 1000000L * 1000 / totalNumberOfTenThousandthPulsesInSlot).toInt() + val secondsRemaining = secondsPassedInCurrentSlot % 1800 + var delayUntilNextTenthPulseInUsec = delayBetweenTenthPulsesInUsec + for (i in 0 until secondsRemaining) { + delayUntilNextTenthPulseInUsec -= 1000000 + while (delayUntilNextTenthPulseInUsec <= 0) { + delayUntilNextTenthPulseInUsec += delayBetweenTenthPulsesInUsec + } + } + val remainingTenthPulses = ((if (remainingTenThousandthPulses % 1000 != 0L) 1 else 0) + remainingTenThousandthPulses / 1000).toShort() + return CurrentBasalInsulinProgramElement(index, delayUntilNextTenthPulseInUsec, remainingTenthPulses) + } + index++ + startSlotIndex += element.numberOfSlots.toInt() + } + throw IllegalStateException("Could not determine current long insulin program element") + } + + fun calculateChecksum(pulsesPerSlot: ShortArray?, currentSlot: CurrentSlot): Short { + val buffer = ByteBuffer.allocate(1 + 2 + 2 + NUMBER_OF_BASAL_SLOTS * 2) // + .put(currentSlot.index) // + .putShort(currentSlot.pulsesRemaining) // + .putShort(currentSlot.eighthSecondsRemaining) + for (pulses in pulsesPerSlot!!) { + buffer.putShort(pulses) + } + return MessageUtil.calculateChecksum(buffer.array()) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.java deleted file mode 100644 index f60a5b3e8e..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.java +++ /dev/null @@ -1,68 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util; - -import java.nio.ByteBuffer; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.TempBasalInsulinProgramElement; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil; - -public final class ProgramTempBasalUtil { - private ProgramTempBasalUtil() { - } - - public static List mapTenthPulsesPerSlotToLongInsulinProgramElements(short[] tenthPulsesPerSlot) { - return ProgramBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot, TempBasalInsulinProgramElement::new); - } - - public static short[] mapTempBasalToTenthPulsesPerSlot(int durationInSlots, double rateInUnitsPerHour) { - short pulsesPerHour = (short) Math.round(rateInUnitsPerHour * 20); - - short[] tenthPulsesPerSlot = new short[durationInSlots]; - for (int i = 0; durationInSlots > i; i++) { - tenthPulsesPerSlot[i] = (short) (roundToHalf(pulsesPerHour / 2.0d) * 10); - } - - return tenthPulsesPerSlot; - } - - private static double roundToHalf(double d) { - return (double) (short) ((short) (int) (d * 10.0d) / 5 * 5) / 10.0d; - } - - public static short[] mapTempBasalToPulsesPerSlot(byte durationInSlots, double rateInUnitsPerHour) { - short pulsesPerHour = (short) Math.round(rateInUnitsPerHour * 20); - short[] pulsesPerSlot = new short[durationInSlots]; - - boolean remainingPulse = false; - - for (int i = 0; durationInSlots > i; i++) { - pulsesPerSlot[i] = (short) (pulsesPerHour / 2); - if (pulsesPerHour % 2 == 1) { // Do extra alternate pulse - if (remainingPulse) { - pulsesPerSlot[i] += 1; - } - remainingPulse = !remainingPulse; - } - } - - return pulsesPerSlot; - } - - public static short calculateChecksum(byte totalNumberOfSlots, short pulsesInFirstSlot, short[] pulsesPerSlot) { - ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + 2 + 2 * pulsesPerSlot.length) // - .put(totalNumberOfSlots) // - .putShort((short) 0x3840) // - .putShort(pulsesInFirstSlot); - for (short pulses : pulsesPerSlot) { - buffer.putShort(pulses); - } - - return MessageUtil.calculateChecksum(buffer.array()); - } - - public static List mapPulsesPerSlotToShortInsulinProgramElements(short[] pulsesPerSlot) { - return ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot); - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt new file mode 100644 index 0000000000..29652e3e97 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt @@ -0,0 +1,62 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.BasalInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.ShortInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.TempBasalInsulinProgramElement +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.MessageUtil +import java.nio.ByteBuffer +import kotlin.math.roundToInt + +object ProgramTempBasalUtil { + + fun mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot: ShortArray?): List { + return ProgramBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) { startSlotIndex: Byte, numberOfSlots: Byte, totalTenthPulses: Short -> TempBasalInsulinProgramElement(startSlotIndex, numberOfSlots, totalTenthPulses) } + } + + fun mapTempBasalToTenthPulsesPerSlot(durationInSlots: Int, rateInUnitsPerHour: Double): ShortArray { + val pulsesPerHour = (rateInUnitsPerHour * 20).roundToInt().toShort() + val tenthPulsesPerSlot = ShortArray(durationInSlots) + var i = 0 + while (durationInSlots > i) { + tenthPulsesPerSlot[i] = (roundToHalf(pulsesPerHour / 2.0) * 10).toShort() + i++ + } + return tenthPulsesPerSlot + } + + private fun roundToHalf(d: Double): Double { + return ((d * 10.0).toInt().toShort() / 5 * 5).toShort().toDouble() / 10.0 + } + + fun mapTempBasalToPulsesPerSlot(durationInSlots: Byte, rateInUnitsPerHour: Double): ShortArray { + val pulsesPerHour = (rateInUnitsPerHour * 20).roundToInt().toShort() + val pulsesPerSlot = ShortArray(durationInSlots.toInt()) + var remainingPulse = false + var i = 0 + while (durationInSlots > i) { + pulsesPerSlot[i] = (pulsesPerHour / 2).toShort() + if (pulsesPerHour % 2 == 1) { // Do extra alternate pulse + if (remainingPulse) { + pulsesPerSlot[i] = (pulsesPerSlot[i] + 1).toShort() + } + remainingPulse = !remainingPulse + } + i++ + } + return pulsesPerSlot + } + + fun calculateChecksum(totalNumberOfSlots: Byte, pulsesInFirstSlot: Short, pulsesPerSlot: ShortArray?): Short { + val buffer = ByteBuffer.allocate(1 + 2 + 2 + 2 * pulsesPerSlot!!.size) // + .put(totalNumberOfSlots) // + .putShort(0x3840.toShort()) // + .putShort(pulsesInFirstSlot) + for (pulses in pulsesPerSlot) { + buffer.putShort(pulses) + } + return MessageUtil.calculateChecksum(buffer.array()) + } + + fun mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot: ShortArray?): List = + ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java deleted file mode 100644 index 7fcf8a8ece..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.java +++ /dev/null @@ -1,174 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum AlarmType { - NONE((byte) 0x00), - ALARM_PW_FLASH_ERASE((byte) 0x01), - ALARM_PW_FLASH_WRITE((byte) 0x02), - ALARM_BASAL_CKSUM((byte) 0x03), - ALARM_BASAL_PPULSE((byte) 0x04), - ALARM_BASAL_STEP((byte) 0x05), - ALARM_AUTO_WAKEUP_TIMEOUT((byte) 0x06), - ALARM_WIRE_OVERDRIVEN((byte) 0x07), - ALARM_BEEP_REP_INVALID_INDEX((byte) 0x08), - ALARM_INVALID_REP_PATTERN((byte) 0x09), - ALARM_TEMP_BASAL_STEP((byte) 0x0a), - ALARM_TEMP_BASAL_CKSUM((byte) 0x0b), - ALARM_BOLUS_OVERFLOW((byte) 0x0c), - ALARM_COP_RESET((byte) 0x0d), - ALARM_ILOP_RESET((byte) 0x0e), - ALARM_ILAD_RESET((byte) 0x0f), - ALARM_SAWCOP_RESET((byte) 0x10), - ALARM_BOLUS_STEP((byte) 0x11), - ALARM_LVD_RESET((byte) 0x12), - ALARM_INVALID_RF_MSG_LENGTH((byte) 0x13), - ALARM_OCCLUDED((byte) 0x14), - ALARM_BOLUSPROG_CHKSUM((byte) 0x15), - ALARM_BOLUS_LOG((byte) 0x16), - ALARM_CRITICAL_VAR((byte) 0x17), - ALARM_EMPTY_RESERVOIR((byte) 0x18), - ALARM_LOADERR((byte) 0x19), - ALARM_PSA_FAILURE((byte) 0x1a), - ALARM_TICKCNT_NOT_CLEARED((byte) 0x1b), - ALARM_PUMP_EXPIRED((byte) 0x1c), - ALARM_COMD_BIT_NOT_SET((byte) 0x1d), - ALARM_INVALID_COMD_SET((byte) 0x1e), - ALARM_ALERTS_ARRAY_CKSM((byte) 0x1f), - ALARM_UNIT_TEST((byte) 0x20), - ALARM_TICK_TIME_ERROR((byte) 0x21), - ALARM_CRITICAL_HAZARD((byte) 0x22), - ALARM_PIEZO_FREQ((byte) 0x23), - ALARM_TICKCNT_ERROR_RTC((byte) 0x24), - ALARM_TICK_FAILURE((byte) 0x25), - ALARM_INVALID((byte) 0x26), - ALARM_LUMP_ALERT_PROGRAM((byte) 0x27), - ALARM_INVALID_PASS_CODE((byte) 0x28), - ALARM_ALERT0((byte) 0x29), - ALARM_ALERT1((byte) 0x2a), - ALARM_ALERT2((byte) 0x2b), - ALARM_ALERT3((byte) 0x2c), - ALARM_ALERT4((byte) 0x2d), - ALARM_ALERT5((byte) 0x2e), - ALARM_ALERT6((byte) 0x2f), - ALARM_ALERT7((byte) 0x30), - ALARM_ILLEGAL_PUMP_STATE((byte) 0x31), - ALARM_COP_TEST_FAILURE((byte) 0x32), - ALARM_MCTF((byte) 0x33), - ALARM_ILLEGAL_RESET((byte) 0x34), - ALARM_VETO_NOT_SET((byte) 0x35), - ALARM_ILLEGAL_PIN_RESET((byte) 0x36), - ALARM_INVALID_BEEP_PATTERN((byte) 0x37), - ALARM_WIRE_STATE_MACHINE((byte) 0x38), - ALARM_VETO_TEST_DEFAULT((byte) 0x39), - ALARM_ALERT_INVALID_INDEX((byte) 0x3a), - ALARM_SAWCOP_TEST_FAIL((byte) 0x3b), - ALARM_MCUCOP_TEST_FAIL((byte) 0x3c), - ALARM_STEP_SENSOR_SHORTED((byte) 0x3d), - ALARM_FLASH_FAILURE((byte) 0x3e), - ALARM_SPARE63((byte) 0x3f), - ALARM_SS_OPEN_CNT_EXCEEDED((byte) 0x40), - ALARM_SS_EXCESSIVE_SUMMED((byte) 0x41), - ALARM_SS_MIN_PULSE_TRANSITION((byte) 0x42), - ALARM_SS_DEFAULT((byte) 0x43), - ALARM_OPEN_WIRE1((byte) 0x44), - ALARM_OPEN_WIRE2((byte) 0x45), - ALARM_LOADERR_FAILURE((byte) 0x46), - ALARM_SAW_VETO_FAILURE((byte) 0x47), - ALARM_BAD_RFM_CLOCK((byte) 0x48), - ALARM_BAD_TICK_HIGH((byte) 0x49), - ALARM_BAD_TICK_PERIOD((byte) 0x4a), - ALARM_BAD_TRIM_VALUE((byte) 0x4b), - ALARM_BAD_BUS_CLOCK((byte) 0x4c), - ALARM_BAD_CAL_MODE((byte) 0x4d), - ALARM_SAW_TRIM_ERROR((byte) 0x4e), - ALARM_RFM_CRYSTAL_ERROR((byte) 0x4f), - ALARM_CALST_TIMEOUT((byte) 0x50), - ALARM_TICKCNT_ERROR((byte) 0x51), - ALARM_BAD_RFM_XTAL_START((byte) 0x52), - ALARM_BAD_RX_SENSENSITIVITY((byte) 0x53), - ALARM_BAD_TX_PKT_SIZE((byte) 0x54), - ALARM_TICK_LOW_PHASE_EXCEEDED((byte) 0x55), - ALARM_TICK_HIGH_PHASE_EXCEEDED((byte) 0x56), - ALARM_OCCL_CRITVAR_FAIL((byte) 0x57), - ALARM_OCCL_PARAM((byte) 0x58), - ALARM_PROG_OCCL_FAIL((byte) 0x59), - ALARM_PW_TO_HIGH_FOR_OCCL_DET((byte) 0x5a), - ALARM_OCCL_CSUM((byte) 0x5b), - ALARM_PRIME_OPEN_CNT_TO_LOW((byte) 0x5c), - ALARM_BAD_RF_CDTHR((byte) 0x5d), - ALARM_FLASH_NOT_SECURE((byte) 0x5e), - ALARM_WIRE_TEST_OPEN_GROUND((byte) 0x5f), - ALARM_OCCL_STARTUP1((byte) 0x60), - ALARM_OCCL_STARTUP2((byte) 0x61), - ALARM_OCCL_EXCESS_TIMEOUTS1((byte) 0x62), - ALARM_SPARE99((byte) 0x63), - ALARM_SPARE100((byte) 0x64), - ALARM_SPARE101((byte) 0x65), - ALARM_OCCL_EXCESS_TIMEOUTS2((byte) 0x66), - ALARM_OCCL_EXCESS_TIMEOUTS3((byte) 0x67), - ALARM_OCCL_NOISY_PULSE_WIDTHS((byte) 0x68), - ALARM_OCCL_AT_BOLUS_END((byte) 0x69), - ALARM_OCCL_ABOVE_THRESHOLD((byte) 0x6a), - ALARM_BASAL_UNDERINFUSION((byte) 0x80), - ALARM_BASAL_OVERINFUSION((byte) 0x81), - ALARM_TEMP_UNDERINFUSION((byte) 0x82), - ALARM_TEMP_OVERINFUSION((byte) 0x83), - ALARM_BOLUS_UNDERINFUSION((byte) 0x84), - ALARM_BOLUS_OVERINFUSION((byte) 0x85), - ALARM_BASAL_OVERINFUSION_PULSE((byte) 0x86), - ALARM_TEMP_OVERINFUSION_PULSE((byte) 0x87), - ALARM_BOLUS_OVERINFUSION_PULSE((byte) 0x88), - ALARM_IMMBOLUS_UNDERINFUSION_PULSE((byte) 0x89), - ALARM_EXTBOLUS_OVERINFUSION_PULSE((byte) 0x8a), - ALARM_PROGRAM_CSUM((byte) 0x8b), - ALARM_UNUSED_140((byte) 0x8c), - ALARM_UNRECOGNIZED_PULSE((byte) 0x8d), - ALARM_SYNC_WITHOUT_TEMP_ACTIVE((byte) 0x8e), - ALARM_INTERLOCK_LOAD((byte) 0x8f), - ALARM_ILLEGAL_CHAN_PARAM((byte) 0x90), - ALARM_BASAL_PULSE_CHAN_INACTIVE((byte) 0x91), - ALARM_TEMP_PULSE_CHAN_INACTIVE((byte) 0x92), - ALARM_BOLUS_PULSE_CHAN_INACTIVE((byte) 0x93), - ALARM_INT_SEMAPHORE_NOT_SET((byte) 0x94), - ALARM_ILLEGAL_INTERLOCK_CHAN((byte) 0x95), - ALARM_TERMINATE_BOLUS((byte) 0x96), - ALARM_OPEN_TRANSITIONS_COUNT((byte) 0x97), - ALARM_BLE_TO((byte) 0xa0), - ALARM_BLE_INITIATED((byte) 0xa1), - ALARM_BLE_UNK_ALARM((byte) 0xa2), - ALARM_UNUSED_163((byte) 0xa3), - ALARM_UNUSED_164((byte) 0xa4), - ALARM_UNUSED_165((byte) 0xa5), - ALARM_BLE_IAAS((byte) 0xa6), - ALARM_UNUSED_167((byte) 0xa7), - ALARM_CRC_FAILURE((byte) 0xa8), - ALARM_BLE_WD_PING_TIMEOUT((byte) 0xa9), - ALARM_BLE_EXCESSIVE_RESETS((byte) 0xaa), - ALARM_BLE_NAK_ERROR((byte) 0xab), - ALARM_BLE_REQ_HIGH_TIMEOUT((byte) 0xac), - ALARM_BLE_UNKNOWN_RESP((byte) 0xad), - ALARM_BLE_UNUSED_174((byte) 0xae), - ALARM_BLE_REQ_STUCK_HIGH((byte) 0xaf), - ALARM_BLE_STATE_MACHINE_1((byte) 0xb1), - ALARM_BLE_STATE_MACHINE_2((byte) 0xb2), - ALARM_BLE_UNUSED_179((byte) 0xb3), - ALARM_BLE_ARB_LOST((byte) 0xb4), - ALARM_BLE_ER48_DUAL_NACK((byte) 0xc0), - ALARM_BLE_QN_EXCEED_MAX_RETRY((byte) 0xc1), - ALARM_BLE_QN_CRIT_VAR_FAIL((byte) 0xc2), - UNKNOWN((byte) 0xff); - - private byte value; - - AlarmType(byte value) { - this.value = value; - } - - public static AlarmType byValue(byte value) { - for (AlarmType type : values()) { - if (type.value == value) { - return type; - } - } - return UNKNOWN; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt new file mode 100644 index 0000000000..b6b59da23f --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class AlarmType(private val value: Byte) { + NONE(0x00.toByte()), ALARM_PW_FLASH_ERASE(0x01.toByte()), ALARM_PW_FLASH_WRITE(0x02.toByte()), ALARM_BASAL_CKSUM(0x03.toByte()), ALARM_BASAL_PPULSE(0x04.toByte()), ALARM_BASAL_STEP(0x05.toByte()), ALARM_AUTO_WAKEUP_TIMEOUT(0x06.toByte()), ALARM_WIRE_OVERDRIVEN(0x07.toByte()), ALARM_BEEP_REP_INVALID_INDEX(0x08.toByte()), ALARM_INVALID_REP_PATTERN(0x09.toByte()), ALARM_TEMP_BASAL_STEP(0x0a.toByte()), ALARM_TEMP_BASAL_CKSUM(0x0b.toByte()), ALARM_BOLUS_OVERFLOW(0x0c.toByte()), ALARM_COP_RESET(0x0d.toByte()), ALARM_ILOP_RESET(0x0e.toByte()), ALARM_ILAD_RESET(0x0f.toByte()), ALARM_SAWCOP_RESET(0x10.toByte()), ALARM_BOLUS_STEP(0x11.toByte()), ALARM_LVD_RESET(0x12.toByte()), ALARM_INVALID_RF_MSG_LENGTH(0x13.toByte()), ALARM_OCCLUDED(0x14.toByte()), ALARM_BOLUSPROG_CHKSUM(0x15.toByte()), ALARM_BOLUS_LOG(0x16.toByte()), ALARM_CRITICAL_VAR(0x17.toByte()), ALARM_EMPTY_RESERVOIR(0x18.toByte()), ALARM_LOADERR(0x19.toByte()), ALARM_PSA_FAILURE(0x1a.toByte()), ALARM_TICKCNT_NOT_CLEARED(0x1b.toByte()), ALARM_PUMP_EXPIRED(0x1c.toByte()), ALARM_COMD_BIT_NOT_SET(0x1d.toByte()), ALARM_INVALID_COMD_SET(0x1e.toByte()), ALARM_ALERTS_ARRAY_CKSM(0x1f.toByte()), ALARM_UNIT_TEST(0x20.toByte()), ALARM_TICK_TIME_ERROR(0x21.toByte()), ALARM_CRITICAL_HAZARD(0x22.toByte()), ALARM_PIEZO_FREQ(0x23.toByte()), ALARM_TICKCNT_ERROR_RTC(0x24.toByte()), ALARM_TICK_FAILURE(0x25.toByte()), ALARM_INVALID(0x26.toByte()), ALARM_LUMP_ALERT_PROGRAM(0x27.toByte()), ALARM_INVALID_PASS_CODE(0x28.toByte()), ALARM_ALERT0(0x29.toByte()), ALARM_ALERT1(0x2a.toByte()), ALARM_ALERT2(0x2b.toByte()), ALARM_ALERT3(0x2c.toByte()), ALARM_ALERT4(0x2d.toByte()), ALARM_ALERT5(0x2e.toByte()), ALARM_ALERT6(0x2f.toByte()), ALARM_ALERT7(0x30.toByte()), ALARM_ILLEGAL_PUMP_STATE(0x31.toByte()), ALARM_COP_TEST_FAILURE(0x32.toByte()), ALARM_MCTF(0x33.toByte()), ALARM_ILLEGAL_RESET(0x34.toByte()), ALARM_VETO_NOT_SET(0x35.toByte()), ALARM_ILLEGAL_PIN_RESET(0x36.toByte()), ALARM_INVALID_BEEP_PATTERN(0x37.toByte()), ALARM_WIRE_STATE_MACHINE(0x38.toByte()), ALARM_VETO_TEST_DEFAULT(0x39.toByte()), ALARM_ALERT_INVALID_INDEX(0x3a.toByte()), ALARM_SAWCOP_TEST_FAIL(0x3b.toByte()), ALARM_MCUCOP_TEST_FAIL(0x3c.toByte()), ALARM_STEP_SENSOR_SHORTED(0x3d.toByte()), ALARM_FLASH_FAILURE(0x3e.toByte()), ALARM_SPARE63(0x3f.toByte()), ALARM_SS_OPEN_CNT_EXCEEDED(0x40.toByte()), ALARM_SS_EXCESSIVE_SUMMED(0x41.toByte()), ALARM_SS_MIN_PULSE_TRANSITION(0x42.toByte()), ALARM_SS_DEFAULT(0x43.toByte()), ALARM_OPEN_WIRE1(0x44.toByte()), ALARM_OPEN_WIRE2(0x45.toByte()), ALARM_LOADERR_FAILURE(0x46.toByte()), ALARM_SAW_VETO_FAILURE(0x47.toByte()), ALARM_BAD_RFM_CLOCK(0x48.toByte()), ALARM_BAD_TICK_HIGH(0x49.toByte()), ALARM_BAD_TICK_PERIOD(0x4a.toByte()), ALARM_BAD_TRIM_VALUE(0x4b.toByte()), ALARM_BAD_BUS_CLOCK(0x4c.toByte()), ALARM_BAD_CAL_MODE(0x4d.toByte()), ALARM_SAW_TRIM_ERROR(0x4e.toByte()), ALARM_RFM_CRYSTAL_ERROR(0x4f.toByte()), ALARM_CALST_TIMEOUT(0x50.toByte()), ALARM_TICKCNT_ERROR(0x51.toByte()), ALARM_BAD_RFM_XTAL_START(0x52.toByte()), ALARM_BAD_RX_SENSENSITIVITY(0x53.toByte()), ALARM_BAD_TX_PKT_SIZE(0x54.toByte()), ALARM_TICK_LOW_PHASE_EXCEEDED(0x55.toByte()), ALARM_TICK_HIGH_PHASE_EXCEEDED(0x56.toByte()), ALARM_OCCL_CRITVAR_FAIL(0x57.toByte()), ALARM_OCCL_PARAM(0x58.toByte()), ALARM_PROG_OCCL_FAIL(0x59.toByte()), ALARM_PW_TO_HIGH_FOR_OCCL_DET(0x5a.toByte()), ALARM_OCCL_CSUM(0x5b.toByte()), ALARM_PRIME_OPEN_CNT_TO_LOW(0x5c.toByte()), ALARM_BAD_RF_CDTHR(0x5d.toByte()), ALARM_FLASH_NOT_SECURE(0x5e.toByte()), ALARM_WIRE_TEST_OPEN_GROUND(0x5f.toByte()), ALARM_OCCL_STARTUP1(0x60.toByte()), ALARM_OCCL_STARTUP2(0x61.toByte()), ALARM_OCCL_EXCESS_TIMEOUTS1(0x62.toByte()), ALARM_SPARE99(0x63.toByte()), ALARM_SPARE100(0x64.toByte()), ALARM_SPARE101(0x65.toByte()), ALARM_OCCL_EXCESS_TIMEOUTS2(0x66.toByte()), ALARM_OCCL_EXCESS_TIMEOUTS3(0x67.toByte()), ALARM_OCCL_NOISY_PULSE_WIDTHS(0x68.toByte()), ALARM_OCCL_AT_BOLUS_END(0x69.toByte()), ALARM_OCCL_ABOVE_THRESHOLD(0x6a.toByte()), ALARM_BASAL_UNDERINFUSION(0x80.toByte()), ALARM_BASAL_OVERINFUSION(0x81.toByte()), ALARM_TEMP_UNDERINFUSION(0x82.toByte()), ALARM_TEMP_OVERINFUSION(0x83.toByte()), ALARM_BOLUS_UNDERINFUSION(0x84.toByte()), ALARM_BOLUS_OVERINFUSION(0x85.toByte()), ALARM_BASAL_OVERINFUSION_PULSE(0x86.toByte()), ALARM_TEMP_OVERINFUSION_PULSE(0x87.toByte()), ALARM_BOLUS_OVERINFUSION_PULSE(0x88.toByte()), ALARM_IMMBOLUS_UNDERINFUSION_PULSE(0x89.toByte()), ALARM_EXTBOLUS_OVERINFUSION_PULSE(0x8a.toByte()), ALARM_PROGRAM_CSUM(0x8b.toByte()), ALARM_UNUSED_140(0x8c.toByte()), ALARM_UNRECOGNIZED_PULSE(0x8d.toByte()), ALARM_SYNC_WITHOUT_TEMP_ACTIVE(0x8e.toByte()), ALARM_INTERLOCK_LOAD(0x8f.toByte()), ALARM_ILLEGAL_CHAN_PARAM(0x90.toByte()), ALARM_BASAL_PULSE_CHAN_INACTIVE(0x91.toByte()), ALARM_TEMP_PULSE_CHAN_INACTIVE(0x92.toByte()), ALARM_BOLUS_PULSE_CHAN_INACTIVE(0x93.toByte()), ALARM_INT_SEMAPHORE_NOT_SET(0x94.toByte()), ALARM_ILLEGAL_INTERLOCK_CHAN(0x95.toByte()), ALARM_TERMINATE_BOLUS(0x96.toByte()), ALARM_OPEN_TRANSITIONS_COUNT(0x97.toByte()), ALARM_BLE_TO(0xa0.toByte()), ALARM_BLE_INITIATED(0xa1.toByte()), ALARM_BLE_UNK_ALARM(0xa2.toByte()), ALARM_UNUSED_163(0xa3.toByte()), ALARM_UNUSED_164(0xa4.toByte()), ALARM_UNUSED_165(0xa5.toByte()), ALARM_BLE_IAAS(0xa6.toByte()), ALARM_UNUSED_167(0xa7.toByte()), ALARM_CRC_FAILURE(0xa8.toByte()), ALARM_BLE_WD_PING_TIMEOUT(0xa9.toByte()), ALARM_BLE_EXCESSIVE_RESETS(0xaa.toByte()), ALARM_BLE_NAK_ERROR(0xab.toByte()), ALARM_BLE_REQ_HIGH_TIMEOUT(0xac.toByte()), ALARM_BLE_UNKNOWN_RESP(0xad.toByte()), ALARM_BLE_UNUSED_174(0xae.toByte()), ALARM_BLE_REQ_STUCK_HIGH(0xaf.toByte()), ALARM_BLE_STATE_MACHINE_1(0xb1.toByte()), ALARM_BLE_STATE_MACHINE_2(0xb2.toByte()), ALARM_BLE_UNUSED_179(0xb3.toByte()), ALARM_BLE_ARB_LOST(0xb4.toByte()), ALARM_BLE_ER48_DUAL_NACK(0xc0.toByte()), ALARM_BLE_QN_EXCEED_MAX_RETRY(0xc1.toByte()), ALARM_BLE_QN_CRIT_VAR_FAIL(0xc2.toByte()), UNKNOWN(0xff.toByte()); + + companion object { + + fun byValue(value: Byte): AlarmType { + for (type in values()) { + if (type.value == value) { + return type + } + } + return UNKNOWN + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java deleted file mode 100644 index 8a52836d58..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.java +++ /dev/null @@ -1,61 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -import java.nio.ByteBuffer; - -public class AlertConfiguration implements Encodable { - private AlertSlot slot; - private boolean enabled; - private short durationInMinutes; - private boolean autoOff; - private AlertTriggerType triggerType; - private short offsetInMinutesOrThresholdInMicroLiters; - private BeepType beepType; - private BeepRepetitionType beepRepetition; - - public AlertConfiguration(AlertSlot slot, boolean enabled, short durationInMinutes, boolean autoOff, AlertTriggerType triggerType, short offsetInMinutesOrThresholdInMicroLiters, BeepType beepType, BeepRepetitionType beepRepetition) { - this.slot = slot; - this.enabled = enabled; - this.durationInMinutes = durationInMinutes; - this.autoOff = autoOff; - this.triggerType = triggerType; - this.offsetInMinutesOrThresholdInMicroLiters = offsetInMinutesOrThresholdInMicroLiters; - this.beepType = beepType; - this.beepRepetition = beepRepetition; - } - - @Override public byte[] getEncoded() { - byte firstByte = (byte) (slot.getValue() << 4); - if (enabled) { - firstByte |= 1 << 3; - } - if (triggerType == AlertTriggerType.RESERVOIR_VOLUME_TRIGGER) { - firstByte |= 1 << 2; - } - if (autoOff) { - firstByte |= 1 << 1; - } - firstByte |= ((durationInMinutes >> 8) & 0x01); - - return ByteBuffer.allocate(6) // - .put(firstByte) - .put((byte) durationInMinutes) // - .putShort(offsetInMinutesOrThresholdInMicroLiters) // - .put(beepRepetition.getValue()) // - .put(beepType.getValue()) // - .array(); - } - - @Override public String toString() { - return "AlertConfiguration{" + - "slot=" + slot + - ", enabled=" + enabled + - ", durationInMinutes=" + durationInMinutes + - ", autoOff=" + autoOff + - ", triggerType=" + triggerType + - ", offsetInMinutesOrThresholdInMicroLiters=" + offsetInMinutesOrThresholdInMicroLiters + - ", beepType=" + beepType + - ", beepRepetition=" + beepRepetition + - '}'; - } - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt new file mode 100644 index 0000000000..a677a533ca --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt @@ -0,0 +1,43 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +import java.nio.ByteBuffer +import kotlin.experimental.or + +class AlertConfiguration(private val slot: AlertSlot, private val enabled: Boolean, private val durationInMinutes: Short, private val autoOff: Boolean, private val triggerType: AlertTriggerType, private val offsetInMinutesOrThresholdInMicroLiters: Short, private val beepType: BeepType, private val beepRepetition: BeepRepetitionType) : Encodable { + + + override val encoded: ByteArray + get() { + var firstByte = (slot.value.toInt() shl 4).toByte() + if (enabled) { + firstByte = firstByte or (1 shl 3) + } + if (triggerType == AlertTriggerType.RESERVOIR_VOLUME_TRIGGER) { + firstByte = firstByte or (1 shl 2) + } + if (autoOff) { + firstByte = firstByte or (1 shl 1) + } + firstByte = firstByte or ((durationInMinutes.toInt() shr 8 and 0x01).toByte()) //Todo bitstuff + return ByteBuffer.allocate(6) // + .put(firstByte) + .put(durationInMinutes.toByte()) // + .putShort(offsetInMinutesOrThresholdInMicroLiters) // + .put(beepRepetition.value) // + .put(beepType.value) // + .array() + } + + override fun toString(): String { + return "AlertConfiguration{" + + "slot=" + slot + + ", enabled=" + enabled + + ", durationInMinutes=" + durationInMinutes + + ", autoOff=" + autoOff + + ", triggerType=" + triggerType + + ", offsetInMinutesOrThresholdInMicroLiters=" + offsetInMinutesOrThresholdInMicroLiters + + ", beepType=" + beepType + + ", beepRepetition=" + beepRepetition + + '}' + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java deleted file mode 100644 index 9e8b23cb74..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.java +++ /dev/null @@ -1,32 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum AlertSlot { - AUTO_OFF((byte) 0x00), - MULTI_COMMAND((byte) 0x01), - EXPIRATION_IMMINENT((byte) 0x02), - USER_SET_EXPIRATION((byte) 0x03), - LOW_RESERVOIR((byte) 0x04), - SUSPEND_IN_PROGRESS((byte) 0x05), - SUSPEND_ENDED((byte) 0x06), - EXPIRATION((byte) 0x07), - UNKNOWN((byte) 0xff); - - private byte value; - - AlertSlot(byte value) { - this.value = value; - } - - public static AlertSlot byValue(byte value) { - for (AlertSlot slot : values()) { - if (slot.value == value) { - return slot; - } - } - return UNKNOWN; - } - - public byte getValue() { - return value; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt new file mode 100644 index 0000000000..15fa641c86 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class AlertSlot(val value: Byte) { + AUTO_OFF(0x00.toByte()), MULTI_COMMAND(0x01.toByte()), EXPIRATION_IMMINENT(0x02.toByte()), USER_SET_EXPIRATION(0x03.toByte()), LOW_RESERVOIR(0x04.toByte()), SUSPEND_IN_PROGRESS(0x05.toByte()), SUSPEND_ENDED(0x06.toByte()), EXPIRATION(0x07.toByte()), UNKNOWN(0xff.toByte()); + + companion object { + + fun byValue(value: Byte): AlertSlot { + for (slot in values()) { + if (slot.value == value) { + return slot + } + } + return UNKNOWN + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.java deleted file mode 100644 index fda5bf010f..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.java +++ /dev/null @@ -1,6 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum AlertTriggerType { - TIME_TRIGGER, - RESERVOIR_VOLUME_TRIGGER -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt new file mode 100644 index 0000000000..6410cc9cfd --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class AlertTriggerType { + TIME_TRIGGER, RESERVOIR_VOLUME_TRIGGER +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.java deleted file mode 100644 index 5019260b0b..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.java +++ /dev/null @@ -1,92 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -public class BasalProgram { - private final List segments; - - public BasalProgram(List segments) { - if (segments == null) { - throw new IllegalArgumentException("segments can not be null"); - } - - // TODO validate segments - - this.segments = new ArrayList<>(segments); - } - - public void addSegment(Segment segment) { - segments.add(segment); - } - - public List getSegments() { - return Collections.unmodifiableList(segments); - } - - public boolean isZeroBasal() { - int total = 0; - for (Segment segment : segments) { - total += segment.getBasalRateInHundredthUnitsPerHour(); - } - return total == 0; - } - - public boolean hasZeroUnitSegments() { - for (Segment segment : segments) { - if (segment.getBasalRateInHundredthUnitsPerHour() == 0) { - return true; - } - } - return false; - } - - public static class Segment { - private static final byte PULSES_PER_UNIT = 20; - - private final short startSlotIndex; - private final short endSlotIndex; - private final int basalRateInHundredthUnitsPerHour; - - public Segment(short startSlotIndex, short endSlotIndex, int basalRateInHundredthUnitsPerHour) { - this.startSlotIndex = startSlotIndex; - this.endSlotIndex = endSlotIndex; - this.basalRateInHundredthUnitsPerHour = basalRateInHundredthUnitsPerHour; - } - - public short getStartSlotIndex() { - return startSlotIndex; - } - - public short getEndSlotIndex() { - return endSlotIndex; - } - - public int getBasalRateInHundredthUnitsPerHour() { - return basalRateInHundredthUnitsPerHour; - } - - public short getPulsesPerHour() { - return (short) (basalRateInHundredthUnitsPerHour * PULSES_PER_UNIT / 100); - } - - public short getNumberOfSlots() { - return (short) (endSlotIndex - startSlotIndex); - } - - @Override public String toString() { - return "Segment{" + - "startSlotIndex=" + startSlotIndex + - ", endSlotIndex=" + endSlotIndex + - ", basalRateInHundredthUnitsPerHour=" + basalRateInHundredthUnitsPerHour + - '}'; - } - } - - @Override public String toString() { - return "BasalProgram{" + - "segments=" + segments + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt new file mode 100644 index 0000000000..7d5ebddae3 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt @@ -0,0 +1,47 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +import java.util.* + +class BasalProgram(segments: List) { + + val segments: MutableList = segments.toMutableList() + get() = Collections.unmodifiableList(field) // TODO Adrian: moved method here + + fun addSegment(segment: Segment) { + segments.add(segment) + } + + fun hasZeroUnitSegments() = segments.any { it.basalRateInHundredthUnitsPerHour == 0 } + + fun isZeroBasal() = segments.sumBy(Segment::basalRateInHundredthUnitsPerHour) == 0 + + class Segment(val startSlotIndex: Short, val endSlotIndex: Short, val basalRateInHundredthUnitsPerHour: Int) { + + fun getPulsesPerHour(): Short { + return (basalRateInHundredthUnitsPerHour * PULSES_PER_UNIT / 100).toShort() + } + + fun getNumberOfSlots(): Short { + return (endSlotIndex - startSlotIndex).toShort() + } + + override fun toString(): String { + return "Segment{" + + "startSlotIndex=" + startSlotIndex + + ", endSlotIndex=" + endSlotIndex + + ", basalRateInHundredthUnitsPerHour=" + basalRateInHundredthUnitsPerHour + + '}' + } + + companion object { + + private const val PULSES_PER_UNIT: Byte = 20 + } + } + + override fun toString(): String { + return "BasalProgram{" + + "segments=" + segments + + '}' + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java deleted file mode 100644 index 2b290f96b5..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.java +++ /dev/null @@ -1,20 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -// FIXME names -public enum BeepRepetitionType { - XXX((byte) 0x01), // Used in low reservoir alert - XXX2((byte) 0x03), // Used in user pod expiration alert - XXX3((byte) 0x05), // Used in pod expiration alert - XXX4((byte) 0x06), // Used in imminent pod expiration alert - XXX5((byte) 0x08); // Used in lump of coal alert - - private byte value; - - BeepRepetitionType(byte value) { - this.value = value; - } - - public byte getValue() { - return value; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt new file mode 100644 index 0000000000..7464a676c0 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +// FIXME names +enum class BeepRepetitionType( // Used in lump of coal alert + val value: Byte) { + + XXX(0x01.toByte()), // Used in low reservoir alert + XXX2(0x03.toByte()), // Used in user pod expiration alert + XXX3(0x05.toByte()), // Used in pod expiration alert + XXX4(0x06.toByte()), // Used in imminent pod expiration alert + XXX5(0x08.toByte()); + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java deleted file mode 100644 index ee750df520..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.java +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum BeepType { - SILENT((byte) 0x00), - FOUR_TIMES_BIP_BEEP((byte) 0x02), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert - LONG_SINGLE_BEEP((byte) 0x06); // Used in stop delivery command - - private byte value; - - BeepType(byte value) { - this.value = value; - } - - public byte getValue() { - return value; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt new file mode 100644 index 0000000000..e72ef75b51 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class BeepType( // Used in stop delivery command + val value: Byte) { + + SILENT(0x00.toByte()), FOUR_TIMES_BIP_BEEP(0x02.toByte()), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert + LONG_SINGLE_BEEP(0x06.toByte()); +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java deleted file mode 100644 index 7dc9618fb5..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.java +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum DeliveryStatus { - SUSPENDED((byte) 0x00), - BASAL_ACTIVE((byte) 0x01), - TEMP_BASAL_ACTIVE((byte) 0x02), - PRIMING((byte) 0x04), - BOLUS_AND_BASAL_ACTIVE((byte) 0x05), - BOLUS_AND_TEMP_BASAL_ACTIVE((byte) 0x06), - UNKNOWN((byte) 0xff); - - private byte value; - - DeliveryStatus(byte value) { - this.value = value; - } - - public static DeliveryStatus byValue(byte value) { - for (DeliveryStatus status : values()) { - if (status.value == value) { - return status; - } - } - return UNKNOWN; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt new file mode 100644 index 0000000000..e80564a839 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class DeliveryStatus(private val value: Byte) { + SUSPENDED(0x00.toByte()), BASAL_ACTIVE(0x01.toByte()), TEMP_BASAL_ACTIVE(0x02.toByte()), PRIMING(0x04.toByte()), BOLUS_AND_BASAL_ACTIVE(0x05.toByte()), BOLUS_AND_TEMP_BASAL_ACTIVE(0x06.toByte()), UNKNOWN(0xff.toByte()); + + companion object { + + fun byValue(value: Byte): DeliveryStatus { + for (status in values()) { + if (status.value == value) { + return status + } + } + return UNKNOWN + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.java deleted file mode 100644 index d17d42050f..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.java +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public interface Encodable { - byte[] getEncoded(); -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt new file mode 100644 index 0000000000..28276e2abf --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +interface Encodable { + + val encoded: ByteArray +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java deleted file mode 100644 index d6482386ee..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.java +++ /dev/null @@ -1,49 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum NakErrorType { - FLASH_WRITE((byte) 0x01), - FLASH_ERASE((byte) 0x02), - FLASH_OPERATION((byte) 0x03), - FLASH_ADDR((byte) 0x04), - POD_STATE((byte) 0x05), - CRITICAL_VARIABLE((byte) 0x06), - ILLEGAL_PARAM((byte) 0x07), - BOLUS_CRITICAL_VAR((byte) 0x08), - INT_ILLEGAL_PARAM((byte) 0x09), - ILLEGAL_CHECKSUM((byte) 0x0a), - INVALID_MSG_LEN((byte) 0x0b), - PUMP_STATE((byte) 0x0c), - ILLEGAL_COMMAND((byte) 0x0d), - ILLEGAL_FILL_STATE((byte) 0x0e), - MAX_READWRITE_SIZE((byte) 0x0f), - ILLEGAL_READ_ADDRESS((byte) 0x10), - ILLEGAL_READ_MEM_TYPE((byte) 0x11), - INIT_POD((byte) 0x12), - ILLEGAL_CMD_STATE((byte) 0x13), - ILLEGAL_SECURITY_CODE((byte) 0x14), - POD_IN_ALARM((byte) 0x15), - COMD_NOT_SET((byte) 0x16), - ILLEGAL_RX_SENS_VALUE((byte) 0x17), - ILLEGAL_TX_PKT_SIZE((byte) 0x18), - OCCL_PARAMS_ALREADY_SET((byte) 0x19), - OCCL_PARAM((byte) 0x1a), - ILLEGAL_CDTHR_VALUE((byte) 0x1b), - IGNORE_COMMAND((byte) 0x1c), - INVALID_CRC((byte) 0x1d), - UNKNOWN((byte) 0xff); - - private byte value; - - NakErrorType(byte value) { - this.value = value; - } - - public static NakErrorType byValue(byte value) { - for (NakErrorType type : values()) { - if (type.value == value) { - return type; - } - } - return UNKNOWN; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt new file mode 100644 index 0000000000..08e4275d48 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class NakErrorType(private val value: Byte) { + FLASH_WRITE(0x01.toByte()), FLASH_ERASE(0x02.toByte()), FLASH_OPERATION(0x03.toByte()), FLASH_ADDR(0x04.toByte()), POD_STATE(0x05.toByte()), CRITICAL_VARIABLE(0x06.toByte()), ILLEGAL_PARAM(0x07.toByte()), BOLUS_CRITICAL_VAR(0x08.toByte()), INT_ILLEGAL_PARAM(0x09.toByte()), ILLEGAL_CHECKSUM(0x0a.toByte()), INVALID_MSG_LEN(0x0b.toByte()), PUMP_STATE(0x0c.toByte()), ILLEGAL_COMMAND(0x0d.toByte()), ILLEGAL_FILL_STATE(0x0e.toByte()), MAX_READWRITE_SIZE(0x0f.toByte()), ILLEGAL_READ_ADDRESS(0x10.toByte()), ILLEGAL_READ_MEM_TYPE(0x11.toByte()), INIT_POD(0x12.toByte()), ILLEGAL_CMD_STATE(0x13.toByte()), ILLEGAL_SECURITY_CODE(0x14.toByte()), POD_IN_ALARM(0x15.toByte()), COMD_NOT_SET(0x16.toByte()), ILLEGAL_RX_SENS_VALUE(0x17.toByte()), ILLEGAL_TX_PKT_SIZE(0x18.toByte()), OCCL_PARAMS_ALREADY_SET(0x19.toByte()), OCCL_PARAM(0x1a.toByte()), ILLEGAL_CDTHR_VALUE(0x1b.toByte()), IGNORE_COMMAND(0x1c.toByte()), INVALID_CRC(0x1d.toByte()), UNKNOWN(0xff.toByte()); + + companion object { + + fun byValue(value: Byte): NakErrorType { + for (type in values()) { + if (type.value == value) { + return type + } + } + return UNKNOWN + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.java deleted file mode 100644 index a6f78b06e4..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.java +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public class OmnipodEvent { - public enum OmnipodEventType { - CONNECTED, - ALREADY_CONNECTED, - FAILED_TO_CONNECT, - DISCONNECTED, - COMMAND_SENT, - GOT_POD_VERSION, - SET_UNIQUE_ID, - PRIMED_PUMP, - FINISHED_ACTIVATION_1, - PROGRAMMED_BASAL, - PROGRAMMED_ALERTS, - SET_BEEPS, - INSERTED_CANNULA, - FINISHED_ACTIVATION_2, - PROGRAMMED_TEMP_BASAL, - STARTED_BOLUS, - STOPPED_DELIVERY, - SILENCED_ALERTS, - DEACTIVATED, - COMMAND_SENDING, - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt new file mode 100644 index 0000000000..fb67205fad --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +class OmnipodEvent { + enum class OmnipodEventType { + CONNECTED, ALREADY_CONNECTED, FAILED_TO_CONNECT, DISCONNECTED, COMMAND_SENT, GOT_POD_VERSION, SET_UNIQUE_ID, PRIMED_PUMP, FINISHED_ACTIVATION_1, PROGRAMMED_BASAL, PROGRAMMED_ALERTS, SET_BEEPS, INSERTED_CANNULA, FINISHED_ACTIVATION_2, PROGRAMMED_TEMP_BASAL, STARTED_BOLUS, STOPPED_DELIVERY, SILENCED_ALERTS, DEACTIVATED, COMMAND_SENDING + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java deleted file mode 100644 index 88fb98b546..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.java +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public enum PodStatus { - UNINITIALIZED((byte) 0x00), - MFG_TEST((byte) 0x01), - FILLED((byte) 0x02), - UID_SET((byte) 0x03), - ENGAGING_CLUTCH_DRIVE((byte) 0x04), - CLUTCH_DRIVE_ENGAGED((byte) 0x05), - BASAL_PROGRAM_RUNNING((byte) 0x06), - PRIMING((byte) 0x07), - RUNNING_ABOVE_MIN_VOLUME((byte) 0x08), - RUNNING_BELOW_MIN_VOLUME((byte) 0x09), - UNUSED_10((byte) 0x0a), - UNUSED_11((byte) 0x0b), - UNUSED_12((byte) 0x0c), - ALARM((byte) 0x0d), - LUMP_OF_COAL((byte) 0x0e), - DEACTIVATED((byte) 0x0f), - UNKNOWN((byte) 0xff); - - private byte value; - - PodStatus(byte value) { - this.value = value; - } - - public static PodStatus byValue(byte value) { - for (PodStatus status : values()) { - if (status.value == value) { - return status; - } - } - return UNKNOWN; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt new file mode 100644 index 0000000000..f62c5560d0 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt @@ -0,0 +1,17 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class PodStatus(private val value: Byte) { + UNINITIALIZED(0x00.toByte()), MFG_TEST(0x01.toByte()), FILLED(0x02.toByte()), UID_SET(0x03.toByte()), ENGAGING_CLUTCH_DRIVE(0x04.toByte()), CLUTCH_DRIVE_ENGAGED(0x05.toByte()), BASAL_PROGRAM_RUNNING(0x06.toByte()), PRIMING(0x07.toByte()), RUNNING_ABOVE_MIN_VOLUME(0x08.toByte()), RUNNING_BELOW_MIN_VOLUME(0x09.toByte()), UNUSED_10(0x0a.toByte()), UNUSED_11(0x0b.toByte()), UNUSED_12(0x0c.toByte()), ALARM(0x0d.toByte()), LUMP_OF_COAL(0x0e.toByte()), DEACTIVATED(0x0f.toByte()), UNKNOWN(0xff.toByte()); + + companion object { + + fun byValue(value: Byte): PodStatus { + for (status in values()) { + if (status.value == value) { + return status + } + } + return UNKNOWN + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.java deleted file mode 100644 index 018986eb36..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.java +++ /dev/null @@ -1,19 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition; - -public class ProgramReminder implements Encodable { - private final boolean atStart; - private final boolean atEnd; - private final byte atInterval; - - public ProgramReminder(boolean atStart, boolean atEnd, byte atIntervalInMinutes) { - this.atStart = atStart; - this.atEnd = atEnd; - this.atInterval = atIntervalInMinutes; - } - - @Override public byte[] getEncoded() { - return new byte[]{(byte) (((this.atStart ? 1 : 0) << 7) - | ((this.atEnd ? 1 : 0) << 6) - | (this.atInterval & 0x3f))}; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt new file mode 100644 index 0000000000..732cfb9e09 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +import kotlin.experimental.and + +class ProgramReminder(private val atStart: Boolean, private val atEnd: Boolean, private val atInterval: Byte) : Encodable { + + override val encoded: ByteArray + get() = byteArrayOf(((if (atStart) 1 else 0) shl 7 + or ((if (atEnd) 1 else 0) shl 6) + or ((atInterval and 0x3f).toInt())).toByte()) +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.java deleted file mode 100644 index f36851f7d8..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -abstract class ActivationResponseBase extends ResponseBase { - final ResponseType.ActivationResponseType activationResponseType; - - ActivationResponseBase(ResponseType.ActivationResponseType activationResponseType, byte[] encoded) { - super(ResponseType.ACTIVATION_RESPONSE, encoded); - this.activationResponseType = activationResponseType; - } - - public ResponseType.ActivationResponseType getActivationResponseType() { - return activationResponseType; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt new file mode 100644 index 0000000000..52a680273e --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType + +abstract class ActivationResponseBase(val activationResponseType: ActivationResponseType, encoded: ByteArray) : ResponseBase(ResponseType.ACTIVATION_RESPONSE, encoded) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.java deleted file mode 100644 index efb356681e..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -public class AdditionalStatusResponseBase extends ResponseBase { - final ResponseType.AdditionalStatusResponseType statusResponseType; - - AdditionalStatusResponseBase(ResponseType.AdditionalStatusResponseType statusResponseType, byte[] encoded) { - super(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded); - this.statusResponseType = statusResponseType; - } - - public ResponseType.AdditionalStatusResponseType getStatusResponseType() { - return statusResponseType; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt new file mode 100644 index 0000000000..5db0f35b44 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.AdditionalStatusResponseType + +open class AdditionalStatusResponseBase internal constructor(val statusResponseType: AdditionalStatusResponseType, encoded: ByteArray) : ResponseBase(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.java deleted file mode 100644 index bb7ce23766..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.java +++ /dev/null @@ -1,240 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -public class AlarmStatusResponse extends AdditionalStatusResponseBase { - private final byte messageType; - private final short messageLength; - private final byte additionalStatusResponseType; - private final PodStatus podStatus; - private final DeliveryStatus deliveryStatus; - private final short bolusPulsesRemaining; - private final short sequenceNumberOfLastProgrammingCommand; - private final short totalPulsesDelivered; - private final AlarmType alarmType; - private final short alarmTime; - private final short reservoirPulsesRemaining; - private final short minutesSinceActivation; - private final boolean alert0Active; - private final boolean alert1Active; - private final boolean alert2Active; - private final boolean alert3Active; - private final boolean alert4Active; - private final boolean alert5Active; - private final boolean alert6Active; - private final boolean alert7Active; - private final boolean occlusionAlarm; - private final boolean pulseInfoInvalid; - private final PodStatus podStatusWhenAlarmOccurred; - private final boolean immediateBolusWhenAlarmOccurred; - private final byte occlusionType; - private final boolean occurredWhenFetchingImmediateBolusActiveInformation; - private final short rssi; - private final short receiverLowerGain; - private final PodStatus podStatusWhenAlarmOccurred2; - private final short returnAddressOfPodAlarmHandlerCaller; - - public AlarmStatusResponse(byte[] encoded) { - super(ResponseType.AdditionalStatusResponseType.ALARM_STATUS, encoded); - messageType = encoded[0]; - messageLength = (short) (encoded[1] & 0xff); - additionalStatusResponseType = encoded[2]; - podStatus = PodStatus.byValue((byte) (encoded[3] & 0x0f)); - deliveryStatus = DeliveryStatus.byValue((byte) (encoded[4] & 0x0f)); - bolusPulsesRemaining = (short) (ByteBuffer.wrap(new byte[]{encoded[5], encoded[6]}).getShort() & 2047); - sequenceNumberOfLastProgrammingCommand = (short) (encoded[7] & 0x0f); - totalPulsesDelivered = ByteBuffer.wrap(new byte[]{encoded[8], encoded[9]}).getShort(); - alarmType = AlarmType.byValue(encoded[10]); - alarmTime = ByteBuffer.wrap(new byte[]{encoded[11], encoded[12]}).getShort(); - reservoirPulsesRemaining = ByteBuffer.wrap(new byte[]{encoded[13], encoded[14]}).getShort(); - minutesSinceActivation = ByteBuffer.wrap(new byte[]{encoded[15], encoded[16]}).getShort(); - - byte activeAlerts = encoded[17]; - alert0Active = (activeAlerts & 1) == 1; - alert1Active = ((activeAlerts >>> 1) & 1) == 1; - alert2Active = ((activeAlerts >>> 2) & 1) == 1; - alert3Active = ((activeAlerts >>> 3) & 1) == 1; - alert4Active = ((activeAlerts >>> 4) & 1) == 1; - alert5Active = ((activeAlerts >>> 5) & 1) == 1; - alert6Active = ((activeAlerts >>> 6) & 1) == 1; - alert7Active = ((activeAlerts >>> 7) & 1) == 1; - - byte alarmFlags = encoded[18]; - occlusionAlarm = (alarmFlags & 1) == 1; - pulseInfoInvalid = ((alarmFlags >> 1) & 1) == 1; - - byte byte19 = encoded[19]; - byte byte20 = encoded[20]; - podStatusWhenAlarmOccurred = PodStatus.byValue((byte) (byte19 & 0x0f)); - immediateBolusWhenAlarmOccurred = ((byte19 >> 4) & 1) == 1; - occlusionType = (byte) ((byte19 >> 5) & 3); - occurredWhenFetchingImmediateBolusActiveInformation = ((byte19 >> 7) & 1) == 1; - rssi = (short) (byte20 & 0x3f); - receiverLowerGain = (short) ((byte20 >> 6) & 0x03); - podStatusWhenAlarmOccurred2 = PodStatus.byValue((byte) (encoded[21] & 0x0f)); - returnAddressOfPodAlarmHandlerCaller = ByteBuffer.wrap(new byte[]{encoded[22], encoded[23]}).getShort(); - } - - public byte getMessageType() { - return messageType; - } - - public short getMessageLength() { - return messageLength; - } - - public byte getAdditionalStatusResponseType() { - return additionalStatusResponseType; - } - - public PodStatus getPodStatus() { - return podStatus; - } - - public DeliveryStatus getDeliveryStatus() { - return deliveryStatus; - } - - public short getBolusPulsesRemaining() { - return bolusPulsesRemaining; - } - - public short getSequenceNumberOfLastProgrammingCommand() { - return sequenceNumberOfLastProgrammingCommand; - } - - public short getTotalPulsesDelivered() { - return totalPulsesDelivered; - } - - public AlarmType getAlarmType() { - return alarmType; - } - - public short getAlarmTime() { - return alarmTime; - } - - public short getReservoirPulsesRemaining() { - return reservoirPulsesRemaining; - } - - public short getMinutesSinceActivation() { - return minutesSinceActivation; - } - - public boolean isAlert0Active() { - return alert0Active; - } - - public boolean isAlert1Active() { - return alert1Active; - } - - public boolean isAlert2Active() { - return alert2Active; - } - - public boolean isAlert3Active() { - return alert3Active; - } - - public boolean isAlert4Active() { - return alert4Active; - } - - public boolean isAlert5Active() { - return alert5Active; - } - - public boolean isAlert6Active() { - return alert6Active; - } - - public boolean isAlert7Active() { - return alert7Active; - } - - public boolean isOcclusionAlarm() { - return occlusionAlarm; - } - - public boolean isPulseInfoInvalid() { - return pulseInfoInvalid; - } - - public PodStatus getPodStatusWhenAlarmOccurred() { - return podStatusWhenAlarmOccurred; - } - - public boolean isImmediateBolusWhenAlarmOccurred() { - return immediateBolusWhenAlarmOccurred; - } - - public byte getOcclusionType() { - return occlusionType; - } - - public boolean isOccurredWhenFetchingImmediateBolusActiveInformation() { - return occurredWhenFetchingImmediateBolusActiveInformation; - } - - public short getRssi() { - return rssi; - } - - public short getReceiverLowerGain() { - return receiverLowerGain; - } - - public PodStatus getPodStatusWhenAlarmOccurred2() { - return podStatusWhenAlarmOccurred2; - } - - public short getReturnAddressOfPodAlarmHandlerCaller() { - return returnAddressOfPodAlarmHandlerCaller; - } - - @Override public String toString() { - return "AlarmStatusResponse{" + - "messageType=" + messageType + - ", messageLength=" + messageLength + - ", additionalStatusResponseType=" + additionalStatusResponseType + - ", podStatus=" + podStatus + - ", deliveryStatus=" + deliveryStatus + - ", bolusPulsesRemaining=" + bolusPulsesRemaining + - ", sequenceNumberOfLastProgrammingCommand=" + sequenceNumberOfLastProgrammingCommand + - ", totalPulsesDelivered=" + totalPulsesDelivered + - ", alarmType=" + alarmType + - ", alarmTime=" + alarmTime + - ", reservoirPulsesRemaining=" + reservoirPulsesRemaining + - ", minutesSinceActivation=" + minutesSinceActivation + - ", alert0Active=" + alert0Active + - ", alert1Active=" + alert1Active + - ", alert2Active=" + alert2Active + - ", alert3Active=" + alert3Active + - ", alert4Active=" + alert4Active + - ", alert5Active=" + alert5Active + - ", alert6Active=" + alert6Active + - ", alert7Active=" + alert7Active + - ", occlusionAlarm=" + occlusionAlarm + - ", pulseInfoInvalid=" + pulseInfoInvalid + - ", podStatusWhenAlarmOccurred=" + podStatusWhenAlarmOccurred + - ", immediateBolusWhenAlarmOccurred=" + immediateBolusWhenAlarmOccurred + - ", occlusionType=" + occlusionType + - ", occurredWhenFetchingImmediateBolusActiveInformation=" + occurredWhenFetchingImmediateBolusActiveInformation + - ", rssi=" + rssi + - ", receiverLowerGain=" + receiverLowerGain + - ", podStatusWhenAlarmOccurred2=" + podStatusWhenAlarmOccurred2 + - ", returnAddressOfPodAlarmHandlerCaller=" + returnAddressOfPodAlarmHandlerCaller + - ", statusResponseType=" + statusResponseType + - ", responseType=" + responseType + - ", encoded=" + Arrays.toString(encoded) + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt new file mode 100644 index 0000000000..fcfdeec13d --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -0,0 +1,243 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.* +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.AdditionalStatusResponseType +import java.nio.ByteBuffer +import java.util.* +import kotlin.experimental.and + +class AlarmStatusResponse(encoded: ByteArray) : AdditionalStatusResponseBase(AdditionalStatusResponseType.ALARM_STATUS, encoded) { + + private val messageType: Byte + private val messageLength: Short + private val additionalStatusResponseType: Byte + private val podStatus: PodStatus + private val deliveryStatus: DeliveryStatus + private val bolusPulsesRemaining: Short + private val sequenceNumberOfLastProgrammingCommand: Short + private val totalPulsesDelivered: Short + private val alarmType: AlarmType + private val alarmTime: Short + private val reservoirPulsesRemaining: Short + private val minutesSinceActivation: Short + private val alert0Active: Boolean + private val alert1Active: Boolean + private val alert2Active: Boolean + private val alert3Active: Boolean + private val alert4Active: Boolean + private val alert5Active: Boolean + private val alert6Active: Boolean + private val alert7Active: Boolean + private val occlusionAlarm: Boolean + private val pulseInfoInvalid: Boolean + private val podStatusWhenAlarmOccurred: PodStatus + private val immediateBolusWhenAlarmOccurred: Boolean + private val occlusionType: Byte + private val occurredWhenFetchingImmediateBolusActiveInformation: Boolean + private val rssi: Short + private val receiverLowerGain: Short + private val podStatusWhenAlarmOccurred2: PodStatus + private val returnAddressOfPodAlarmHandlerCaller: Short + fun getMessageType(): Byte { + return messageType + } + + fun getMessageLength(): Short { + return messageLength + } + + fun getAdditionalStatusResponseType(): Byte { + return additionalStatusResponseType + } + + fun getPodStatus(): PodStatus { + return podStatus + } + + fun getDeliveryStatus(): DeliveryStatus { + return deliveryStatus + } + + fun getBolusPulsesRemaining(): Short { + return bolusPulsesRemaining + } + + fun getSequenceNumberOfLastProgrammingCommand(): Short { + return sequenceNumberOfLastProgrammingCommand + } + + fun getTotalPulsesDelivered(): Short { + return totalPulsesDelivered + } + + fun getAlarmType(): AlarmType { + return alarmType + } + + fun getAlarmTime(): Short { + return alarmTime + } + + fun getReservoirPulsesRemaining(): Short { + return reservoirPulsesRemaining + } + + fun getMinutesSinceActivation(): Short { + return minutesSinceActivation + } + + fun isAlert0Active(): Boolean { + return alert0Active + } + + fun isAlert1Active(): Boolean { + return alert1Active + } + + fun isAlert2Active(): Boolean { + return alert2Active + } + + fun isAlert3Active(): Boolean { + return alert3Active + } + + fun isAlert4Active(): Boolean { + return alert4Active + } + + fun isAlert5Active(): Boolean { + return alert5Active + } + + fun isAlert6Active(): Boolean { + return alert6Active + } + + fun isAlert7Active(): Boolean { + return alert7Active + } + + fun isOcclusionAlarm(): Boolean { + return occlusionAlarm + } + + fun isPulseInfoInvalid(): Boolean { + return pulseInfoInvalid + } + + fun getPodStatusWhenAlarmOccurred(): PodStatus { + return podStatusWhenAlarmOccurred + } + + fun isImmediateBolusWhenAlarmOccurred(): Boolean { + return immediateBolusWhenAlarmOccurred + } + + fun getOcclusionType(): Byte { + return occlusionType + } + + fun isOccurredWhenFetchingImmediateBolusActiveInformation(): Boolean { + return occurredWhenFetchingImmediateBolusActiveInformation + } + + fun getRssi(): Short { + return rssi + } + + fun getReceiverLowerGain(): Short { + return receiverLowerGain + } + + fun getPodStatusWhenAlarmOccurred2(): PodStatus { + return podStatusWhenAlarmOccurred2 + } + + fun getReturnAddressOfPodAlarmHandlerCaller(): Short { + return returnAddressOfPodAlarmHandlerCaller + } + + override fun toString(): String { + return "AlarmStatusResponse{" + + "messageType=" + messageType + + ", messageLength=" + messageLength + + ", additionalStatusResponseType=" + additionalStatusResponseType + + ", podStatus=" + podStatus + + ", deliveryStatus=" + deliveryStatus + + ", bolusPulsesRemaining=" + bolusPulsesRemaining + + ", sequenceNumberOfLastProgrammingCommand=" + sequenceNumberOfLastProgrammingCommand + + ", totalPulsesDelivered=" + totalPulsesDelivered + + ", alarmType=" + alarmType + + ", alarmTime=" + alarmTime + + ", reservoirPulsesRemaining=" + reservoirPulsesRemaining + + ", minutesSinceActivation=" + minutesSinceActivation + + ", alert0Active=" + alert0Active + + ", alert1Active=" + alert1Active + + ", alert2Active=" + alert2Active + + ", alert3Active=" + alert3Active + + ", alert4Active=" + alert4Active + + ", alert5Active=" + alert5Active + + ", alert6Active=" + alert6Active + + ", alert7Active=" + alert7Active + + ", occlusionAlarm=" + occlusionAlarm + + ", pulseInfoInvalid=" + pulseInfoInvalid + + ", podStatusWhenAlarmOccurred=" + podStatusWhenAlarmOccurred + + ", immediateBolusWhenAlarmOccurred=" + immediateBolusWhenAlarmOccurred + + ", occlusionType=" + occlusionType + + ", occurredWhenFetchingImmediateBolusActiveInformation=" + occurredWhenFetchingImmediateBolusActiveInformation + + ", rssi=" + rssi + + ", receiverLowerGain=" + receiverLowerGain + + ", podStatusWhenAlarmOccurred2=" + podStatusWhenAlarmOccurred2 + + ", returnAddressOfPodAlarmHandlerCaller=" + returnAddressOfPodAlarmHandlerCaller + + ", statusResponseType=" + statusResponseType + + ", responseType=" + responseType + + ", encoded=" + Arrays.toString(encoded) + + '}' + } + + init { + messageType = encoded[0] + messageLength = (encoded[1].toInt() and 0xff).toShort() + additionalStatusResponseType = encoded[2] + podStatus = PodStatus.byValue((encoded[3] and 0x0f)) + deliveryStatus = DeliveryStatus.Companion.byValue((encoded[4] and 0x0f)) + bolusPulsesRemaining = (ByteBuffer.wrap(byteArrayOf(encoded[5], encoded[6])).short and 2047) + sequenceNumberOfLastProgrammingCommand = (encoded[7] and 0x0f).toShort() + totalPulsesDelivered = ByteBuffer.wrap(byteArrayOf(encoded[8], encoded[9])).short + alarmType = AlarmType.Companion.byValue(encoded[10]) + alarmTime = ByteBuffer.wrap(byteArrayOf(encoded[11], encoded[12])).short + reservoirPulsesRemaining = ByteBuffer.wrap(byteArrayOf(encoded[13], encoded[14])).short + minutesSinceActivation = ByteBuffer.wrap(byteArrayOf(encoded[15], encoded[16])).short + val activeAlerts = encoded[17].toInt() // TODO: toInt()? + alert0Active = activeAlerts and 1 == 1 + alert1Active = activeAlerts ushr 1 and 1 == 1 + alert2Active = activeAlerts ushr 2 and 1 == 1 + alert3Active = activeAlerts ushr 3 and 1 == 1 + alert4Active = activeAlerts ushr 4 and 1 == 1 + alert5Active = activeAlerts ushr 5 and 1 == 1 + alert6Active = activeAlerts ushr 6 and 1 == 1 + alert7Active = activeAlerts ushr 7 and 1 == 1 + val alarmFlags = encoded[18] + occlusionAlarm = (alarmFlags.toInt() and 1) == 1 + pulseInfoInvalid = alarmFlags shr 1 and 1 == 1 + val byte19 = encoded[19] + val byte20 = encoded[20] + podStatusWhenAlarmOccurred = PodStatus.byValue((byte19 and 0x0f)) + immediateBolusWhenAlarmOccurred = byte19 shr 4 and 1 == 1 + occlusionType = ((byte19 shr 5 and 3).toByte()) + occurredWhenFetchingImmediateBolusActiveInformation = byte19 shr 7 and 1 == 1 + rssi = (byte20 and 0x3f).toShort() + receiverLowerGain = ((byte20 shr 6 and 0x03).toShort()) + podStatusWhenAlarmOccurred2 = PodStatus.byValue((encoded[21] and 0x0f)) + returnAddressOfPodAlarmHandlerCaller = ByteBuffer.wrap(byteArrayOf(encoded[22], encoded[23])).short + } + + //TODO autoconvert to Int ok? + private infix fun Byte.ushr(i: Int) = toInt() ushr i + private infix fun Short.shr(i: Int): Int = toInt() shr i + private infix fun Byte.shl(i: Int): Int = toInt() shl i + private infix fun Byte.shr(i: Int): Int = toInt() shr i + +} + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.java deleted file mode 100644 index bc448f18fb..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.java +++ /dev/null @@ -1,136 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import java.util.Arrays; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -public class DefaultStatusResponse extends ResponseBase { - private final byte messageType; - private final DeliveryStatus deliveryStatus; - private final PodStatus podStatus; - private final short totalPulsesDelivered; - private final short sequenceNumberOfLastProgrammingCommand; - private final short bolusPulsesRemaining; - private final boolean occlusionAlertActive; - private final boolean alert1Active; - private final boolean alert2Active; - private final boolean alert3Active; - private final boolean alert4Active; - private final boolean alert5Active; - private final boolean alert6Active; - private final boolean alert7Active; - private final short minutesSinceActivation; - private final short reservoirPulsesRemaining; - - public DefaultStatusResponse(byte[] encoded) { - super(ResponseType.DEFAULT_STATUS_RESPONSE, encoded); - - messageType = encoded[0]; - deliveryStatus = DeliveryStatus.byValue((byte) ((encoded[1] >> 4) & 0x0f)); - podStatus = PodStatus.byValue((byte) (encoded[1] & 0x0f)); - totalPulsesDelivered = (short) (((encoded[2] & 0x0f) << 12) | ((encoded[3] & 0xff) << 1) | ((encoded[4] & 0xff) >>> 7)); - sequenceNumberOfLastProgrammingCommand = (byte) ((encoded[4] >>> 3) & 0x0f); - bolusPulsesRemaining = (short) ((((encoded[4] & 0x07) << 10) | (encoded[5] & 0xff)) & 2047); - - short activeAlerts = (short) (((encoded[6] & 0xff) << 1) | (encoded[7] >>> 7)); - occlusionAlertActive = (activeAlerts & 1) == 1; - alert1Active = ((activeAlerts >> 1) & 1) == 1; - alert2Active = ((activeAlerts >> 2) & 1) == 1; - alert3Active = ((activeAlerts >> 3) & 1) == 1; - alert4Active = ((activeAlerts >> 4) & 1) == 1; - alert5Active = ((activeAlerts >> 5) & 1) == 1; - alert6Active = ((activeAlerts >> 6) & 1) == 1; - alert7Active = ((activeAlerts >> 7) & 1) == 1; - - minutesSinceActivation = (short) (((encoded[7] & 0x7f) << 6) | (((encoded[8] & 0xff) >>> 2) & 0x3f)); - reservoirPulsesRemaining = (short) (((encoded[8] << 8) | encoded[9]) & 0x3ff); - } - - public byte getMessageType() { - return messageType; - } - - public DeliveryStatus getDeliveryStatus() { - return deliveryStatus; - } - - public PodStatus getPodStatus() { - return podStatus; - } - - public short getTotalPulsesDelivered() { - return totalPulsesDelivered; - } - - public short getSequenceNumberOfLastProgrammingCommand() { - return sequenceNumberOfLastProgrammingCommand; - } - - public short getBolusPulsesRemaining() { - return bolusPulsesRemaining; - } - - public boolean isOcclusionAlertActive() { - return occlusionAlertActive; - } - - public boolean isAlert1Active() { - return alert1Active; - } - - public boolean isAlert2Active() { - return alert2Active; - } - - public boolean isAlert3Active() { - return alert3Active; - } - - public boolean isAlert4Active() { - return alert4Active; - } - - public boolean isAlert5Active() { - return alert5Active; - } - - public boolean isAlert6Active() { - return alert6Active; - } - - public boolean isAlert7Active() { - return alert7Active; - } - - public short getMinutesSinceActivation() { - return minutesSinceActivation; - } - - public short getReservoirPulsesRemaining() { - return reservoirPulsesRemaining; - } - - @Override public String toString() { - return "DefaultStatusResponse{" + - "messageType=" + messageType + - ", deliveryStatus=" + deliveryStatus + - ", podStatus=" + podStatus + - ", totalPulsesDelivered=" + totalPulsesDelivered + - ", sequenceNumberOfLastProgrammingCommand=" + sequenceNumberOfLastProgrammingCommand + - ", bolusPulsesRemaining=" + bolusPulsesRemaining + - ", occlusionAlertActive=" + occlusionAlertActive + - ", alert1Active=" + alert1Active + - ", alert2Active=" + alert2Active + - ", alert3Active=" + alert3Active + - ", alert4Active=" + alert4Active + - ", alert5Active=" + alert5Active + - ", alert6Active=" + alert6Active + - ", alert7Active=" + alert7Active + - ", minutesSinceActivation=" + minutesSinceActivation + - ", reservoirPulsesRemaining=" + reservoirPulsesRemaining + - ", responseType=" + responseType + - ", encoded=" + Arrays.toString(encoded) + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt new file mode 100644 index 0000000000..33aa3b90e3 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt @@ -0,0 +1,118 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import kotlin.experimental.and + +class DefaultStatusResponse(encoded: ByteArray) : ResponseBase(ResponseType.DEFAULT_STATUS_RESPONSE, encoded) { + + // TODO: Here is a lot of bitshifting that had to be changed. we should go over it. + private val messageType: Byte = encoded[0] + private val deliveryStatus: DeliveryStatus = DeliveryStatus.byValue((encoded[1].toInt() shr 4 and 0x0f).toByte()) + private val podStatus: PodStatus = PodStatus.Companion.byValue((encoded[1] and 0x0f) as Byte) + private val totalPulsesDelivered: Short = ((encoded[2] and 0x0f shl 12 or (encoded[3].toInt() and 0xff shl 1) or (encoded[4].toInt() and 0xff ushr 7)).toShort()) + private val sequenceNumberOfLastProgrammingCommand: Short = (encoded[4] ushr 3 and 0x0f).toShort() + private val bolusPulsesRemaining: Short = ((encoded[4] and 0x07 shl 10 or (encoded[5].toInt() and 0xff) and 2047).toShort()) + private val activeAlerts = (encoded[6].toInt() and 0xff shl 1 or (encoded[7] ushr 7)).toShort() + private val occlusionAlertActive: Boolean = (activeAlerts and 1).toInt() == 1 + private val alert1Active: Boolean = activeAlerts shr 1 and 1 == 1 + private val alert2Active: Boolean = activeAlerts shr 2 and 1 == 1 + private val alert3Active: Boolean = activeAlerts shr 3 and 1 == 1 + private val alert4Active: Boolean = activeAlerts shr 4 and 1 == 1 + private val alert5Active: Boolean = activeAlerts shr 5 and 1 == 1 + private val alert6Active: Boolean = activeAlerts shr 6 and 1 == 1 + private val alert7Active: Boolean = activeAlerts shr 7 and 1 == 1 + private val minutesSinceActivation: Short = (encoded[7] and 0x7f shl 6 or (encoded[8].toInt() and 0xff ushr 2 and 0x3f)).toShort() + private val reservoirPulsesRemaining: Short = (encoded[8] shl 8 or encoded[9].toInt() and 0x3ff).toShort() + fun getMessageType(): Byte { + return messageType + } + + fun getDeliveryStatus(): DeliveryStatus { + return deliveryStatus + } + + fun getPodStatus(): PodStatus { + return podStatus + } + + fun getTotalPulsesDelivered(): Short { + return totalPulsesDelivered + } + + fun getSequenceNumberOfLastProgrammingCommand(): Short { + return sequenceNumberOfLastProgrammingCommand + } + + fun getBolusPulsesRemaining(): Short { + return bolusPulsesRemaining + } + + fun isOcclusionAlertActive(): Boolean { + return occlusionAlertActive + } + + fun isAlert1Active(): Boolean { + return alert1Active + } + + fun isAlert2Active(): Boolean { + return alert2Active + } + + fun isAlert3Active(): Boolean { + return alert3Active + } + + fun isAlert4Active(): Boolean { + return alert4Active + } + + fun isAlert5Active(): Boolean { + return alert5Active + } + + fun isAlert6Active(): Boolean { + return alert6Active + } + + fun isAlert7Active(): Boolean { + return alert7Active + } + + fun getMinutesSinceActivation(): Short { + return minutesSinceActivation + } + + fun getReservoirPulsesRemaining(): Short { + return reservoirPulsesRemaining + } + + override fun toString(): String { + return "DefaultStatusResponse{" + + "messageType=" + messageType + + ", deliveryStatus=" + deliveryStatus + + ", podStatus=" + podStatus + + ", totalPulsesDelivered=" + totalPulsesDelivered + + ", sequenceNumberOfLastProgrammingCommand=" + sequenceNumberOfLastProgrammingCommand + + ", bolusPulsesRemaining=" + bolusPulsesRemaining + + ", occlusionAlertActive=" + occlusionAlertActive + + ", alert1Active=" + alert1Active + + ", alert2Active=" + alert2Active + + ", alert3Active=" + alert3Active + + ", alert4Active=" + alert4Active + + ", alert5Active=" + alert5Active + + ", alert6Active=" + alert6Active + + ", alert7Active=" + alert7Active + + ", minutesSinceActivation=" + minutesSinceActivation + + ", reservoirPulsesRemaining=" + reservoirPulsesRemaining + + ", responseType=" + responseType + + ", encoded=" + encoded.contentToString() + + '}' + } +} + +//TODO autoconvert to Int ok? +private infix fun Byte.ushr(i: Int) = toInt() ushr i +private infix fun Short.shr(i: Int): Int = toInt() shr i +private infix fun Byte.shl(i: Int): Int = toInt() shl i diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.java deleted file mode 100644 index 8b55189ebe..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.java +++ /dev/null @@ -1,71 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import java.util.Arrays; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -public class NakResponse extends ResponseBase { - private final byte messageType; - private final short messageLength; - private final NakErrorType nakErrorType; - private final AlarmType alarmType; - private final PodStatus podStatus; - private final short securityNakSyncCount; - - public NakResponse(byte[] encoded) { - super(ResponseType.NAK_RESPONSE, encoded); - this.messageType = encoded[0]; - this.messageLength = encoded[1]; - this.nakErrorType = NakErrorType.byValue(encoded[2]); - byte byte3 = encoded[3]; - byte byte4 = encoded[4]; - if (nakErrorType == NakErrorType.ILLEGAL_SECURITY_CODE) { - this.securityNakSyncCount = (short) ((byte3 << 8) | byte4); - this.alarmType = null; - this.podStatus = null; - } else { - this.securityNakSyncCount = 0; - this.alarmType = AlarmType.byValue(byte3); - this.podStatus = PodStatus.byValue(byte4); - } - } - - public byte getMessageType() { - return messageType; - } - - public short getMessageLength() { - return messageLength; - } - - public NakErrorType getNakErrorType() { - return nakErrorType; - } - - public AlarmType getAlarmType() { - return alarmType; - } - - public PodStatus getPodStatus() { - return podStatus; - } - - public short getSecurityNakSyncCount() { - return securityNakSyncCount; - } - - @Override public String toString() { - return "NakResponse{" + - "messageType=" + messageType + - ", messageLength=" + messageLength + - ", nakErrorType=" + nakErrorType + - ", alarmType=" + alarmType + - ", podStatus=" + podStatus + - ", securityNakSyncCount=" + securityNakSyncCount + - ", responseType=" + responseType + - ", encoded=" + Arrays.toString(encoded) + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt new file mode 100644 index 0000000000..0c2f8940fc --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt @@ -0,0 +1,69 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import java.util.* + +class NakResponse(encoded: ByteArray) : ResponseBase(ResponseType.NAK_RESPONSE, encoded) { + + private val messageType: Byte // TODO directly assign here + private val messageLength: Short + private val nakErrorType: NakErrorType + private var alarmType: AlarmType? = null + private var podStatus: PodStatus? = null + private var securityNakSyncCount: Short = 0 + fun getMessageType(): Byte { + return messageType + } + + fun getMessageLength(): Short { + return messageLength + } + + fun getNakErrorType(): NakErrorType { // TODO make public, a val cannot be reassigned, same for other Responses + return nakErrorType + } + + fun getAlarmType(): AlarmType? { + return alarmType + } + + fun getPodStatus(): PodStatus? { + return podStatus + } + + fun getSecurityNakSyncCount(): Short { + return securityNakSyncCount + } + + override fun toString(): String { + return "NakResponse{" + + "messageType=" + messageType + + ", messageLength=" + messageLength + + ", nakErrorType=" + nakErrorType + + ", alarmType=" + alarmType + + ", podStatus=" + podStatus + + ", securityNakSyncCount=" + securityNakSyncCount + + ", responseType=" + responseType + + ", encoded=" + encoded.contentToString() + + '}' + } + + init { + messageType = encoded[0] + messageLength = encoded[1].toShort() + nakErrorType = NakErrorType.Companion.byValue(encoded[2]) + val byte3 = encoded[3] + val byte4 = encoded[4] + if (nakErrorType == NakErrorType.ILLEGAL_SECURITY_CODE) { + securityNakSyncCount = ((byte3.toInt() shl 8 or byte4.toInt()).toShort()) // TODO: toInt() + alarmType = null + podStatus = null + } else { + securityNakSyncCount = 0 + alarmType = AlarmType.byValue(byte3) + podStatus = PodStatus.byValue(byte4) + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.java deleted file mode 100644 index e4edf3f4ba..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.java +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -public interface Response { - ResponseType getResponseType(); - - byte[] getEncoded(); -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt new file mode 100644 index 0000000000..82b368b60b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +interface Response { + + val responseType: ResponseType + val encoded: ByteArray +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.java deleted file mode 100644 index bb43dcf4dc..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import java.util.Arrays; - -abstract class ResponseBase implements Response { - final ResponseType responseType; - final byte[] encoded; - - ResponseBase(ResponseType responseType, byte[] encoded) { - this.responseType = responseType; - this.encoded = Arrays.copyOf(encoded, encoded.length); - } - - @Override public ResponseType getResponseType() { - return responseType; - } - - @Override - public byte[] getEncoded() { - return encoded; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt new file mode 100644 index 0000000000..07b99e5b8e --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +abstract class ResponseBase(override val responseType: ResponseType, encoded: ByteArray) : Response { + + override val encoded: ByteArray = encoded.copyOf(encoded.size) + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java deleted file mode 100644 index 384ae11c0e..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.java +++ /dev/null @@ -1,80 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -public enum ResponseType { - ACTIVATION_RESPONSE((byte) 0x01), - DEFAULT_STATUS_RESPONSE((byte) 0x1d), - ADDITIONAL_STATUS_RESPONSE((byte) 0x02), - NAK_RESPONSE((byte) 0x06), - UNKNOWN((byte) 0xff); - - private byte value; - - ResponseType(byte value) { - this.value = value; - } - - public byte getValue() { - return value; - } - - public static ResponseType byValue(byte value) { - for (ResponseType type : values()) { - if (type.value == value) { - return type; - } - } - return UNKNOWN; - } - - enum AdditionalStatusResponseType { - STATUS_RESPONSE_PAGE_1((byte) 0x01), - ALARM_STATUS((byte) 0x02), - STATUS_RESPONSE_PAGE_3((byte) 0x03), - STATUS_RESPONSE_PAGE_5((byte) 0x05), - STATUS_RESPONSE_PAGE_6((byte) 0x06), - STATUS_RESPONSE_PAGE_70((byte) 0x46), - STATUS_RESPONSE_PAGE_80((byte) 0x50), - STATUS_RESPONSE_PAGE_81((byte) 0x51), - UNKNOWN((byte) 0xff); - - private byte value; - - AdditionalStatusResponseType(byte value) { - this.value = value; - } - - public static AdditionalStatusResponseType byValue(byte value) { - for (AdditionalStatusResponseType type : values()) { - if (type.value == value) { - return type; - } - } - return UNKNOWN; - } - - public byte getValue() { - return value; - } - } - - enum ActivationResponseType { - GET_VERSION_RESPONSE((byte) 0x15), - SET_UNIQUE_ID_RESPONSE((byte) 0x1b), - UNKNOWN((byte) 0xff); - - private byte length; - - ActivationResponseType(byte length) { - this.length = length; - } - - public static ActivationResponseType byLength(byte length) { - for (ActivationResponseType type : values()) { - if (type.length == length) { - return type; - } - } - return UNKNOWN; - } - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt new file mode 100644 index 0000000000..2aad1ae23c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt @@ -0,0 +1,57 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +enum class ResponseType(private val value: Byte) { + ACTIVATION_RESPONSE(0x01.toByte()), DEFAULT_STATUS_RESPONSE(0x1d.toByte()), ADDITIONAL_STATUS_RESPONSE(0x02.toByte()), NAK_RESPONSE(0x06.toByte()), UNKNOWN(0xff.toByte()); + + fun getValue(): Byte { + return value + } + + enum class AdditionalStatusResponseType(private val value: Byte) { + STATUS_RESPONSE_PAGE_1(0x01.toByte()), ALARM_STATUS(0x02.toByte()), STATUS_RESPONSE_PAGE_3(0x03.toByte()), STATUS_RESPONSE_PAGE_5(0x05.toByte()), STATUS_RESPONSE_PAGE_6(0x06.toByte()), STATUS_RESPONSE_PAGE_70(0x46.toByte()), STATUS_RESPONSE_PAGE_80(0x50.toByte()), STATUS_RESPONSE_PAGE_81(0x51.toByte()), UNKNOWN(0xff.toByte()); + + fun getValue(): Byte { + return value + } + + companion object { + + fun byValue(value: Byte): AdditionalStatusResponseType { + for (type in values()) { + if (type.value == value) { + return type + } + } + return UNKNOWN + } + } + } + + enum class ActivationResponseType(private val length: Byte) { + GET_VERSION_RESPONSE(0x15.toByte()), SET_UNIQUE_ID_RESPONSE(0x1b.toByte()), UNKNOWN(0xff.toByte()); + + companion object { + + fun byLength(length: Byte): ActivationResponseType { + for (type in values()) { + if (type.length == length) { + return type + } + } + return UNKNOWN + } + } + } + + companion object { + + fun byValue(value: Byte): ResponseType { + for (type in values()) { + if (type.value == value) { + return type + } + } + return UNKNOWN + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java deleted file mode 100644 index 2c0703258a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.java +++ /dev/null @@ -1,155 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -public final class SetUniqueIdResponse extends ActivationResponseBase { - private byte messageType; - private short messageLength; - private short pulseVolumeInTenThousandthMicroLiter; - private short pumpRate; - private short primePumpRate; - private short numberOfEngagingClutchDrivePulses; - private short numberOfPrimePulses; - private short podExpirationTimeInHours; - private short firmwareVersionMajor; - private short firmwareVersionMinor; - private short firmwareVersionInterim; - private short bleVersionMajor; - private short bleVersionMinor; - private short bleVersionInterim; - private short productId; - private PodStatus podStatus; - private long lotNumber; - private long podSequenceNumber; - private long uniqueIdReceivedInCommand; - - public SetUniqueIdResponse(byte[] encoded) { - super(ResponseType.ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded); - - messageType = encoded[0]; - messageLength = (short) (encoded[1] & 0xff); - pulseVolumeInTenThousandthMicroLiter = ByteBuffer.wrap(new byte[]{encoded[2], encoded[3]}).getShort(); - pumpRate = (short) (encoded[4] & 0xff); - primePumpRate = (short) (encoded[5] & 0xff); - numberOfEngagingClutchDrivePulses = (short) (encoded[6] & 0xff); - numberOfPrimePulses = (short) (encoded[7] & 0xff); - podExpirationTimeInHours = (short) (encoded[8] & 0xff); - firmwareVersionMajor = (short) (encoded[9] & 0xff); - firmwareVersionMinor = (short) (encoded[10] & 0xff); - firmwareVersionInterim = (short) (encoded[11] & 0xff); - bleVersionMajor = (short) (encoded[12] & 0xff); - bleVersionMinor = (short) (encoded[13] & 0xff); - bleVersionInterim = (short) (encoded[14] & 0xff); - productId = (short) (encoded[15] & 0xff); - podStatus = PodStatus.byValue(encoded[16]); - lotNumber = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20]}).getLong(); - podSequenceNumber = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24]}).getLong(); - uniqueIdReceivedInCommand = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, encoded[25], encoded[26], encoded[27], encoded[28]}).getLong(); - } - - public byte getMessageType() { - return messageType; - } - - public short getMessageLength() { - return messageLength; - } - - public short getPulseVolumeInTenThousandthMicroLiter() { - return pulseVolumeInTenThousandthMicroLiter; - } - - public short getDeliveryRate() { - return pumpRate; - } - - public short getPrimeRate() { - return primePumpRate; - } - - public short getNumberOfEngagingClutchDrivePulses() { - return numberOfEngagingClutchDrivePulses; - } - - public short getNumberOfPrimePulses() { - return numberOfPrimePulses; - } - - public short getPodExpirationTimeInHours() { - return podExpirationTimeInHours; - } - - public short getFirmwareVersionMajor() { - return firmwareVersionMajor; - } - - public short getFirmwareVersionMinor() { - return firmwareVersionMinor; - } - - public short getFirmwareVersionInterim() { - return firmwareVersionInterim; - } - - public short getBleVersionMajor() { - return bleVersionMajor; - } - - public short getBleVersionMinor() { - return bleVersionMinor; - } - - public short getBleVersionInterim() { - return bleVersionInterim; - } - - public short getProductId() { - return productId; - } - - public PodStatus getPodStatus() { - return podStatus; - } - - public long getLotNumber() { - return lotNumber; - } - - public long getPodSequenceNumber() { - return podSequenceNumber; - } - - public long getUniqueIdReceivedInCommand() { - return uniqueIdReceivedInCommand; - } - - @Override public String toString() { - return "SetUniqueIdResponse{" + - "messageType=" + messageType + - ", messageLength=" + messageLength + - ", pulseVolume=" + pulseVolumeInTenThousandthMicroLiter + - ", pumpRate=" + pumpRate + - ", primePumpRate=" + primePumpRate + - ", numberOfEngagingClutchDrivePulses=" + numberOfEngagingClutchDrivePulses + - ", numberOfPrimePulses=" + numberOfPrimePulses + - ", podExpirationTimeInHours=" + podExpirationTimeInHours + - ", softwareVersionMajor=" + firmwareVersionMajor + - ", softwareVersionMinor=" + firmwareVersionMinor + - ", softwareVersionInterim=" + firmwareVersionInterim + - ", bleVersionMajor=" + bleVersionMajor + - ", bleVersionMinor=" + bleVersionMinor + - ", bleVersionInterim=" + bleVersionInterim + - ", productId=" + productId + - ", podStatus=" + podStatus + - ", lotNumber=" + lotNumber + - ", podSequenceNumber=" + podSequenceNumber + - ", uniqueIdReceivedInCommand=" + uniqueIdReceivedInCommand + - ", activationResponseType=" + activationResponseType + - ", responseType=" + responseType + - ", encoded=" + Arrays.toString(encoded) + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt new file mode 100644 index 0000000000..d559043ac2 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt @@ -0,0 +1,154 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType +import java.nio.ByteBuffer +import java.util.* +import kotlin.experimental.and + +class SetUniqueIdResponse(encoded: ByteArray) : ActivationResponseBase(ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded) { + + private val messageType: Byte // TODO directly assign here + private val messageLength: Short + private val pulseVolumeInTenThousandthMicroLiter: Short + private val pumpRate: Short + private val primePumpRate: Short + private val numberOfEngagingClutchDrivePulses: Short + private val numberOfPrimePulses: Short + private val podExpirationTimeInHours: Short + private val firmwareVersionMajor: Short + private val firmwareVersionMinor: Short + private val firmwareVersionInterim: Short + private val bleVersionMajor: Short + private val bleVersionMinor: Short + private val bleVersionInterim: Short + private val productId: Short + private val podStatus: PodStatus + private val lotNumber: Long + private val podSequenceNumber: Long + private val uniqueIdReceivedInCommand: Long + fun getMessageType(): Byte { + return messageType + } + + fun getMessageLength(): Short { // TODO value getters + return messageLength + } + + fun getPulseVolumeInTenThousandthMicroLiter(): Short { + return pulseVolumeInTenThousandthMicroLiter + } + + fun getDeliveryRate(): Short { + return pumpRate + } + + fun getPrimeRate(): Short { + return primePumpRate + } + + fun getNumberOfEngagingClutchDrivePulses(): Short { + return numberOfEngagingClutchDrivePulses + } + + fun getNumberOfPrimePulses(): Short { + return numberOfPrimePulses + } + + fun getPodExpirationTimeInHours(): Short { + return podExpirationTimeInHours + } + + fun getFirmwareVersionMajor(): Short { + return firmwareVersionMajor + } + + fun getFirmwareVersionMinor(): Short { + return firmwareVersionMinor + } + + fun getFirmwareVersionInterim(): Short { + return firmwareVersionInterim + } + + fun getBleVersionMajor(): Short { + return bleVersionMajor + } + + fun getBleVersionMinor(): Short { + return bleVersionMinor + } + + fun getBleVersionInterim(): Short { + return bleVersionInterim + } + + fun getProductId(): Short { + return productId + } + + fun getPodStatus(): PodStatus { + return podStatus + } + + fun getLotNumber(): Long { + return lotNumber + } + + fun getPodSequenceNumber(): Long { + return podSequenceNumber + } + + fun getUniqueIdReceivedInCommand(): Long { + return uniqueIdReceivedInCommand + } + + override fun toString(): String { + return "SetUniqueIdResponse{" + + "messageType=" + messageType + + ", messageLength=" + messageLength + + ", pulseVolume=" + pulseVolumeInTenThousandthMicroLiter + + ", pumpRate=" + pumpRate + + ", primePumpRate=" + primePumpRate + + ", numberOfEngagingClutchDrivePulses=" + numberOfEngagingClutchDrivePulses + + ", numberOfPrimePulses=" + numberOfPrimePulses + + ", podExpirationTimeInHours=" + podExpirationTimeInHours + + ", softwareVersionMajor=" + firmwareVersionMajor + + ", softwareVersionMinor=" + firmwareVersionMinor + + ", softwareVersionInterim=" + firmwareVersionInterim + + ", bleVersionMajor=" + bleVersionMajor + + ", bleVersionMinor=" + bleVersionMinor + + ", bleVersionInterim=" + bleVersionInterim + + ", productId=" + productId + + ", podStatus=" + podStatus + + ", lotNumber=" + lotNumber + + ", podSequenceNumber=" + podSequenceNumber + + ", uniqueIdReceivedInCommand=" + uniqueIdReceivedInCommand + + ", activationResponseType=" + activationResponseType + + ", responseType=" + responseType + + ", encoded=" + encoded.contentToString() + + '}' + } + + init { + messageType = encoded[0] + messageLength = (encoded[1].toInt() and 0xff) .toShort() + pulseVolumeInTenThousandthMicroLiter = ByteBuffer.wrap(byteArrayOf(encoded[2], encoded[3])).short + pumpRate = (encoded[4].toInt() and 0xff) .toShort() + primePumpRate = (encoded[5].toInt() and 0xff) .toShort() + numberOfEngagingClutchDrivePulses = (encoded[6].toInt() and 0xff) .toShort() + numberOfPrimePulses = (encoded[7].toInt() and 0xff) .toShort() + podExpirationTimeInHours = (encoded[8].toInt() and 0xff) .toShort() + firmwareVersionMajor = (encoded[9].toInt() and 0xff) .toShort() + firmwareVersionMinor = (encoded[10].toInt() and 0xff) .toShort() + firmwareVersionInterim = (encoded[11].toInt() and 0xff) .toShort() + bleVersionMajor = (encoded[12].toInt() and 0xff) .toShort() + bleVersionMinor = (encoded[13].toInt() and 0xff) .toShort() + bleVersionInterim = (encoded[14].toInt() and 0xff) .toShort() + productId = (encoded[15].toInt() and 0xff) .toShort() + podStatus = PodStatus.byValue(encoded[16]) + lotNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20])).long + podSequenceNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24])).long + uniqueIdReceivedInCommand = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[25], encoded[26], encoded[27], encoded[28])).long + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.java deleted file mode 100644 index 8f3c2e2be8..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.java +++ /dev/null @@ -1,128 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -public final class VersionResponse extends ActivationResponseBase { - - private final byte messageType; - private final short messageLength; - private final short firmwareVersionMajor; - private final short firmwareVersionMinor; - private final short firmwareVersionInterim; - private final short bleVersionMajor; - private final short bleVersionMinor; - private final short bleVersionInterim; - private final short productId; - private final PodStatus podStatus; - private final long lotNumber; - private final long podSequenceNumber; - private final byte rssi; - private final byte receiverLowerGain; - private final long uniqueIdReceivedInCommand; - - public VersionResponse(byte[] encoded) { - super(ResponseType.ActivationResponseType.GET_VERSION_RESPONSE, encoded); - - messageType = encoded[0]; - messageLength = (short) (encoded[1] & 0xff); - firmwareVersionMajor = (short) (encoded[2] & 0xff); - firmwareVersionMinor = (short) (encoded[3] & 0xff); - firmwareVersionInterim = (short) (encoded[4] & 0xff); - bleVersionMajor = (short) (encoded[5] & 0xff); - bleVersionMinor = (short) (encoded[6] & 0xff); - bleVersionInterim = (short) (encoded[7] & 0xff); - productId = (short) (encoded[8] & 0xff); - podStatus = PodStatus.byValue((byte) (encoded[9] & 0xf)); - lotNumber = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, encoded[10], encoded[11], encoded[12], encoded[13]}).getLong(); - podSequenceNumber = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, encoded[14], encoded[15], encoded[16], encoded[17]}).getLong(); - rssi = (byte) (encoded[18] & 0x3f); - receiverLowerGain = (byte) ((encoded[18] >> 6) & 0x03); - uniqueIdReceivedInCommand = ByteBuffer.wrap(new byte[]{0, 0, 0, 0, encoded[19], encoded[20], encoded[21], encoded[22]}).getLong(); - } - - public byte getMessageType() { - return messageType; - } - - public short getMessageLength() { - return messageLength; - } - - public short getFirmwareVersionMajor() { - return firmwareVersionMajor; - } - - public short getFirmwareVersionMinor() { - return firmwareVersionMinor; - } - - public short getFirmwareVersionInterim() { - return firmwareVersionInterim; - } - - public short getBleVersionMajor() { - return bleVersionMajor; - } - - public short getBleVersionMinor() { - return bleVersionMinor; - } - - public short getBleVersionInterim() { - return bleVersionInterim; - } - - public short getProductId() { - return productId; - } - - public PodStatus getPodStatus() { - return podStatus; - } - - public long getLotNumber() { - return lotNumber; - } - - public long getPodSequenceNumber() { - return podSequenceNumber; - } - - public byte getRssi() { - return rssi; - } - - public byte getReceiverLowerGain() { - return receiverLowerGain; - } - - public long getUniqueIdReceivedInCommand() { - return uniqueIdReceivedInCommand; - } - - @Override public String toString() { - return "VersionResponse{" + - "messageType=" + messageType + - ", messageLength=" + messageLength + - ", firmwareVersionMajor=" + firmwareVersionMajor + - ", firmwareVersionMinor=" + firmwareVersionMinor + - ", firmwareVersionInterim=" + firmwareVersionInterim + - ", bleVersionMajor=" + bleVersionMajor + - ", bleVersionMinor=" + bleVersionMinor + - ", bleVersionInterim=" + bleVersionInterim + - ", productId=" + productId + - ", podStatus=" + podStatus + - ", lotNumber=" + lotNumber + - ", podSequenceNumber=" + podSequenceNumber + - ", rssi=" + rssi + - ", receiverLowerGain=" + receiverLowerGain + - ", uniqueIdReceivedInCommand=" + uniqueIdReceivedInCommand + - ", activationResponseType=" + activationResponseType + - ", responseType=" + responseType + - ", encoded=" + Arrays.toString(encoded) + - '}'; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt new file mode 100644 index 0000000000..6108ccf2b1 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt @@ -0,0 +1,109 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType +import java.nio.ByteBuffer +import java.util.* +import kotlin.experimental.and + +class VersionResponse(encoded: ByteArray) : ActivationResponseBase(ActivationResponseType.GET_VERSION_RESPONSE, encoded) { + + private val messageType: Byte = encoded[0] + private val messageLength: Short = (encoded[1].toInt() and 0xff) .toShort() + private val firmwareVersionMajor: Short = (encoded[2].toInt() and 0xff) .toShort() + private val firmwareVersionMinor: Short = (encoded[3].toInt() and 0xff) .toShort() + private val firmwareVersionInterim: Short = (encoded[4].toInt() and 0xff) .toShort() + private val bleVersionMajor: Short = (encoded[5].toInt() and 0xff) .toShort() + private val bleVersionMinor: Short = (encoded[6].toInt() and 0xff) .toShort() + private val bleVersionInterim: Short = (encoded[7].toInt() and 0xff) .toShort() + private val productId: Short = (encoded[8].toInt() and 0xff) .toShort() + private val podStatus: PodStatus = PodStatus.byValue((encoded[9] and 0xf)) + private val lotNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[10], encoded[11], encoded[12], encoded[13])).long + private val podSequenceNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[14], encoded[15], encoded[16], encoded[17])).long + private val rssi: Byte = (encoded[18] and 0x3f) + private val receiverLowerGain: Byte = ((encoded[18].toInt() shr 6 and 0x03).toByte()) + private val uniqueIdReceivedInCommand: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[19], encoded[20], encoded[21], encoded[22])).long + fun getMessageType(): Byte { + return messageType + } + + fun getMessageLength(): Short { + return messageLength + } + + fun getFirmwareVersionMajor(): Short { + return firmwareVersionMajor + } + + fun getFirmwareVersionMinor(): Short { + return firmwareVersionMinor + } + + fun getFirmwareVersionInterim(): Short { + return firmwareVersionInterim + } + + fun getBleVersionMajor(): Short { + return bleVersionMajor + } + + fun getBleVersionMinor(): Short { + return bleVersionMinor + } + + fun getBleVersionInterim(): Short { + return bleVersionInterim + } + + fun getProductId(): Short { + return productId + } + + fun getPodStatus(): PodStatus { + return podStatus + } + + fun getLotNumber(): Long { + return lotNumber + } + + fun getPodSequenceNumber(): Long { + return podSequenceNumber + } + + fun getRssi(): Byte { + return rssi + } + + fun getReceiverLowerGain(): Byte { + return receiverLowerGain + } + + fun getUniqueIdReceivedInCommand(): Long { + return uniqueIdReceivedInCommand + } + + override fun toString(): String { + return "VersionResponse{" + + "messageType=" + messageType + + ", messageLength=" + messageLength + + ", firmwareVersionMajor=" + firmwareVersionMajor + + ", firmwareVersionMinor=" + firmwareVersionMinor + + ", firmwareVersionInterim=" + firmwareVersionInterim + + ", bleVersionMajor=" + bleVersionMajor + + ", bleVersionMinor=" + bleVersionMinor + + ", bleVersionInterim=" + bleVersionInterim + + ", productId=" + productId + + ", podStatus=" + podStatus + + ", lotNumber=" + lotNumber + + ", podSequenceNumber=" + podSequenceNumber + + ", rssi=" + rssi + + ", receiverLowerGain=" + receiverLowerGain + + ", uniqueIdReceivedInCommand=" + uniqueIdReceivedInCommand + + ", activationResponseType=" + activationResponseType + + ", responseType=" + responseType + + ", encoded=" + Arrays.toString(encoded) + + '}' + } + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt similarity index 50% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index 275bb1d6ec..77970336cf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -1,4 +1,3 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state -public interface OmnipodDashPodStateManager { -} +interface OmnipodDashPodStateManager \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.java deleted file mode 100644 index 6d9297f12a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.java +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util; - -public class MessageUtil { - - private static final short[] crc16table = {0, -32763, -32753, 10, -32741, 30, 20, -32751, -32717, 54, 60, -32711, 40, -32723, -32729, 34, -32669, 102, 108, -32663, 120, -32643, -32649, 114, 80, -32683, -32673, 90, -32693, 78, 68, -32703, -32573, 198, 204, -32567, 216, -32547, -32553, 210, 240, -32523, -32513, 250, -32533, 238, 228, -32543, 160, -32603, -32593, 170, -32581, 190, 180, -32591, -32621, 150, 156, -32615, 136, -32627, -32633, 130, -32381, 390, 396, -32375, 408, -32355, -32361, 402, 432, -32331, -32321, 442, -32341, 430, 420, -32351, 480, -32283, -32273, 490, -32261, 510, 500, -32271, -32301, 470, 476, -32295, 456, -32307, -32313, 450, 320, -32443, -32433, 330, -32421, 350, 340, -32431, -32397, 374, 380, -32391, 360, -32403, -32409, 354, -32477, 294, 300, -32471, 312, -32451, -32457, 306, 272, -32491, -32481, 282, -32501, 270, 260, -32511, -31997, 774, 780, -31991, 792, -31971, -31977, 786, 816, -31947, -31937, 826, -31957, 814, 804, -31967, 864, -31899, -31889, 874, -31877, 894, 884, -31887, -31917, 854, 860, -31911, 840, -31923, -31929, 834, 960, -31803, -31793, 970, -31781, 990, 980, -31791, -31757, 1014, 1020, -31751, 1000, -31763, -31769, 994, -31837, 934, 940, -31831, 952, -31811, -31817, 946, 912, -31851, -31841, 922, -31861, 910, 900, -31871, 640, -32123, -32113, 650, -32101, 670, 660, -32111, -32077, 694, 700, -32071, 680, -32083, -32089, 674, -32029, 742, 748, -32023, 760, -32003, -32009, 754, 720, -32043, -32033, 730, -32053, 718, 708, -32063, -32189, 582, 588, -32183, 600, -32163, -32169, 594, 624, -32139, -32129, 634, -32149, 622, 612, -32159, 544, -32219, -32209, 554, -32197, 574, 564, -32207, -32237, 534, 540, -32231, 520, -32243, -32249, 514}; - - public static int createCrc(short[] sArr) { - int i = 0; - for (short s = 0; s < sArr.length; s = (short) (s + 1)) { - byte b = (byte) sArr[s]; - short s2 = b; - if (b < 0) { - s2 = (short) (((byte) (b & Byte.MAX_VALUE)) + 128); - } - i += s2; - } - return i; - } - - public static short createCrc(byte[] bArr) { - short s = 0; - for (byte b : bArr) { - byte b2 = (byte) (b ^ (s & 255)); - short s2 = b2; - if (b2 < 0) { - s2 = (short) (((byte) (b2 & Byte.MAX_VALUE)) + 128); - } - s = (short) (((short) (((short) (s >> 8)) & 255)) ^ crc16table[s2]); - } - return s; - } - - public static short calculateChecksum(byte[] bytes) { - short sum = 0; - for (byte b : bytes) { - sum += (short) (b & 0xff); - } - return sum; - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt new file mode 100644 index 0000000000..5aa3dbf73f --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt @@ -0,0 +1,45 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util + +import kotlin.experimental.and +import kotlin.experimental.xor + +object MessageUtil { + + private val crc16table = shortArrayOf(0, -32763, -32753, 10, -32741, 30, 20, -32751, -32717, 54, 60, -32711, 40, -32723, -32729, 34, -32669, 102, 108, -32663, 120, -32643, -32649, 114, 80, -32683, -32673, 90, -32693, 78, 68, -32703, -32573, 198, 204, -32567, 216, -32547, -32553, 210, 240, -32523, -32513, 250, -32533, 238, 228, -32543, 160, -32603, -32593, 170, -32581, 190, 180, -32591, -32621, 150, 156, -32615, 136, -32627, -32633, 130, -32381, 390, 396, -32375, 408, -32355, -32361, 402, 432, -32331, -32321, 442, -32341, 430, 420, -32351, 480, -32283, -32273, 490, -32261, 510, 500, -32271, -32301, 470, 476, -32295, 456, -32307, -32313, 450, 320, -32443, -32433, 330, -32421, 350, 340, -32431, -32397, 374, 380, -32391, 360, -32403, -32409, 354, -32477, 294, 300, -32471, 312, -32451, -32457, 306, 272, -32491, -32481, 282, -32501, 270, 260, -32511, -31997, 774, 780, -31991, 792, -31971, -31977, 786, 816, -31947, -31937, 826, -31957, 814, 804, -31967, 864, -31899, -31889, 874, -31877, 894, 884, -31887, -31917, 854, 860, -31911, 840, -31923, -31929, 834, 960, -31803, -31793, 970, -31781, 990, 980, -31791, -31757, 1014, 1020, -31751, 1000, -31763, -31769, 994, -31837, 934, 940, -31831, 952, -31811, -31817, 946, 912, -31851, -31841, 922, -31861, 910, 900, -31871, 640, -32123, -32113, 650, -32101, 670, 660, -32111, -32077, 694, 700, -32071, 680, -32083, -32089, 674, -32029, 742, 748, -32023, 760, -32003, -32009, 754, 720, -32043, -32033, 730, -32053, 718, 708, -32063, -32189, 582, 588, -32183, 600, -32163, -32169, 594, 624, -32139, -32129, 634, -32149, 622, 612, -32159, 544, -32219, -32209, 554, -32197, 574, 564, -32207, -32237, 534, 540, -32231, 520, -32243, -32249, 514) + + fun createCrc(sArr: ShortArray): Int { + var i = 0 + var s: Short = 0 + while (s < sArr.size) { + val b = sArr[s.toInt()].toByte() + var s2 = b.toShort() + if (b < 0) { + s2 = ((b and Byte.MAX_VALUE) as Byte + 128).toShort() + } + i += s2.toInt() + s = (s + 1).toShort() + } + return i + } + + fun createCrc(bArr: ByteArray): Short { + var s: Short = 0 + for (b in bArr) { + val b2 = (b xor (s and 255).toByte()) // TODO byte conversion ok? + var s2 = b2.toShort() + if (b2 < 0) { + s2 = ((b2 and Byte.MAX_VALUE) as Byte + 128).toShort() + } + s = (((s.toInt() shr 8).toShort() and 255) xor crc16table[s2.toInt()]) + } + return s + } + + fun calculateChecksum(bytes: ByteArray): Short { + var sum: Short = 0 + for (b in bytes) { + sum = (sum + (b.toInt() and 0xff)).toShort() + } + return sum + } +} \ No newline at end of file From bc8eefaffdf750f1d93308902f38edf811af48f9 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Thu, 25 Feb 2021 23:55:12 +0100 Subject: [PATCH 012/649] Convert OmnipodDashPumpPlugin to Kotlin --- .../omnipod/dash/OmnipodDashPumpPlugin.java | 213 ------------------ .../omnipod/dash/OmnipodDashPumpPlugin.kt | 206 +++++++++++++++++ 2 files changed, 206 insertions(+), 213 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java deleted file mode 100644 index 628445b62b..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.java +++ /dev/null @@ -1,213 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash; - -import androidx.annotation.Nullable; - -import com.google.gson.JsonObject; - -import org.jetbrains.annotations.NotNull; -import org.json.JSONObject; - -import java.util.Collections; -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.PumpDescription; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.interfaces.PumpPluginBase; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; -import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOverviewFragment; -import info.nightscout.androidaps.queue.commands.CustomCommand; -import info.nightscout.androidaps.utils.TimeChangeType; -import info.nightscout.androidaps.utils.resources.ResourceHelper; - -@Singleton -public class OmnipodDashPumpPlugin extends PumpPluginBase implements PumpInterface { - private static final PumpDescription PUMP_DESCRIPTION = new PumpDescription(PumpType.Omnipod_Dash); - - private final AAPSLogger aapsLogger; - private final ResourceHelper resourceHelper; - private final CommandQueueProvider commandQueue; - - @Inject - public OmnipodDashPumpPlugin(HasAndroidInjector injector, AAPSLogger aapsLogger, ResourceHelper resourceHelper, CommandQueueProvider commandQueue) { - super(new PluginDescription() // - .mainType(PluginType.PUMP) // - .fragmentClass(OmnipodDashOverviewFragment.class.getName()) // - .pluginIcon(R.drawable.ic_pod_128) - .pluginName(R.string.omnipod_dash_name) // - .shortName(R.string.omnipod_dash_name_short) // - .preferencesId(R.xml.omnipod_dash_preferences) // - .description(R.string.omnipod_dash_pump_description), injector, aapsLogger, resourceHelper, commandQueue); - this.aapsLogger = aapsLogger; - this.resourceHelper = resourceHelper; - this.commandQueue = commandQueue; - } - - @Override public boolean isInitialized() { - return true; - } - - @Override public boolean isSuspended() { - return false; - } - - @Override public boolean isBusy() { - // prevents the queue from executing - return true; - } - - @Override public boolean isConnected() { - return false; - } - - @Override public boolean isConnecting() { - return false; - } - - @Override public boolean isHandshakeInProgress() { - return false; - } - - @Override public void finishHandshaking() { - - } - - @Override public void connect(@NotNull String reason) { - - } - - @Override public void disconnect(@NotNull String reason) { - - } - - @Override public void stopConnecting() { - - } - - @Override public void getPumpStatus(@NotNull String reason) { - - } - - @NotNull @Override public PumpEnactResult setNewBasalProfile(@NotNull Profile profile) { - // TODO - return new PumpEnactResult(getInjector()).success(true).enacted(true); - } - - @Override public boolean isThisProfileSet(@NotNull Profile profile) { - // TODO - return true; - } - - @Override public long lastDataTime() { - // TODO - return System.currentTimeMillis(); - } - - @Override public double getBaseBasalRate() { - return 0; - } - - @Override public double getReservoirLevel() { - return 0; - } - - @Override public int getBatteryLevel() { - return 0; - } - - @NotNull @Override public PumpEnactResult deliverTreatment(@NotNull DetailedBolusInfo detailedBolusInfo) { - return null; - } - - @Override public void stopBolusDelivering() { - - } - - @NotNull @Override public PumpEnactResult setTempBasalAbsolute(double absoluteRate, int durationInMinutes, @NotNull Profile profile, boolean enforceNew) { - return null; - } - - @NotNull @Override public PumpEnactResult setTempBasalPercent(int percent, int durationInMinutes, @NotNull Profile profile, boolean enforceNew) { - return null; - } - - @NotNull @Override public PumpEnactResult setExtendedBolus(double insulin, int durationInMinutes) { - return null; - } - - @NotNull @Override public PumpEnactResult cancelTempBasal(boolean enforceNew) { - return null; - } - - @NotNull @Override public PumpEnactResult cancelExtendedBolus() { - return null; - } - - @NotNull @Override public JSONObject getJSONStatus(@NotNull Profile profile, @NotNull String profileName, @NotNull String version) { - return new JSONObject(); - } - - @NotNull @Override public ManufacturerType manufacturer() { - return getPumpDescription().pumpType.getManufacturer(); - } - - @NotNull @Override public PumpType model() { - return getPumpDescription().pumpType; - } - - @NotNull @Override public String serialNumber() { - return null; - } - - @NotNull @Override public PumpDescription getPumpDescription() { - return PUMP_DESCRIPTION; - } - - @NotNull @Override public String shortStatus(boolean veryShort) { - return null; - } - - @Override public boolean isFakingTempsByExtendedBoluses() { - return false; - } - - @NotNull @Override public PumpEnactResult loadTDDs() { - return null; - } - - @Override public boolean canHandleDST() { - return false; - } - - @Override - public List getCustomActions() { - return Collections.emptyList(); - } - - @Override - public void executeCustomAction(@NotNull CustomActionType customActionType) { - aapsLogger.warn(LTag.PUMP, "Unsupported custom action: " + customActionType); - } - - @Nullable @Override public PumpEnactResult executeCustomCommand(@NotNull CustomCommand customCommand) { - return null; - } - - @Override public void timezoneOrDSTChanged(@NotNull TimeChangeType timeChangeType) { - - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt new file mode 100644 index 0000000000..db977caef9 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -0,0 +1,206 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash + +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.interfaces.* +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.common.ManufacturerType +import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction +import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOverviewFragment +import info.nightscout.androidaps.queue.commands.CustomCommand +import info.nightscout.androidaps.utils.TimeChangeType +import info.nightscout.androidaps.utils.resources.ResourceHelper +import org.json.JSONObject +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class OmnipodDashPumpPlugin @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + resourceHelper: ResourceHelper, + commandQueue: CommandQueueProvider) + : PumpPluginBase(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue), PumpInterface { + + companion object { + + private val pluginDescription = PluginDescription() // + .mainType(PluginType.PUMP) // + .fragmentClass(OmnipodDashOverviewFragment::class.java.name) // + .pluginIcon(R.drawable.ic_pod_128) + .pluginName(R.string.omnipod_dash_name) // + .shortName(R.string.omnipod_dash_name_short) // + .preferencesId(R.xml.omnipod_dash_preferences) // + .description(R.string.omnipod_dash_pump_description) + + private val pumpDescription = PumpDescription(PumpType.Omnipod_Dash) + } + + override fun isInitialized(): Boolean { + // TODO + return true + } + + override fun isSuspended(): Boolean { + // TODO + return false + } + + override fun isBusy(): Boolean { + // prevents the queue from executing commands + // TODO + return true + } + + override fun isConnected(): Boolean { + // TODO + return false + } + + override fun isConnecting(): Boolean { + // TODO + return false + } + + override fun isHandshakeInProgress(): Boolean { + // TODO + return false + } + + override fun finishHandshaking() { + // TODO + } + + override fun connect(reason: String) { + // TODO + } + + override fun disconnect(reason: String) { + // TODO + } + + override fun stopConnecting() { + // TODO + } + + override fun getPumpStatus(reason: String) { + // TODO + } + + override fun setNewBasalProfile(profile: Profile): PumpEnactResult { + // TODO + return PumpEnactResult(injector).success(true).enacted(true) + } + + override fun isThisProfileSet(profile: Profile): Boolean { + // TODO + return true + } + + override fun lastDataTime(): Long { + // TODO + return System.currentTimeMillis() + } + + override val baseBasalRate: Double + get() = 0.0 // TODO + + override val reservoirLevel: Double + get() = 0.0 // TODO + + override val batteryLevel: Int + get() = 0 + + override fun deliverTreatment(detailedBolusInfo: DetailedBolusInfo): PumpEnactResult { + // TODO + return PumpEnactResult(injector).success(false).enacted(false).comment("TODO") + } + + override fun stopBolusDelivering() { + // TODO + } + + override fun setTempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult { + // TODO + return PumpEnactResult(injector).success(false).enacted(false).comment("TODO") + } + + override fun setTempBasalPercent(percent: Int, durationInMinutes: Int, profile: Profile, enforceNew: Boolean): PumpEnactResult { + // TODO i18n + return PumpEnactResult(injector).success(false).enacted(false).comment("Omnipod Dash driver does not support percentage temp basals") + } + + override fun setExtendedBolus(insulin: Double, durationInMinutes: Int): PumpEnactResult { + // TODO i18n + return PumpEnactResult(injector).success(false).enacted(false).comment("Omnipod Dash driver does not support extended boluses") + } + + override fun cancelTempBasal(enforceNew: Boolean): PumpEnactResult { + // TODO + return PumpEnactResult(injector).success(false).enacted(false).comment("TODO") + } + + override fun cancelExtendedBolus(): PumpEnactResult { + // TODO i18n + return PumpEnactResult(injector).success(false).enacted(false).comment("Omnipod Dash driver does not support extended boluses") + } + + override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject { + // TODO + return JSONObject() + } + + override val pumpDescription: PumpDescription = Companion.pumpDescription + + override fun manufacturer(): ManufacturerType { + return pumpDescription.pumpType.manufacturer + } + + override fun model(): PumpType { + return pumpDescription.pumpType + } + + override fun serialNumber(): String { + // TODO + return "TODO" + } + + override fun shortStatus(veryShort: Boolean): String { + // TODO + return "TODO" + } + + override val isFakingTempsByExtendedBoluses: Boolean + get() = false + + override fun loadTDDs(): PumpEnactResult { + // TODO i18n + return PumpEnactResult(injector).success(false).enacted(false).comment("Omnipod Dash driver does not support TDD") + } + + override fun canHandleDST(): Boolean { + return false + } + + override fun getCustomActions(): List { + return emptyList() + } + + override fun executeCustomAction(customActionType: CustomActionType) { + aapsLogger.warn(LTag.PUMP, "Unsupported custom action: $customActionType") + } + + override fun executeCustomCommand(customCommand: CustomCommand): PumpEnactResult? { + // TODO + return null + } + + override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { + // TODO + } +} \ No newline at end of file From 41b2602d610120747845fadf0884d7d1aada252e Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 01:26:21 +0100 Subject: [PATCH 013/649] Add OmnipodDashPodStateManager --- .../omnipod/dash/dagger/OmnipodDashModule.kt | 14 +- ...DashManager.java => OmnipodDashManager.kt} | 5 +- .../omnipod/dash/driver/comm/BleManager.kt | 4 +- .../dash/driver/comm/OmnipodDashBleManager.kt | 7 + .../comm/OmnipodDashCommunicationManager.kt | 3 - .../pod/definition/ActivationProgress.kt | 18 ++ .../driver/pod/definition/SoftwareVersion.kt | 5 + .../pod/state/OmnipodDashPodStateManager.kt | 50 +++++- .../state/OmnipodDashPodStateManagerImpl.kt | 166 ++++++++++++++++++ .../action/DashInitializePodViewModel.kt | 6 +- 10 files changed, 263 insertions(+), 15 deletions(-) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/{OmnipodDashManager.java => OmnipodDashManager.kt} (59%) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index 0d9b275dd6..e4d2e3517b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -1,10 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.dagger import dagger.Module +import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ActivityScope import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodWizardModule import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.DashPodManagementActivity import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOverviewFragment import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.DashPodActivationWizardActivity @@ -31,6 +35,12 @@ abstract class OmnipodDashModule { @ContributesAndroidInjector abstract fun contributesOmnipodDashOverviewFragment(): OmnipodDashOverviewFragment - @ContributesAndroidInjector - abstract fun contributesBleManager(): BleManager + companion object { + + @Provides + fun providesBleManager(bleManager: BleManager): OmnipodDashBleManager = bleManager + + @Provides + fun providesPodStateManager(podStateManager: OmnipodDashPodStateManagerImpl): OmnipodDashPodStateManager = podStateManager + } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.java b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt similarity index 59% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.java rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index a23de9bcf0..d0c15d5107 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.java +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -1,4 +1,3 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver; +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver -public interface OmnipodDashManager { -} +interface OmnipodDashManager \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt index 16d6153b58..e624e3050f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt @@ -20,13 +20,13 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class BleManager @Inject constructor(private val context: Context, private val aapsLogger: AAPSLogger) : OmnipodDashCommunicationManager { +class BleManager @Inject constructor(private val context: Context, private val aapsLogger: AAPSLogger) : OmnipodDashBleManager { private val bluetoothManager: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - fun activateNewPod() { + override fun activateNewPod() { aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") val podScanner = PodScanner(aapsLogger, bluetoothAdapter) val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt new file mode 100644 index 0000000000..c90e0438b4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm + +interface OmnipodDashBleManager { + + // TODO should we keep this method? + fun activateNewPod() +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt deleted file mode 100644 index db95a2046b..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashCommunicationManager.kt +++ /dev/null @@ -1,3 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm - -interface OmnipodDashCommunicationManager \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt new file mode 100644 index 0000000000..029db3965e --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt @@ -0,0 +1,18 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +enum class ActivationProgress { + NOT_STARTED, + GOT_POD_VERSION, + SET_UNIQUE_ID, + PROGRAMMED_LOW_RESERVOIR_ALERTS, + REPROGRAMMED_LUMP_OF_COAL_ALERT, + PRIMING, + PRIME_COMPLETED, + PROGRAMMED_USER_SET_EXPIRATION_ALERT, + PHASE_1_COMPLETED, + PROGRAMMED_BASAL, + PROGRAMMED_CANCEL_LOC_ETC_ALERT, + INSERTING_CANNULA, + CANNULA_INSERTED, + COMPLETED +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt new file mode 100644 index 0000000000..4f03fb2428 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +import java.io.Serializable + +data class SoftwareVersion(private val major: Int, private val minor: Int, private val interim: Int) : Serializable diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index 77970336cf..4d7ea23e81 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -1,3 +1,51 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state -interface OmnipodDashPodStateManager \ No newline at end of file +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.SoftwareVersion +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse +import java.io.Serializable + +interface OmnipodDashPodStateManager { + + var activationProgress: ActivationProgress + var lastConnectionTime: Long + + val messageSequenceNumber: Short + val activationTime: Long? + val uniqueId: Int? + val bluetoothAddress: String? + + val bluetoothVersion: SoftwareVersion? + val firmwareVersion: SoftwareVersion? + val lotNumber: Int? + val podSequenceNumber: Int? + val pulseRate: Int? + val primePulseRate: Int? + val podLifeInHours: Int? + val firstPrimeBolusVolume: Int? + val secondPrimeBolusVolume: Int? + + val pulsesDelivered: Int? + val pulsesRemaining: Int? + val podStatus: PodStatus? + val deliveryStatus: DeliveryStatus? + + val tempBasal: TempBasal? + val tempBasalActive: Boolean + val basalProgram: BasalProgram? + + fun increaseMessageSequenceNumber() + fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) + fun updateFromVersionResponse(response: VersionResponse) + fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) + fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) + fun reset() + + data class TempBasal(val startTime: Long, val rate: Double, val durationInMinutes: Int) : Serializable +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt new file mode 100644 index 0000000000..c72e853996 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -0,0 +1,166 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state + +import com.google.gson.Gson +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.SoftwareVersion +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import java.io.Serializable +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class OmnipodDashPodStateManagerImpl @Inject constructor( + private val resourceHelper: ResourceHelper, + private val logger: AAPSLogger, + private val sharedPreferences: SP +) : OmnipodDashPodStateManager { + + private var podState: PodState + + init { + podState = load() + } + + override var activationProgress: ActivationProgress + get() = podState.activationProgress + set(value) { + podState.activationProgress = value + store() + } + + override var lastConnectionTime: Long + get() = podState.lastConnectionTime + set(value) { + podState.lastConnectionTime = value + store() + } + + override val messageSequenceNumber: Short = podState.messageSequenceNumber + + override val activationTime: Long? = podState.activationTime + + override val uniqueId: Int? = podState.uniqueId + + override val bluetoothAddress: String? = podState.bluetoothAddress + + override val bluetoothVersion: SoftwareVersion? = podState.bluetoothVersion + + override val firmwareVersion: SoftwareVersion? = podState.firmwareVersion + + override val lotNumber: Int? = podState.lotNumber + + override val podSequenceNumber: Int? = podState.podSequenceNumber + + override val pulseRate: Int? = podState.pulseRate + + override val primePulseRate: Int? = podState.primePulseRate + + override val podLifeInHours: Int? = podState.podLifeInHours + + override val firstPrimeBolusVolume: Int? = podState.firstPrimeBolusVolume + + override val secondPrimeBolusVolume: Int? = podState.secondPrimeBolusVolume + + override val pulsesDelivered: Int? = podState.pulsesDelivered + + override val pulsesRemaining: Int? = podState.pulsesRemaining + + override val podStatus: PodStatus? = podState.podStatus + + override val deliveryStatus: DeliveryStatus? = podState.deliveryStatus + + override val tempBasal: OmnipodDashPodStateManager.TempBasal? = podState.tempBasal + + override val tempBasalActive: Boolean + get() = tempBasal != null && tempBasal.startTime + tempBasal.durationInMinutes * 60 * 1000 > System.currentTimeMillis() + + override val basalProgram: BasalProgram? = podState.basalProgram + + override fun increaseMessageSequenceNumber() { + podState.messageSequenceNumber = ((podState.messageSequenceNumber.toInt() + 1) and 0x0f).toShort() + store() + } + + override fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) { + TODO("Not yet implemented") + } + + override fun updateFromVersionResponse(response: VersionResponse) { + TODO("Not yet implemented") + } + + override fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) { + response.getBleVersionInterim() + } + + override fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) { + TODO("Not yet implemented") + } + + override fun reset() { + podState = PodState() + store() + } + + private fun store() { + try { + val serialized = Gson().toJson(podState) + logger.debug(LTag.PUMP, "Storing Pod state: $serialized") + sharedPreferences.putString(R.string.key_omnipod_dash_pod_state, serialized) + } catch (ex: Exception) { + logger.error(LTag.PUMP, "Failed to store Pod state", ex) + } + } + + private fun load(): PodState { + if (sharedPreferences.contains(R.string.key_omnipod_dash_pod_state)) { + try { + return Gson().fromJson(sharedPreferences.getString(R.string.key_omnipod_dash_pod_state, ""), PodState::class.java) + } catch (ex: Exception) { + logger.error(LTag.PUMP, "Failed to deserialize Pod state", ex) + } + } + logger.debug(LTag.PUMP, "Creating new Pod state") + return PodState() + } + + class PodState : Serializable { + + var activationProgress: ActivationProgress = ActivationProgress.NOT_STARTED + var lastConnectionTime: Long = 0 + + var messageSequenceNumber: Short = 0 + var activationTime: Long? = null + var uniqueId: Int? = null + var bluetoothAddress: String? = null + + var bluetoothVersion: SoftwareVersion? = null + var firmwareVersion: SoftwareVersion? = null + var lotNumber: Int? = null + var podSequenceNumber: Int? = null + var pulseRate: Int? = null + var primePulseRate: Int? = null + var podLifeInHours: Int? = null + var firstPrimeBolusVolume: Int? = null + var secondPrimeBolusVolume: Int? = null + + var pulsesDelivered: Int? = null + var pulsesRemaining: Int? = null + var podStatus: PodStatus? = null + var deliveryStatus: DeliveryStatus? = null + + var basalProgram: BasalProgram? = null + var tempBasal: OmnipodDashPodStateManager.TempBasal? = null + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index b97060a907..396d56d009 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -2,20 +2,18 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activatio import android.os.AsyncTask import androidx.annotation.StringRes -import androidx.lifecycle.viewModelScope import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager -import kotlinx.coroutines.launch +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager import javax.inject.Inject class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger, private val injector: HasAndroidInjector, - private val bleManager: BleManager) : InitializePodViewModel() { + private val bleManager: OmnipodDashBleManager) : InitializePodViewModel() { override fun isPodInAlarm(): Boolean = false // TODO From bd0afdaf1645d13ac6f43830ab80a4897389b478 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 01:31:13 +0100 Subject: [PATCH 014/649] Resolve TODO --- .../omnipod/dash/dagger/OmnipodDashModule.kt | 2 +- .../pod/definition/ActivationProgress.kt | 6 +++++- .../dash/ui/DashPodManagementActivity.kt | 19 ++++++++++--------- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index e4d2e3517b..ae22f4409a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -43,4 +43,4 @@ abstract class OmnipodDashModule { @Provides fun providesPodStateManager(podStateManager: OmnipodDashPodStateManagerImpl): OmnipodDashPodStateManager = podStateManager } -} +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt index 029db3965e..e43a277f2e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt @@ -14,5 +14,9 @@ enum class ActivationProgress { PROGRAMMED_CANCEL_LOC_ETC_ALERT, INSERTING_CANNULA, CANNULA_INSERTED, - COMPLETED + COMPLETED; + + fun isBefore(other: ActivationProgress): Boolean = ordinal < other.ordinal + + fun isAtLeast(other: ActivationProgress): Boolean = ordinal >= other.ordinal } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt index ac96ad394b..26aa52b5df 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt @@ -12,6 +12,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.Comm import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.PodActivationWizardActivity import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashPodManagementBinding +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.DashPodActivationWizardActivity import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.DashPodDeactivationWizardActivity import info.nightscout.androidaps.queue.Callback @@ -34,6 +36,7 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var context: Context @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var podStateManager: OmnipodDashPodStateManager private var disposables: CompositeDisposable = CompositeDisposable() @@ -46,17 +49,15 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { setContentView(binding.root) binding.buttonActivatePod.setOnClickListener { - /* TODO determine type - val type: PodActivationWizardActivity.Type = if (podStateManager.isPodInitialized - and podStateManager.activationProgress.isAtLeast(ActivationProgress.PRIMING_COMPLETED)) { - PodActivationWizardActivity.Type.SHORT - } else { - PodActivationWizardActivity.Type.LONG - } - */ + val type: PodActivationWizardActivity.Type = + if (podStateManager.activationProgress.isAtLeast(ActivationProgress.PRIME_COMPLETED)) { + PodActivationWizardActivity.Type.SHORT + } else { + PodActivationWizardActivity.Type.LONG + } val intent = Intent(this, DashPodActivationWizardActivity::class.java) - intent.putExtra(PodActivationWizardActivity.KEY_TYPE, PodActivationWizardActivity.Type.LONG) + intent.putExtra(PodActivationWizardActivity.KEY_TYPE, type) startActivity(intent) } From a348cb74e749ad4fbcdd0f6421e2a088e46231d4 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 02:15:49 +0100 Subject: [PATCH 015/649] Implement more methods in OmnipodDashPodStateManagerImpl --- .../driver/pod/definition/SoftwareVersion.kt | 7 +- .../driver/pod/response/VersionResponse.kt | 1 + .../pod/state/OmnipodDashPodStateManager.kt | 35 +++--- .../state/OmnipodDashPodStateManagerImpl.kt | 109 ++++++++++++------ 4 files changed, 98 insertions(+), 54 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt index 4f03fb2428..e373a1ba41 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt @@ -2,4 +2,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti import java.io.Serializable -data class SoftwareVersion(private val major: Int, private val minor: Int, private val interim: Int) : Serializable +data class SoftwareVersion(private val major: Short, private val minor: Short, private val interim: Short) : Serializable { + + override fun toString(): String { + return "$major.$minor.$interim" + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt index 6108ccf2b1..315adc5018 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt @@ -23,6 +23,7 @@ class VersionResponse(encoded: ByteArray) : ActivationResponseBase(ActivationRes private val rssi: Byte = (encoded[18] and 0x3f) private val receiverLowerGain: Byte = ((encoded[18].toInt() shr 6 and 0x03).toByte()) private val uniqueIdReceivedInCommand: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[19], encoded[20], encoded[21], encoded[22])).long + fun getMessageType(): Byte { return messageType } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index 4d7ea23e81..0a390622f6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -1,40 +1,41 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.SoftwareVersion +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse import java.io.Serializable +import java.util.* interface OmnipodDashPodStateManager { var activationProgress: ActivationProgress - var lastConnectionTime: Long + var lastConnection: Long + val lastUpdated: Long val messageSequenceNumber: Short + val sequenceNumberOfLastProgrammingCommand: Short? val activationTime: Long? - val uniqueId: Int? + val uniqueId: Long? val bluetoothAddress: String? val bluetoothVersion: SoftwareVersion? val firmwareVersion: SoftwareVersion? - val lotNumber: Int? - val podSequenceNumber: Int? - val pulseRate: Int? - val primePulseRate: Int? - val podLifeInHours: Int? - val firstPrimeBolusVolume: Int? - val secondPrimeBolusVolume: Int? + val lotNumber: Long? + val podSequenceNumber: Long? + val pulseRate: Short? + val primePulseRate: Short? + val podLifeInHours: Short? + val firstPrimeBolusVolume: Short? + val secondPrimeBolusVolume: Short? - val pulsesDelivered: Int? - val pulsesRemaining: Int? + val pulsesDelivered: Short? + val pulsesRemaining: Short? val podStatus: PodStatus? val deliveryStatus: DeliveryStatus? + val minutesSinceActivation: Short? + val activeAlerts: EnumSet? val tempBasal: TempBasal? val tempBasalActive: Boolean @@ -47,5 +48,5 @@ interface OmnipodDashPodStateManager { fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) fun reset() - data class TempBasal(val startTime: Long, val rate: Double, val durationInMinutes: Int) : Serializable + data class TempBasal(val startTime: Long, val rate: Double, val durationInMinutes: Short) : Serializable } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index c72e853996..bd7838428e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -4,24 +4,19 @@ import com.google.gson.Gson import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.R -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.SoftwareVersion +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse -import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.io.Serializable +import java.util.* import javax.inject.Inject import javax.inject.Singleton @Singleton class OmnipodDashPodStateManagerImpl @Inject constructor( - private val resourceHelper: ResourceHelper, private val logger: AAPSLogger, private val sharedPreferences: SP ) : OmnipodDashPodStateManager { @@ -39,47 +34,55 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( store() } - override var lastConnectionTime: Long - get() = podState.lastConnectionTime + override var lastConnection: Long + get() = podState.lastConnection set(value) { - podState.lastConnectionTime = value + podState.lastConnection = value store() } + override val lastUpdated: Long = podState.lastUpdated + override val messageSequenceNumber: Short = podState.messageSequenceNumber + override val sequenceNumberOfLastProgrammingCommand: Short? = podState.sequenceNumberOfLastProgrammingCommand + override val activationTime: Long? = podState.activationTime - override val uniqueId: Int? = podState.uniqueId + override val uniqueId: Long? = podState.uniqueId override val bluetoothAddress: String? = podState.bluetoothAddress - override val bluetoothVersion: SoftwareVersion? = podState.bluetoothVersion + override val bluetoothVersion: SoftwareVersion? = podState.bleVersion override val firmwareVersion: SoftwareVersion? = podState.firmwareVersion - override val lotNumber: Int? = podState.lotNumber + override val lotNumber: Long? = podState.lotNumber - override val podSequenceNumber: Int? = podState.podSequenceNumber + override val podSequenceNumber: Long? = podState.podSequenceNumber - override val pulseRate: Int? = podState.pulseRate + override val pulseRate: Short? = podState.pulseRate - override val primePulseRate: Int? = podState.primePulseRate + override val primePulseRate: Short? = podState.primePulseRate - override val podLifeInHours: Int? = podState.podLifeInHours + override val podLifeInHours: Short? = podState.podLifeInHours - override val firstPrimeBolusVolume: Int? = podState.firstPrimeBolusVolume + override val firstPrimeBolusVolume: Short? = podState.firstPrimeBolusVolume - override val secondPrimeBolusVolume: Int? = podState.secondPrimeBolusVolume + override val secondPrimeBolusVolume: Short? = podState.secondPrimeBolusVolume - override val pulsesDelivered: Int? = podState.pulsesDelivered + override val pulsesDelivered: Short? = podState.pulsesDelivered - override val pulsesRemaining: Int? = podState.pulsesRemaining + override val pulsesRemaining: Short? = podState.pulsesRemaining override val podStatus: PodStatus? = podState.podStatus override val deliveryStatus: DeliveryStatus? = podState.deliveryStatus + override val minutesSinceActivation: Short? = podState.minutesSinceActivation + + override val activeAlerts: EnumSet? = podState.activeAlerts + override val tempBasal: OmnipodDashPodStateManager.TempBasal? = podState.tempBasal override val tempBasalActive: Boolean @@ -93,15 +96,45 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( } override fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) { - TODO("Not yet implemented") + podState.deliveryStatus = response.getDeliveryStatus() + podState.podStatus = response.getPodStatus() + podState.pulsesDelivered = response.getTotalPulsesDelivered() + podState.pulsesRemaining = response.getReservoirPulsesRemaining() + podState.sequenceNumberOfLastProgrammingCommand = response.getSequenceNumberOfLastProgrammingCommand() + podState.minutesSinceActivation = response.getMinutesSinceActivation() + + // TODO active alerts + + podState.lastUpdated = System.currentTimeMillis() + store(); } override fun updateFromVersionResponse(response: VersionResponse) { - TODO("Not yet implemented") + podState.bleVersion = SoftwareVersion(response.getBleVersionMajor(), response.getBleVersionMinor(), response.getBleVersionInterim()) + podState.firmwareVersion = SoftwareVersion(response.getFirmwareVersionMajor(), response.getFirmwareVersionMinor(), response.getFirmwareVersionInterim()) + podState.podStatus = response.getPodStatus() + podState.lotNumber = response.getLotNumber() + podState.podSequenceNumber = response.getPodSequenceNumber() + + podState.lastUpdated = System.currentTimeMillis() + store() } override fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) { - response.getBleVersionInterim() + podState.pulseRate = response.getDeliveryRate() + podState.primePulseRate = response.getPrimeRate() + podState.firstPrimeBolusVolume = response.getNumberOfPrimePulses() + podState.secondPrimeBolusVolume = response.getNumberOfEngagingClutchDrivePulses() + podState.podLifeInHours = response.getPodExpirationTimeInHours() + podState.bleVersion = SoftwareVersion(response.getBleVersionMajor(), response.getBleVersionMinor(), response.getBleVersionInterim()) + podState.firmwareVersion = SoftwareVersion(response.getFirmwareVersionMajor(), response.getFirmwareVersionMinor(), response.getFirmwareVersionInterim()) + podState.podStatus = response.getPodStatus() + podState.lotNumber = response.getLotNumber() + podState.podSequenceNumber = response.getPodSequenceNumber() + podState.uniqueId = response.getUniqueIdReceivedInCommand() + + podState.lastUpdated = System.currentTimeMillis() + store() } override fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) { @@ -138,27 +171,31 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( class PodState : Serializable { var activationProgress: ActivationProgress = ActivationProgress.NOT_STARTED - var lastConnectionTime: Long = 0 + var lastConnection: Long = 0 + var lastUpdated: Long = 0 var messageSequenceNumber: Short = 0 + var sequenceNumberOfLastProgrammingCommand: Short? = null var activationTime: Long? = null - var uniqueId: Int? = null + var uniqueId: Long? = null var bluetoothAddress: String? = null - var bluetoothVersion: SoftwareVersion? = null + var bleVersion: SoftwareVersion? = null var firmwareVersion: SoftwareVersion? = null - var lotNumber: Int? = null - var podSequenceNumber: Int? = null - var pulseRate: Int? = null - var primePulseRate: Int? = null - var podLifeInHours: Int? = null - var firstPrimeBolusVolume: Int? = null - var secondPrimeBolusVolume: Int? = null + var lotNumber: Long? = null + var podSequenceNumber: Long? = null + var pulseRate: Short? = null + var primePulseRate: Short? = null + var podLifeInHours: Short? = null + var firstPrimeBolusVolume: Short? = null + var secondPrimeBolusVolume: Short? = null - var pulsesDelivered: Int? = null - var pulsesRemaining: Int? = null + var pulsesDelivered: Short? = null + var pulsesRemaining: Short? = null var podStatus: PodStatus? = null var deliveryStatus: DeliveryStatus? = null + var minutesSinceActivation: Short? = null + var activeAlerts: EnumSet? = null var basalProgram: BasalProgram? = null var tempBasal: OmnipodDashPodStateManager.TempBasal? = null From f32d6055677c693b1f3351713fff20a1d3270f76 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 02:34:30 +0100 Subject: [PATCH 016/649] Add OmnipodDashManager interface --- .../omnipod/dash/driver/OmnipodDashManager.kt | 27 ++++++++++++++++++- .../omnipod/dash/driver/pod/event/PodEvent.kt | 6 +++++ .../dash/driver/pod/event/PodEventType.kt | 9 +++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEvent.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEventType.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index d0c15d5107..1c4e63ea99 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -1,3 +1,28 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver -interface OmnipodDashManager \ No newline at end of file +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.event.PodEvent +import io.reactivex.Observable + +interface OmnipodDashManager { + + fun activatePodPart1(): Observable + + fun activatePodPart2(): Observable + + fun getStatus(): Observable + + fun setBasalProgram(program: BasalProgram): Observable + + fun suspendDelivery(): Observable + + fun setTime(): Observable + + fun setTempBasal(rate: Double, durationInMinutes: Short): Observable + + fun cancelTempBasal(): Observable + + fun bolus(amount: Double): Observable + + fun cancelBolus(): Observable +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEvent.kt new file mode 100644 index 0000000000..db22203b11 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEvent.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.event + +class PodEvent( + val type: PodEventType, + val data: Any? +) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEventType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEventType.kt new file mode 100644 index 0000000000..d8e564b72a --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/event/PodEventType.kt @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.event + +enum class PodEventType { + CONNECTED, + COMMAND_SENDING, + COMMAND_SENT, + RESPONSE_RECEIVED, + // ... +} \ No newline at end of file From 97aac063ee962acd492cdb0af1c8b799a111505e Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 02:45:44 +0100 Subject: [PATCH 017/649] Add OmnipodDashManagerImpl --- .../omnipod/dash/OmnipodDashPumpPlugin.kt | 4 ++ .../omnipod/dash/dagger/OmnipodDashModule.kt | 5 ++ .../dash/driver/OmnipodDashManagerImpl.kt | 68 +++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index db977caef9..939c480276 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -11,6 +11,8 @@ import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOverviewFragment import info.nightscout.androidaps.queue.commands.CustomCommand import info.nightscout.androidaps.utils.TimeChangeType @@ -21,6 +23,8 @@ import javax.inject.Singleton @Singleton class OmnipodDashPumpPlugin @Inject constructor( + private val omnipodManager: OmnipodDashManager, + private val podStateManager: OmnipodDashPodStateManager, injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index ae22f4409a..38b571f922 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -5,6 +5,8 @@ import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ActivityScope import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodWizardModule +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager @@ -42,5 +44,8 @@ abstract class OmnipodDashModule { @Provides fun providesPodStateManager(podStateManager: OmnipodDashPodStateManagerImpl): OmnipodDashPodStateManager = podStateManager + + @Provides + fun providesOmnipodManager(omnipodManager: OmnipodDashManagerImpl): OmnipodDashManager = omnipodManager } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt new file mode 100644 index 0000000000..af4e3c8700 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -0,0 +1,68 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver + +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.event.PodEvent +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager +import io.reactivex.Observable +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class OmnipodDashManagerImpl @Inject constructor( + private val aapsLogger: AAPSLogger, + private val podStateManager: OmnipodDashPodStateManager, + private val bleManager: OmnipodDashBleManager +) : OmnipodDashManager { + + override fun activatePodPart1(): Observable { + // TODO + return Observable.empty() + } + + override fun activatePodPart2(): Observable { + // TODO + return Observable.empty() + } + + override fun getStatus(): Observable { + // TODO + return Observable.empty() + } + + override fun setBasalProgram(program: BasalProgram): Observable { + // TODO + return Observable.empty() + } + + override fun suspendDelivery(): Observable { + // TODO + return Observable.empty() + } + + override fun setTime(): Observable { + // TODO + return Observable.empty() + } + + override fun setTempBasal(rate: Double, durationInMinutes: Short): Observable { + // TODO + return Observable.empty() + } + + override fun cancelTempBasal(): Observable { + // TODO + return Observable.empty() + } + + override fun bolus(amount: Double): Observable { + // TODO + return Observable.empty() + } + + override fun cancelBolus(): Observable { + // TODO + return Observable.empty() + } +} \ No newline at end of file From acfd40e6d1d1512bdd95a4f0e668b5b132951103 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 02:49:13 +0100 Subject: [PATCH 018/649] Add methods to OmnipodDashManager --- .../pump/omnipod/dash/driver/OmnipodDashManager.kt | 4 ++++ .../pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index 1c4e63ea99..153bcfd9b6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -25,4 +25,8 @@ interface OmnipodDashManager { fun bolus(amount: Double): Observable fun cancelBolus(): Observable + + fun silenceAlerts(): Observable + + fun deactivatePod(): Observable } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index af4e3c8700..f80e6bc207 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -65,4 +65,14 @@ class OmnipodDashManagerImpl @Inject constructor( // TODO return Observable.empty() } + + override fun silenceAlerts(): Observable { + // TODO + return Observable.empty() + } + + override fun deactivatePod(): Observable { + // TODO + return Observable.empty() + } } \ No newline at end of file From cc3b9b7f32327f766e8a76c3bdb06445f07279c6 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 04:12:11 +0100 Subject: [PATCH 019/649] Copied from OmnipodErosOverviewFragment to OmnipodDashOverviewFragment and added lots of TODOS there --- .../omnipod_common_overview_pod_info.xml | 4 +- .../dash/EventOmnipodDashPumpValuesChanged.kt | 6 + .../omnipod/dash/driver/OmnipodDashManager.kt | 2 +- .../dash/driver/OmnipodDashManagerImpl.kt | 2 +- .../dash/driver/{pod => }/event/PodEvent.kt | 2 +- .../driver/{pod => }/event/PodEventType.kt | 5 +- .../driver/pod/definition/BasalProgram.kt | 2 + .../dash/driver/pod/definition/PodStatus.kt | 20 +- .../pod/state/OmnipodDashPodStateManager.kt | 4 + .../state/OmnipodDashPodStateManagerImpl.kt | 9 + .../dash/ui/OmnipodDashOverviewFragment.kt | 537 ++++++++++++++++++ ...omnipod_dash_overview_bluetooth_status.xml | 4 +- omnipod-dash/src/main/res/values/strings.xml | 5 +- .../eros/ui/OmnipodErosOverviewFragment.kt | 8 +- 14 files changed, 595 insertions(+), 15 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/{pod => }/event/PodEvent.kt (90%) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/{pod => }/event/PodEventType.kt (77%) diff --git a/omnipod-common/src/main/res/layout/omnipod_common_overview_pod_info.xml b/omnipod-common/src/main/res/layout/omnipod_common_overview_pod_info.xml index 9cb7ae62dc..350b59a645 100644 --- a/omnipod-common/src/main/res/layout/omnipod_common_overview_pod_info.xml +++ b/omnipod-common/src/main/res/layout/omnipod_common_overview_pod_info.xml @@ -32,7 +32,7 @@ tools:ignore="HardcodedText" /> ) { fun isZeroBasal() = segments.sumBy(Segment::basalRateInHundredthUnitsPerHour) == 0 + fun rateAt(date: Date): Double = 0.0 // TODO + class Segment(val startSlotIndex: Short, val endSlotIndex: Short, val basalRateInHundredthUnitsPerHour: Int) { fun getPulsesPerHour(): Short { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt index f62c5560d0..9fc650caa5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt @@ -1,7 +1,23 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class PodStatus(private val value: Byte) { - UNINITIALIZED(0x00.toByte()), MFG_TEST(0x01.toByte()), FILLED(0x02.toByte()), UID_SET(0x03.toByte()), ENGAGING_CLUTCH_DRIVE(0x04.toByte()), CLUTCH_DRIVE_ENGAGED(0x05.toByte()), BASAL_PROGRAM_RUNNING(0x06.toByte()), PRIMING(0x07.toByte()), RUNNING_ABOVE_MIN_VOLUME(0x08.toByte()), RUNNING_BELOW_MIN_VOLUME(0x09.toByte()), UNUSED_10(0x0a.toByte()), UNUSED_11(0x0b.toByte()), UNUSED_12(0x0c.toByte()), ALARM(0x0d.toByte()), LUMP_OF_COAL(0x0e.toByte()), DEACTIVATED(0x0f.toByte()), UNKNOWN(0xff.toByte()); + UNINITIALIZED(0x00.toByte()), + MFG_TEST(0x01.toByte()), + FILLED(0x02.toByte()), + UID_SET(0x03.toByte()), + ENGAGING_CLUTCH_DRIVE(0x04.toByte()), + CLUTCH_DRIVE_ENGAGED(0x05.toByte()), + BASAL_PROGRAM_SET(0x06.toByte()), + PRIMING(0x07.toByte()), + RUNNING_ABOVE_MIN_VOLUME(0x08.toByte()), + RUNNING_BELOW_MIN_VOLUME(0x09.toByte()), + UNUSED_10(0x0a.toByte()), + UNUSED_11(0x0b.toByte()), + UNUSED_12(0x0c.toByte()), + ALARM(0x0d.toByte()), + LUMP_OF_COAL(0x0e.toByte()), + DEACTIVATED(0x0f.toByte()), + UNKNOWN(0xff.toByte()); companion object { @@ -14,4 +30,6 @@ enum class PodStatus(private val value: Byte) { return UNKNOWN } } + + fun isRunning(): Boolean = this == RUNNING_ABOVE_MIN_VOLUME || this == RUNNING_BELOW_MIN_VOLUME } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index 0a390622f6..85e959d5ec 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -11,6 +11,10 @@ import java.util.* interface OmnipodDashPodStateManager { var activationProgress: ActivationProgress + val isUniqueIdSet: Boolean + val isActivationCompleted: Boolean + val isSuspended: Boolean + val isPodRunning: Boolean var lastConnection: Long val lastUpdated: Long diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index bd7838428e..b9df5b487a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -34,6 +34,15 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( store() } + override val isUniqueIdSet: Boolean = activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) + + override val isActivationCompleted: Boolean = activationProgress == ActivationProgress.COMPLETED + + override val isSuspended: Boolean = podState.deliveryStatus?.equals(DeliveryStatus.SUSPENDED) + ?: true + + override val isPodRunning: Boolean = podState.podStatus?.isRunning() ?: false + override var lastConnection: Long get() = podState.lastConnection set(value) { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt index 295afbf47b..223547e68a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt @@ -1,18 +1,82 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui import android.content.Intent +import android.graphics.Color import android.os.Bundle +import android.os.Handler +import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.activities.ErrorHelperActivity +import info.nightscout.androidaps.events.EventPreferenceChange +import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewButtonsBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonOverviewPodInfoBinding +import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandAcknowledgeAlerts +import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandHandleTimeChange +import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandResumeDelivery +import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandSuspendDelivery +import info.nightscout.androidaps.plugins.pump.omnipod.dash.EventOmnipodDashPumpValuesChanged +import info.nightscout.androidaps.plugins.pump.omnipod.dash.OmnipodDashPumpPlugin +import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashOverviewBinding import info.nightscout.androidaps.plugins.pump.omnipod.dash.databinding.OmnipodDashOverviewBluetoothStatusBinding +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.queue.events.EventQueueChanged +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.alertDialogs.OKDialog +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.sharedPreferences.SP +import info.nightscout.androidaps.utils.ui.UIRunnable +import io.reactivex.disposables.CompositeDisposable +import io.reactivex.rxkotlin.plusAssign +import org.apache.commons.lang3.StringUtils +import org.joda.time.Duration +import java.util.* +import javax.inject.Inject +import kotlin.collections.ArrayList +// TODO generify; see OmnipodErosOverviewFragment class OmnipodDashOverviewFragment : DaggerFragment() { + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var omnipodDashPumpPlugin: OmnipodDashPumpPlugin + @Inject lateinit var podStateManager: OmnipodDashPodStateManager + @Inject lateinit var sp: SP + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var aapsSchedulers: AapsSchedulers + + companion object { + + private const val REFRESH_INTERVAL_MILLIS = 15 * 1000L // 15 seconds + private const val PLACEHOLDER = "-" + } + + private var disposables: CompositeDisposable = CompositeDisposable() + + private val loopHandler = Handler(Looper.getMainLooper()) + private lateinit var refreshLoop: Runnable + + init { + refreshLoop = Runnable { + activity?.runOnUiThread { updateUi() } + loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) + } + } + var _binding: OmnipodDashOverviewBinding? = null var _bluetoothStatusBinding: OmnipodDashOverviewBluetoothStatusBinding? = null var _podInfoBinding: OmnipodCommonOverviewPodInfoBinding? = null @@ -37,7 +101,480 @@ class OmnipodDashOverviewFragment : DaggerFragment() { super.onViewCreated(view, savedInstanceState) buttonBinding.buttonPodManagement.setOnClickListener { + // TODO add protection startActivity(Intent(context, DashPodManagementActivity::class.java)) } + + buttonBinding.buttonResumeDelivery.setOnClickListener { + disablePodActionButtons() + commandQueue.customCommand(CommandResumeDelivery(), + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_delivery_resumed))) + } + + buttonBinding.buttonRefreshStatus.setOnClickListener { + disablePodActionButtons() + commandQueue.readStatus("REQUESTED BY USER", + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)) + } + + buttonBinding.buttonSilenceAlerts.setOnClickListener { + disablePodActionButtons() + commandQueue.customCommand(CommandAcknowledgeAlerts(), + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false) + .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_silenced_alerts)) + .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) }) + } + + buttonBinding.buttonSuspendDelivery.setOnClickListener { + disablePodActionButtons() + commandQueue.customCommand(CommandSuspendDelivery(), + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true) + .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_suspended_delivery))) + } + + buttonBinding.buttonSetTime.setOnClickListener { + disablePodActionButtons() + commandQueue.customCommand(CommandHandleTimeChange(true), + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_set_time), true) + .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_time_on_pod_updated))) + } + } + + override fun onResume() { + super.onResume() + loopHandler.postDelayed(refreshLoop, REFRESH_INTERVAL_MILLIS) + disposables += rxBus + .toObservable(EventOmnipodDashPumpValuesChanged::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ + updateOmnipodStatus() + updatePodActionButtons() + }, fabricPrivacy::logException) + disposables += rxBus + .toObservable(EventQueueChanged::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ + updateQueueStatus() + updatePodActionButtons() + }, fabricPrivacy::logException) + disposables += rxBus + .toObservable(EventPreferenceChange::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ + updatePodActionButtons() + }, fabricPrivacy::logException) + updateUi() + } + + override fun onPause() { + super.onPause() + disposables.clear() + loopHandler.removeCallbacks(refreshLoop) + } + + @Synchronized + override fun onDestroyView() { + super.onDestroyView() + _binding = null + } + + private fun updateUi() { + // TODO update bluetooth status + updateOmnipodStatus() + updatePodActionButtons() + updateQueueStatus() + } + + private fun updateOmnipodStatus() { + updateLastConnection() + updateLastBolus() + updateTempBasal() + updatePodStatus() + + val errors = ArrayList() + + if (podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID)) { + podInfoBinding.uniqueId.text = PLACEHOLDER + podInfoBinding.podLot.text = PLACEHOLDER + podInfoBinding.podSequenceNumber.text = PLACEHOLDER + podInfoBinding.firmwareVersion.text = PLACEHOLDER + podInfoBinding.timeOnPod.text = PLACEHOLDER + podInfoBinding.podExpiryDate.text = PLACEHOLDER + podInfoBinding.podExpiryDate.setTextColor(Color.WHITE) + podInfoBinding.baseBasalRate.text = PLACEHOLDER + podInfoBinding.totalDelivered.text = PLACEHOLDER + podInfoBinding.reservoir.text = PLACEHOLDER + podInfoBinding.reservoir.setTextColor(Color.WHITE) + podInfoBinding.podActiveAlerts.text = PLACEHOLDER + } else { + podInfoBinding.uniqueId.text = podStateManager.uniqueId.toString() + podInfoBinding.podLot.text = podStateManager.lotNumber.toString() + podInfoBinding.podSequenceNumber.text = podStateManager.podSequenceNumber.toString() + podInfoBinding.firmwareVersion.text = resourceHelper.gs(R.string.omnipod_dash_overview_firmware_version_value, podStateManager.firmwareVersion.toString(), podStateManager.bluetoothVersion.toString()) + + // TODO + /* + podInfoBinding.timeOnPod.text = readableZonedTime(podStateManager.time) + podInfoBinding.timeOnPod.setTextColor(if (podStateManager.timeDeviatesMoreThan(OmnipodConstants.TIME_DEVIATION_THRESHOLD)) { + Color.RED + } else { + Color.WHITE + }) + */ + + // TODO + /* + val expiresAt = podStateManager.expiresAt + + if (expiresAt == null) { + podInfoBinding.podExpiryDate.text = PLACEHOLDER + podInfoBinding.podExpiryDate.setTextColor(Color.WHITE) + } else { + podInfoBinding.podExpiryDate.text = readableZonedTime(expiresAt) + podInfoBinding.podExpiryDate.setTextColor(if (DateTime.now().isAfter(expiresAt)) { + Color.RED + } else { + Color.WHITE + }) + } + */ + + /* TODO + if (podStateManager.isPodFaulted) { + val faultEventCode = podStateManager.faultEventCode + errors.add(resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault_description, faultEventCode.value, faultEventCode.name)) + } + */ + + // base basal rate + podInfoBinding.baseBasalRate.text = if (podStateManager.basalProgram != null) { + resourceHelper.gs(R.string.pump_basebasalrate, omnipodDashPumpPlugin.model().determineCorrectBasalSize(podStateManager.basalProgram!!.rateAt(Date()))) + } else { + PLACEHOLDER + } + + // total delivered + podInfoBinding.totalDelivered.text = if (podStateManager.isActivationCompleted && podStateManager.pulsesDelivered != null) { + resourceHelper.gs(R.string.omnipod_common_overview_total_delivered_value, podStateManager.pulseRate) + } else { + PLACEHOLDER + } + + // reservoir + if (podStateManager.pulsesRemaining == null) { + podInfoBinding.reservoir.text = resourceHelper.gs(R.string.omnipod_common_overview_reservoir_value_over50) + podInfoBinding.reservoir.setTextColor(Color.WHITE) + } else { + // TODO + //val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits + // ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() + val lowReservoirThreshold: Short = 20 + + podInfoBinding.reservoir.text = resourceHelper.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.pulsesRemaining) + podInfoBinding.reservoir.setTextColor(if (podStateManager.pulsesRemaining!! < lowReservoirThreshold) { + Color.RED + } else { + Color.WHITE + }) + } + + podInfoBinding.podActiveAlerts.text = if (podStateManager.activeAlerts!!.size > 0) { + // TODO + // TextUtils.join(System.lineSeparator(), omnipodUtil.getTranslatedActiveAlerts(podStateManager)) + "TODO" + } else { + PLACEHOLDER + } + } + + if (errors.size == 0) { + podInfoBinding.errors.text = PLACEHOLDER + podInfoBinding.errors.setTextColor(Color.WHITE) + } else { + podInfoBinding.errors.text = StringUtils.join(errors, System.lineSeparator()) + podInfoBinding.errors.setTextColor(Color.RED) + } + } + + private fun updateLastConnection() { + if (podStateManager.isUniqueIdSet) { + podInfoBinding.lastConnection.text = readableDuration(podStateManager.lastConnection) + val lastConnectionColor = + if (omnipodDashPumpPlugin.isUnreachableAlertTimeoutExceeded(getPumpUnreachableTimeout().millis)) { + Color.RED + } else { + Color.WHITE + } + podInfoBinding.lastConnection.setTextColor(lastConnectionColor) + } else { + podInfoBinding.lastConnection.setTextColor(Color.WHITE) + podInfoBinding.lastConnection.text = readableDuration(podStateManager.lastConnection) + } + } + + private fun updatePodStatus() { + podInfoBinding.podStatus.text = if (podStateManager.activationProgress == ActivationProgress.NOT_STARTED) { + resourceHelper.gs(R.string.omnipod_common_pod_status_no_active_pod) + } else if (!podStateManager.isActivationCompleted) { + if (!podStateManager.isUniqueIdSet) { + resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_activation) + } else { + if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { + resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_activation) + } else { + resourceHelper.gs(R.string.omnipod_common_pod_status_waiting_for_cannula_insertion) + } + } + } else { + if (podStateManager.podStatus!!.isRunning()) { + if (podStateManager.isSuspended) { + resourceHelper.gs(R.string.omnipod_common_pod_status_suspended) + } else { + resourceHelper.gs(R.string.omnipod_common_pod_status_running) + } + // TODO + /* + } else if (podStateManager.podStatus == PodProgressStatus.FAULT_EVENT_OCCURRED) { + resourceHelper.gs(R.string.omnipod_common_pod_status_pod_fault) + } else if (podStateManager.podStatus == PodProgressStatus.INACTIVE) { + resourceHelper.gs(R.string.omnipod_common_pod_status_inactive) + */ + } else { + podStateManager.podStatus.toString() + } + } + + val podStatusColor = if (!podStateManager.isActivationCompleted ||/* TODO podStateManager.isPodDead || */ podStateManager.isSuspended) { + Color.RED + } else { + Color.WHITE + } + podInfoBinding.podStatus.setTextColor(podStatusColor) + } + + private fun updateLastBolus() { + // TODO + /* + if (podStateManager.isActivationCompleted && podStateManager.hasLastBolus()) { + var text = resourceHelper.gs(R.string.omnipod_common_overview_last_bolus_value, omnipodDashPumpPlugin.model().determineCorrectBolusSize(podStateManager.lastBolusAmount), resourceHelper.gs(R.string.insulin_unit_shortname), readableDuration(podStateManager.lastBolusStartTime)) + val textColor: Int + + if (podStateManager.isLastBolusCertain) { + textColor = Color.WHITE + } else { + textColor = Color.RED + text += " (" + resourceHelper.gs(R.string.omnipod_eros_uncertain) + ")" + } + + podInfoBinding.lastBolus.text = text + podInfoBinding.lastBolus.setTextColor(textColor) + + } else { + podInfoBinding.lastBolus.text = PLACEHOLDER + podInfoBinding.lastBolus.setTextColor(Color.WHITE) + } + */ + } + + private fun updateTempBasal() { + if (podStateManager.isActivationCompleted && podStateManager.tempBasalActive) { + val startTime = podStateManager.tempBasal!!.startTime + val rate = podStateManager.tempBasal!!.rate + val duration = podStateManager.tempBasal!!.durationInMinutes + + val minutesRunning = 0 // TODO + + podInfoBinding.tempBasal.text = resourceHelper.gs(R.string.omnipod_common_overview_temp_basal_value, rate, dateUtil.timeString(startTime), minutesRunning, duration) + } else { + podInfoBinding.tempBasal.text = PLACEHOLDER + } + } + + private fun updateQueueStatus() { + if (isQueueEmpty()) { + podInfoBinding.queue.visibility = View.GONE + } else { + podInfoBinding.queue.visibility = View.VISIBLE + podInfoBinding.queue.text = commandQueue.spannedStatus().toString() + } + } + + private fun updatePodActionButtons() { + updateRefreshStatusButton() + updateResumeDeliveryButton() + updateSilenceAlertsButton() + updateSuspendDeliveryButton() + updateSetTimeButton() + } + + private fun disablePodActionButtons() { + buttonBinding.buttonSilenceAlerts.isEnabled = false + buttonBinding.buttonResumeDelivery.isEnabled = false + buttonBinding.buttonSuspendDelivery.isEnabled = false + buttonBinding.buttonSetTime.isEnabled = false + buttonBinding.buttonRefreshStatus.isEnabled = false + } + + private fun updateRefreshStatusButton() { + buttonBinding.buttonRefreshStatus.isEnabled = podStateManager.isUniqueIdSet && podStateManager.activationProgress.isAtLeast(ActivationProgress.PHASE_1_COMPLETED) + && isQueueEmpty() + } + + private fun updateResumeDeliveryButton() { + if (podStateManager.isPodRunning && (podStateManager.isSuspended || commandQueue.isCustomCommandInQueue(CommandResumeDelivery::class.java))) { + buttonBinding.buttonResumeDelivery.visibility = View.VISIBLE + buttonBinding.buttonResumeDelivery.isEnabled = isQueueEmpty() + } else { + buttonBinding.buttonResumeDelivery.visibility = View.GONE + } + } + + private fun updateSilenceAlertsButton() { + if (isAutomaticallySilenceAlertsEnabled() && podStateManager.isPodRunning && (podStateManager.activeAlerts!!.size > 0 || commandQueue.isCustomCommandInQueue(CommandAcknowledgeAlerts::class.java))) { + buttonBinding.buttonSilenceAlerts.visibility = View.VISIBLE + buttonBinding.buttonSilenceAlerts.isEnabled = isQueueEmpty() + } else { + buttonBinding.buttonSilenceAlerts.visibility = View.GONE + } + } + + private fun updateSuspendDeliveryButton() { + // If the Pod is currently suspended, we show the Resume delivery button instead. + if (isSuspendDeliveryButtonEnabled() && podStateManager.isPodRunning && (!podStateManager.isSuspended || commandQueue.isCustomCommandInQueue(CommandSuspendDelivery::class.java))) { + buttonBinding.buttonSuspendDelivery.visibility = View.VISIBLE + buttonBinding.buttonSuspendDelivery.isEnabled = podStateManager.isPodRunning && !podStateManager.isSuspended && isQueueEmpty() + } else { + buttonBinding.buttonSuspendDelivery.visibility = View.GONE + } + } + + private fun updateSetTimeButton() { + // TODO + /* + if (podStateManager.isPodRunning && (podStateManager.timeDeviatesMoreThan(Duration.standardMinutes(5)) || commandQueue.isCustomCommandInQueue(CommandHandleTimeChange::class.java))) { + buttonBinding.buttonSetTime.visibility = View.VISIBLE + buttonBinding.buttonSetTime.isEnabled = !podStateManager.isSuspended && rileyLinkServiceData.rileyLinkServiceState.isReady && isQueueEmpty() + } else { + buttonBinding.buttonSetTime.visibility = View.GONE + } + */ + } + + private fun isAutomaticallySilenceAlertsEnabled(): Boolean { + return sp.getBoolean(R.string.omnipod_common_preferences_automatically_silence_alerts, false) + } + + private fun isSuspendDeliveryButtonEnabled(): Boolean { + return sp.getBoolean(R.string.omnipod_common_preferences_suspend_delivery_button_enabled, false) + } + + private fun displayErrorDialog(title: String, message: String, withSound: Boolean) { + context?.let { + ErrorHelperActivity.runAlarm(it, message, title, if (withSound) R.raw.boluserror else 0) + } + } + + private fun displayOkDialog(title: String, message: String) { + context?.let { + UIRunnable { + OKDialog.show(it, title, message, null) + }.run() + } + } + + /* + private fun readableZonedTime(time: DateTime): String { + val timeAsJavaData = time.toLocalDateTime().toDate() + val timeZone = podStateManager.timeZone.toTimeZone() + if (timeZone == TimeZone.getDefault()) { + return dateUtil.dateAndTimeString(timeAsJavaData) + } + + val isDaylightTime = timeZone.inDaylightTime(timeAsJavaData) + val locale = resources.configuration.locales.get(0) + val timeZoneDisplayName = timeZone.getDisplayName(isDaylightTime, TimeZone.SHORT, locale) + " " + timeZone.getDisplayName(isDaylightTime, TimeZone.LONG, locale) + return resourceHelper.gs(R.string.omnipod_common_time_with_timezone, dateUtil.dateAndTimeString(timeAsJavaData), timeZoneDisplayName) + } + */ + + private fun readableDuration(time: Long): String { + // TODO + return "TODO" + + /* + val duration = Duration(dateTime, DateTime.now()) + val hours = duration.standardHours.toInt() + val minutes = duration.standardMinutes.toInt() + val seconds = duration.standardSeconds.toInt() + when { + seconds < 10 -> { + return resourceHelper.gs(R.string.omnipod_common_moments_ago) + } + + seconds < 60 -> { + return resourceHelper.gs(R.string.omnipod_common_less_than_a_minute_ago) + } + + seconds < 60 * 60 -> { // < 1 hour + return resourceHelper.gs(R.string.omnipod_common_time_ago, resourceHelper.gq(R.plurals.omnipod_common_minutes, minutes, minutes)) + } + + seconds < 24 * 60 * 60 -> { // < 1 day + val minutesLeft = minutes % 60 + if (minutesLeft > 0) + return resourceHelper.gs(R.string.omnipod_common_time_ago, + resourceHelper.gs(R.string.omnipod_common_composite_time, resourceHelper.gq(R.plurals.omnipod_common_hours, hours, hours), resourceHelper.gq(R.plurals.omnipod_common_minutes, minutesLeft, minutesLeft))) + return resourceHelper.gs(R.string.omnipod_common_time_ago, resourceHelper.gq(R.plurals.omnipod_common_hours, hours, hours)) + } + + else -> { + val days = hours / 24 + val hoursLeft = hours % 24 + if (hoursLeft > 0) + return resourceHelper.gs(R.string.omnipod_common_time_ago, + resourceHelper.gs(R.string.omnipod_common_composite_time, resourceHelper.gq(R.plurals.omnipod_common_days, days, days), resourceHelper.gq(R.plurals.omnipod_common_hours, hoursLeft, hoursLeft))) + return resourceHelper.gs(R.string.omnipod_common_time_ago, resourceHelper.gq(R.plurals.omnipod_common_days, days, days)) + } + } + */ + } + + private fun isQueueEmpty(): Boolean { + return commandQueue.size() == 0 && commandQueue.performing() == null + } + + // FIXME ideally we should just have access to LocalAlertUtils here + private fun getPumpUnreachableTimeout(): Duration { + return Duration.standardMinutes(sp.getInt(R.string.key_pump_unreachable_threshold_minutes, Constants.DEFAULT_PUMP_UNREACHABLE_THRESHOLD_MINUTES).toLong()) + } + + inner class DisplayResultDialogCallback(private val errorMessagePrefix: String, private val withSoundOnError: Boolean) : Callback() { + + private var messageOnSuccess: String? = null + private var actionOnSuccess: Runnable? = null + + override fun run() { + if (result.success) { + val messageOnSuccess = this.messageOnSuccess + if (messageOnSuccess != null) { + displayOkDialog(resourceHelper.gs(R.string.omnipod_common_confirmation), messageOnSuccess) + } + actionOnSuccess?.run() + } else { + displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, errorMessagePrefix, result.comment), withSoundOnError) + } + } + + fun messageOnSuccess(message: String): DisplayResultDialogCallback { + messageOnSuccess = message + return this + } + + fun actionOnSuccess(action: Runnable): DisplayResultDialogCallback { + actionOnSuccess = action + return this + } + } + } \ No newline at end of file diff --git a/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml b/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml index 16d1031ed9..d9d95b3a60 100644 --- a/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml +++ b/omnipod-dash/src/main/res/layout/omnipod_dash_overview_bluetooth_status.xml @@ -13,7 +13,7 @@ android:gravity="end" android:paddingStart="5dp" android:paddingEnd="5dp" - android:text="@string/omnipod_dash_bluetooth_address" + android:text="@string/omnipod_dash_overview_bluetooth_address" android:textSize="14sp" /> AAPS.OmnipodDash.pod_state - Bluetooth Status - Bluetooth Address + Bluetooth Status + Bluetooth Address + Firmware %1$s / Bluetooth %2$s Fill a new Pod with enough insulin for 3 days.\n\nListen for two beeps from the Pod during the filling process. These indicate that the minimum amount of 85U has been inserted. Be sure to completely empty the fill syringe, even after hearing the two beeps.\n\nAfter filling the Pod, please press Next.\n\nNote: do not remove the Pod\'s needle cap at this time. diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt index 1b232a6527..8834725c26 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt @@ -254,13 +254,13 @@ class OmnipodErosOverviewFragment : DaggerFragment() { } if (!podStateManager.hasPodState() || !podStateManager.isPodInitialized) { - podInfoBinding.podAddress.text = if (podStateManager.hasPodState()) { + podInfoBinding.uniqueId.text = if (podStateManager.hasPodState()) { podStateManager.address.toString() } else { PLACEHOLDER } podInfoBinding.podLot.text = PLACEHOLDER - podInfoBinding.podTid.text = PLACEHOLDER + podInfoBinding.podSequenceNumber.text = PLACEHOLDER podInfoBinding.firmwareVersion.text = PLACEHOLDER podInfoBinding.timeOnPod.text = PLACEHOLDER podInfoBinding.podExpiryDate.text = PLACEHOLDER @@ -271,9 +271,9 @@ class OmnipodErosOverviewFragment : DaggerFragment() { podInfoBinding.reservoir.setTextColor(Color.WHITE) podInfoBinding.podActiveAlerts.text = PLACEHOLDER } else { - podInfoBinding.podAddress.text = podStateManager.address.toString() + podInfoBinding.uniqueId.text = podStateManager.address.toString() podInfoBinding.podLot.text = podStateManager.lot.toString() - podInfoBinding.podTid.text = podStateManager.tid.toString() + podInfoBinding.podSequenceNumber.text = podStateManager.tid.toString() podInfoBinding.firmwareVersion.text = resourceHelper.gs(R.string.omnipod_eros_overview_firmware_version_value, podStateManager.pmVersion.toString(), podStateManager.piVersion.toString()) podInfoBinding.timeOnPod.text = readableZonedTime(podStateManager.time) From 1a12d6cd9dc46922a4dddd382e44f5ccd98d896f Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 10:04:33 +0100 Subject: [PATCH 020/649] Formatting after Kotlin conversion --- .../omnipod/dash/OmnipodDashPumpPlugin.kt | 4 +- .../dash/driver/pod/command/base/Command.kt | 3 +- .../dash/driver/pod/definition/AlarmType.kt | 156 +++++++++++++++++- .../pod/definition/AlertConfiguration.kt | 12 +- .../dash/driver/pod/definition/AlertSlot.kt | 10 +- .../driver/pod/definition/AlertTriggerType.kt | 3 +- .../pod/definition/BeepRepetitionType.kt | 3 +- .../dash/driver/pod/definition/BeepType.kt | 6 +- .../driver/pod/definition/DeliveryStatus.kt | 8 +- .../driver/pod/definition/NakErrorType.kt | 31 +++- .../driver/pod/definition/OmnipodEvent.kt | 7 - .../pod/response/ActivationResponseBase.kt | 5 +- .../pod/response/AlarmStatusResponse.kt | 5 +- .../dash/driver/pod/response/Response.kt | 4 +- .../dash/driver/pod/response/ResponseBase.kt | 5 +- .../dash/driver/pod/response/ResponseType.kt | 11 +- .../pod/response/SetUniqueIdResponse.kt | 1 + .../driver/pod/response/VersionResponse.kt | 20 ++- 18 files changed, 259 insertions(+), 35 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index 939c480276..4f6b4e7e8c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -28,8 +28,8 @@ class OmnipodDashPumpPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, - commandQueue: CommandQueueProvider) - : PumpPluginBase(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue), PumpInterface { + commandQueue: CommandQueueProvider +) : PumpPluginBase(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue), PumpInterface { companion object { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt index 4675d5199b..bbe29cb2e5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt @@ -1,8 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import java.io.Serializable -interface Command : Encodable { +interface Command : Encodable, Serializable { val commandType: CommandType } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt index b6b59da23f..6e80e8a676 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt @@ -1,7 +1,161 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class AlarmType(private val value: Byte) { - NONE(0x00.toByte()), ALARM_PW_FLASH_ERASE(0x01.toByte()), ALARM_PW_FLASH_WRITE(0x02.toByte()), ALARM_BASAL_CKSUM(0x03.toByte()), ALARM_BASAL_PPULSE(0x04.toByte()), ALARM_BASAL_STEP(0x05.toByte()), ALARM_AUTO_WAKEUP_TIMEOUT(0x06.toByte()), ALARM_WIRE_OVERDRIVEN(0x07.toByte()), ALARM_BEEP_REP_INVALID_INDEX(0x08.toByte()), ALARM_INVALID_REP_PATTERN(0x09.toByte()), ALARM_TEMP_BASAL_STEP(0x0a.toByte()), ALARM_TEMP_BASAL_CKSUM(0x0b.toByte()), ALARM_BOLUS_OVERFLOW(0x0c.toByte()), ALARM_COP_RESET(0x0d.toByte()), ALARM_ILOP_RESET(0x0e.toByte()), ALARM_ILAD_RESET(0x0f.toByte()), ALARM_SAWCOP_RESET(0x10.toByte()), ALARM_BOLUS_STEP(0x11.toByte()), ALARM_LVD_RESET(0x12.toByte()), ALARM_INVALID_RF_MSG_LENGTH(0x13.toByte()), ALARM_OCCLUDED(0x14.toByte()), ALARM_BOLUSPROG_CHKSUM(0x15.toByte()), ALARM_BOLUS_LOG(0x16.toByte()), ALARM_CRITICAL_VAR(0x17.toByte()), ALARM_EMPTY_RESERVOIR(0x18.toByte()), ALARM_LOADERR(0x19.toByte()), ALARM_PSA_FAILURE(0x1a.toByte()), ALARM_TICKCNT_NOT_CLEARED(0x1b.toByte()), ALARM_PUMP_EXPIRED(0x1c.toByte()), ALARM_COMD_BIT_NOT_SET(0x1d.toByte()), ALARM_INVALID_COMD_SET(0x1e.toByte()), ALARM_ALERTS_ARRAY_CKSM(0x1f.toByte()), ALARM_UNIT_TEST(0x20.toByte()), ALARM_TICK_TIME_ERROR(0x21.toByte()), ALARM_CRITICAL_HAZARD(0x22.toByte()), ALARM_PIEZO_FREQ(0x23.toByte()), ALARM_TICKCNT_ERROR_RTC(0x24.toByte()), ALARM_TICK_FAILURE(0x25.toByte()), ALARM_INVALID(0x26.toByte()), ALARM_LUMP_ALERT_PROGRAM(0x27.toByte()), ALARM_INVALID_PASS_CODE(0x28.toByte()), ALARM_ALERT0(0x29.toByte()), ALARM_ALERT1(0x2a.toByte()), ALARM_ALERT2(0x2b.toByte()), ALARM_ALERT3(0x2c.toByte()), ALARM_ALERT4(0x2d.toByte()), ALARM_ALERT5(0x2e.toByte()), ALARM_ALERT6(0x2f.toByte()), ALARM_ALERT7(0x30.toByte()), ALARM_ILLEGAL_PUMP_STATE(0x31.toByte()), ALARM_COP_TEST_FAILURE(0x32.toByte()), ALARM_MCTF(0x33.toByte()), ALARM_ILLEGAL_RESET(0x34.toByte()), ALARM_VETO_NOT_SET(0x35.toByte()), ALARM_ILLEGAL_PIN_RESET(0x36.toByte()), ALARM_INVALID_BEEP_PATTERN(0x37.toByte()), ALARM_WIRE_STATE_MACHINE(0x38.toByte()), ALARM_VETO_TEST_DEFAULT(0x39.toByte()), ALARM_ALERT_INVALID_INDEX(0x3a.toByte()), ALARM_SAWCOP_TEST_FAIL(0x3b.toByte()), ALARM_MCUCOP_TEST_FAIL(0x3c.toByte()), ALARM_STEP_SENSOR_SHORTED(0x3d.toByte()), ALARM_FLASH_FAILURE(0x3e.toByte()), ALARM_SPARE63(0x3f.toByte()), ALARM_SS_OPEN_CNT_EXCEEDED(0x40.toByte()), ALARM_SS_EXCESSIVE_SUMMED(0x41.toByte()), ALARM_SS_MIN_PULSE_TRANSITION(0x42.toByte()), ALARM_SS_DEFAULT(0x43.toByte()), ALARM_OPEN_WIRE1(0x44.toByte()), ALARM_OPEN_WIRE2(0x45.toByte()), ALARM_LOADERR_FAILURE(0x46.toByte()), ALARM_SAW_VETO_FAILURE(0x47.toByte()), ALARM_BAD_RFM_CLOCK(0x48.toByte()), ALARM_BAD_TICK_HIGH(0x49.toByte()), ALARM_BAD_TICK_PERIOD(0x4a.toByte()), ALARM_BAD_TRIM_VALUE(0x4b.toByte()), ALARM_BAD_BUS_CLOCK(0x4c.toByte()), ALARM_BAD_CAL_MODE(0x4d.toByte()), ALARM_SAW_TRIM_ERROR(0x4e.toByte()), ALARM_RFM_CRYSTAL_ERROR(0x4f.toByte()), ALARM_CALST_TIMEOUT(0x50.toByte()), ALARM_TICKCNT_ERROR(0x51.toByte()), ALARM_BAD_RFM_XTAL_START(0x52.toByte()), ALARM_BAD_RX_SENSENSITIVITY(0x53.toByte()), ALARM_BAD_TX_PKT_SIZE(0x54.toByte()), ALARM_TICK_LOW_PHASE_EXCEEDED(0x55.toByte()), ALARM_TICK_HIGH_PHASE_EXCEEDED(0x56.toByte()), ALARM_OCCL_CRITVAR_FAIL(0x57.toByte()), ALARM_OCCL_PARAM(0x58.toByte()), ALARM_PROG_OCCL_FAIL(0x59.toByte()), ALARM_PW_TO_HIGH_FOR_OCCL_DET(0x5a.toByte()), ALARM_OCCL_CSUM(0x5b.toByte()), ALARM_PRIME_OPEN_CNT_TO_LOW(0x5c.toByte()), ALARM_BAD_RF_CDTHR(0x5d.toByte()), ALARM_FLASH_NOT_SECURE(0x5e.toByte()), ALARM_WIRE_TEST_OPEN_GROUND(0x5f.toByte()), ALARM_OCCL_STARTUP1(0x60.toByte()), ALARM_OCCL_STARTUP2(0x61.toByte()), ALARM_OCCL_EXCESS_TIMEOUTS1(0x62.toByte()), ALARM_SPARE99(0x63.toByte()), ALARM_SPARE100(0x64.toByte()), ALARM_SPARE101(0x65.toByte()), ALARM_OCCL_EXCESS_TIMEOUTS2(0x66.toByte()), ALARM_OCCL_EXCESS_TIMEOUTS3(0x67.toByte()), ALARM_OCCL_NOISY_PULSE_WIDTHS(0x68.toByte()), ALARM_OCCL_AT_BOLUS_END(0x69.toByte()), ALARM_OCCL_ABOVE_THRESHOLD(0x6a.toByte()), ALARM_BASAL_UNDERINFUSION(0x80.toByte()), ALARM_BASAL_OVERINFUSION(0x81.toByte()), ALARM_TEMP_UNDERINFUSION(0x82.toByte()), ALARM_TEMP_OVERINFUSION(0x83.toByte()), ALARM_BOLUS_UNDERINFUSION(0x84.toByte()), ALARM_BOLUS_OVERINFUSION(0x85.toByte()), ALARM_BASAL_OVERINFUSION_PULSE(0x86.toByte()), ALARM_TEMP_OVERINFUSION_PULSE(0x87.toByte()), ALARM_BOLUS_OVERINFUSION_PULSE(0x88.toByte()), ALARM_IMMBOLUS_UNDERINFUSION_PULSE(0x89.toByte()), ALARM_EXTBOLUS_OVERINFUSION_PULSE(0x8a.toByte()), ALARM_PROGRAM_CSUM(0x8b.toByte()), ALARM_UNUSED_140(0x8c.toByte()), ALARM_UNRECOGNIZED_PULSE(0x8d.toByte()), ALARM_SYNC_WITHOUT_TEMP_ACTIVE(0x8e.toByte()), ALARM_INTERLOCK_LOAD(0x8f.toByte()), ALARM_ILLEGAL_CHAN_PARAM(0x90.toByte()), ALARM_BASAL_PULSE_CHAN_INACTIVE(0x91.toByte()), ALARM_TEMP_PULSE_CHAN_INACTIVE(0x92.toByte()), ALARM_BOLUS_PULSE_CHAN_INACTIVE(0x93.toByte()), ALARM_INT_SEMAPHORE_NOT_SET(0x94.toByte()), ALARM_ILLEGAL_INTERLOCK_CHAN(0x95.toByte()), ALARM_TERMINATE_BOLUS(0x96.toByte()), ALARM_OPEN_TRANSITIONS_COUNT(0x97.toByte()), ALARM_BLE_TO(0xa0.toByte()), ALARM_BLE_INITIATED(0xa1.toByte()), ALARM_BLE_UNK_ALARM(0xa2.toByte()), ALARM_UNUSED_163(0xa3.toByte()), ALARM_UNUSED_164(0xa4.toByte()), ALARM_UNUSED_165(0xa5.toByte()), ALARM_BLE_IAAS(0xa6.toByte()), ALARM_UNUSED_167(0xa7.toByte()), ALARM_CRC_FAILURE(0xa8.toByte()), ALARM_BLE_WD_PING_TIMEOUT(0xa9.toByte()), ALARM_BLE_EXCESSIVE_RESETS(0xaa.toByte()), ALARM_BLE_NAK_ERROR(0xab.toByte()), ALARM_BLE_REQ_HIGH_TIMEOUT(0xac.toByte()), ALARM_BLE_UNKNOWN_RESP(0xad.toByte()), ALARM_BLE_UNUSED_174(0xae.toByte()), ALARM_BLE_REQ_STUCK_HIGH(0xaf.toByte()), ALARM_BLE_STATE_MACHINE_1(0xb1.toByte()), ALARM_BLE_STATE_MACHINE_2(0xb2.toByte()), ALARM_BLE_UNUSED_179(0xb3.toByte()), ALARM_BLE_ARB_LOST(0xb4.toByte()), ALARM_BLE_ER48_DUAL_NACK(0xc0.toByte()), ALARM_BLE_QN_EXCEED_MAX_RETRY(0xc1.toByte()), ALARM_BLE_QN_CRIT_VAR_FAIL(0xc2.toByte()), UNKNOWN(0xff.toByte()); + NONE(0x00.toByte()), + ALARM_PW_FLASH_ERASE(0x01.toByte()), + ALARM_PW_FLASH_WRITE(0x02.toByte()), + ALARM_BASAL_CKSUM(0x03.toByte()), + ALARM_BASAL_PPULSE(0x04.toByte()), + ALARM_BASAL_STEP(0x05.toByte()), + ALARM_AUTO_WAKEUP_TIMEOUT(0x06.toByte()), + ALARM_WIRE_OVERDRIVEN(0x07.toByte()), + ALARM_BEEP_REP_INVALID_INDEX(0x08.toByte()), + ALARM_INVALID_REP_PATTERN(0x09.toByte()), + ALARM_TEMP_BASAL_STEP(0x0a.toByte()), + ALARM_TEMP_BASAL_CKSUM(0x0b.toByte()), + ALARM_BOLUS_OVERFLOW(0x0c.toByte()), + ALARM_COP_RESET(0x0d.toByte()), + ALARM_ILOP_RESET(0x0e.toByte()), + ALARM_ILAD_RESET(0x0f.toByte()), + ALARM_SAWCOP_RESET(0x10.toByte()), + ALARM_BOLUS_STEP(0x11.toByte()), + ALARM_LVD_RESET(0x12.toByte()), + ALARM_INVALID_RF_MSG_LENGTH(0x13.toByte()), + ALARM_OCCLUDED(0x14.toByte()), + ALARM_BOLUSPROG_CHKSUM(0x15.toByte()), + ALARM_BOLUS_LOG(0x16.toByte()), + ALARM_CRITICAL_VAR(0x17.toByte()), + ALARM_EMPTY_RESERVOIR(0x18.toByte()), + ALARM_LOADERR(0x19.toByte()), + ALARM_PSA_FAILURE(0x1a.toByte()), + ALARM_TICKCNT_NOT_CLEARED(0x1b.toByte()), + ALARM_PUMP_EXPIRED(0x1c.toByte()), + ALARM_COMD_BIT_NOT_SET(0x1d.toByte()), + ALARM_INVALID_COMD_SET(0x1e.toByte()), + ALARM_ALERTS_ARRAY_CKSM(0x1f.toByte()), + ALARM_UNIT_TEST(0x20.toByte()), + ALARM_TICK_TIME_ERROR(0x21.toByte()), + ALARM_CRITICAL_HAZARD(0x22.toByte()), + ALARM_PIEZO_FREQ(0x23.toByte()), + ALARM_TICKCNT_ERROR_RTC(0x24.toByte()), + ALARM_TICK_FAILURE(0x25.toByte()), + ALARM_INVALID(0x26.toByte()), + ALARM_LUMP_ALERT_PROGRAM(0x27.toByte()), + ALARM_INVALID_PASS_CODE(0x28.toByte()), + ALARM_ALERT0(0x29.toByte()), + ALARM_ALERT1(0x2a.toByte()), + ALARM_ALERT2(0x2b.toByte()), + ALARM_ALERT3(0x2c.toByte()), + ALARM_ALERT4(0x2d.toByte()), + ALARM_ALERT5(0x2e.toByte()), + ALARM_ALERT6(0x2f.toByte()), + ALARM_ALERT7(0x30.toByte()), + ALARM_ILLEGAL_PUMP_STATE(0x31.toByte()), + ALARM_COP_TEST_FAILURE(0x32.toByte()), + ALARM_MCTF(0x33.toByte()), + ALARM_ILLEGAL_RESET(0x34.toByte()), + ALARM_VETO_NOT_SET(0x35.toByte()), + ALARM_ILLEGAL_PIN_RESET(0x36.toByte()), + ALARM_INVALID_BEEP_PATTERN(0x37.toByte()), + ALARM_WIRE_STATE_MACHINE(0x38.toByte()), + ALARM_VETO_TEST_DEFAULT(0x39.toByte()), + ALARM_ALERT_INVALID_INDEX(0x3a.toByte()), + ALARM_SAWCOP_TEST_FAIL(0x3b.toByte()), + ALARM_MCUCOP_TEST_FAIL(0x3c.toByte()), + ALARM_STEP_SENSOR_SHORTED(0x3d.toByte()), + ALARM_FLASH_FAILURE(0x3e.toByte()), + ALARM_SPARE63(0x3f.toByte()), + ALARM_SS_OPEN_CNT_EXCEEDED(0x40.toByte()), + ALARM_SS_EXCESSIVE_SUMMED(0x41.toByte()), + ALARM_SS_MIN_PULSE_TRANSITION(0x42.toByte()), + ALARM_SS_DEFAULT(0x43.toByte()), + ALARM_OPEN_WIRE1(0x44.toByte()), + ALARM_OPEN_WIRE2(0x45.toByte()), + ALARM_LOADERR_FAILURE(0x46.toByte()), + ALARM_SAW_VETO_FAILURE(0x47.toByte()), + ALARM_BAD_RFM_CLOCK(0x48.toByte()), + ALARM_BAD_TICK_HIGH(0x49.toByte()), + ALARM_BAD_TICK_PERIOD(0x4a.toByte()), + ALARM_BAD_TRIM_VALUE(0x4b.toByte()), + ALARM_BAD_BUS_CLOCK(0x4c.toByte()), + ALARM_BAD_CAL_MODE(0x4d.toByte()), + ALARM_SAW_TRIM_ERROR(0x4e.toByte()), + ALARM_RFM_CRYSTAL_ERROR(0x4f.toByte()), + ALARM_CALST_TIMEOUT(0x50.toByte()), + ALARM_TICKCNT_ERROR(0x51.toByte()), + ALARM_BAD_RFM_XTAL_START(0x52.toByte()), + ALARM_BAD_RX_SENSENSITIVITY(0x53.toByte()), + ALARM_BAD_TX_PKT_SIZE(0x54.toByte()), + ALARM_TICK_LOW_PHASE_EXCEEDED(0x55.toByte()), + ALARM_TICK_HIGH_PHASE_EXCEEDED(0x56.toByte()), + ALARM_OCCL_CRITVAR_FAIL(0x57.toByte()), + ALARM_OCCL_PARAM(0x58.toByte()), + ALARM_PROG_OCCL_FAIL(0x59.toByte()), + ALARM_PW_TO_HIGH_FOR_OCCL_DET(0x5a.toByte()), + ALARM_OCCL_CSUM(0x5b.toByte()), + ALARM_PRIME_OPEN_CNT_TO_LOW(0x5c.toByte()), + ALARM_BAD_RF_CDTHR(0x5d.toByte()), + ALARM_FLASH_NOT_SECURE(0x5e.toByte()), + ALARM_WIRE_TEST_OPEN_GROUND(0x5f.toByte()), + ALARM_OCCL_STARTUP1(0x60.toByte()), + ALARM_OCCL_STARTUP2(0x61.toByte()), + ALARM_OCCL_EXCESS_TIMEOUTS1(0x62.toByte()), + ALARM_SPARE99(0x63.toByte()), + ALARM_SPARE100(0x64.toByte()), + ALARM_SPARE101(0x65.toByte()), + ALARM_OCCL_EXCESS_TIMEOUTS2(0x66.toByte()), + ALARM_OCCL_EXCESS_TIMEOUTS3(0x67.toByte()), + ALARM_OCCL_NOISY_PULSE_WIDTHS(0x68.toByte()), + ALARM_OCCL_AT_BOLUS_END(0x69.toByte()), + ALARM_OCCL_ABOVE_THRESHOLD(0x6a.toByte()), + ALARM_BASAL_UNDERINFUSION(0x80.toByte()), + ALARM_BASAL_OVERINFUSION(0x81.toByte()), + ALARM_TEMP_UNDERINFUSION(0x82.toByte()), + ALARM_TEMP_OVERINFUSION(0x83.toByte()), + ALARM_BOLUS_UNDERINFUSION(0x84.toByte()), + ALARM_BOLUS_OVERINFUSION(0x85.toByte()), + ALARM_BASAL_OVERINFUSION_PULSE(0x86.toByte()), + ALARM_TEMP_OVERINFUSION_PULSE(0x87.toByte()), + ALARM_BOLUS_OVERINFUSION_PULSE(0x88.toByte()), + ALARM_IMMBOLUS_UNDERINFUSION_PULSE(0x89.toByte()), + ALARM_EXTBOLUS_OVERINFUSION_PULSE(0x8a.toByte()), + ALARM_PROGRAM_CSUM(0x8b.toByte()), + ALARM_UNUSED_140(0x8c.toByte()), + ALARM_UNRECOGNIZED_PULSE(0x8d.toByte()), + ALARM_SYNC_WITHOUT_TEMP_ACTIVE(0x8e.toByte()), + ALARM_INTERLOCK_LOAD(0x8f.toByte()), + ALARM_ILLEGAL_CHAN_PARAM(0x90.toByte()), + ALARM_BASAL_PULSE_CHAN_INACTIVE(0x91.toByte()), + ALARM_TEMP_PULSE_CHAN_INACTIVE(0x92.toByte()), + ALARM_BOLUS_PULSE_CHAN_INACTIVE(0x93.toByte()), + ALARM_INT_SEMAPHORE_NOT_SET(0x94.toByte()), + ALARM_ILLEGAL_INTERLOCK_CHAN(0x95.toByte()), + ALARM_TERMINATE_BOLUS(0x96.toByte()), + ALARM_OPEN_TRANSITIONS_COUNT(0x97.toByte()), + ALARM_BLE_TO(0xa0.toByte()), + ALARM_BLE_INITIATED(0xa1.toByte()), + ALARM_BLE_UNK_ALARM(0xa2.toByte()), + ALARM_UNUSED_163(0xa3.toByte()), + ALARM_UNUSED_164(0xa4.toByte()), + ALARM_UNUSED_165(0xa5.toByte()), + ALARM_BLE_IAAS(0xa6.toByte()), + ALARM_UNUSED_167(0xa7.toByte()), + ALARM_CRC_FAILURE(0xa8.toByte()), + ALARM_BLE_WD_PING_TIMEOUT(0xa9.toByte()), + ALARM_BLE_EXCESSIVE_RESETS(0xaa.toByte()), + ALARM_BLE_NAK_ERROR(0xab.toByte()), + ALARM_BLE_REQ_HIGH_TIMEOUT(0xac.toByte()), + ALARM_BLE_UNKNOWN_RESP(0xad.toByte()), + ALARM_BLE_UNUSED_174(0xae.toByte()), + ALARM_BLE_REQ_STUCK_HIGH(0xaf.toByte()), + ALARM_BLE_STATE_MACHINE_1(0xb1.toByte()), + ALARM_BLE_STATE_MACHINE_2(0xb2.toByte()), + ALARM_BLE_UNUSED_179(0xb3.toByte()), + ALARM_BLE_ARB_LOST(0xb4.toByte()), + ALARM_BLE_ER48_DUAL_NACK(0xc0.toByte()), + ALARM_BLE_QN_EXCEED_MAX_RETRY(0xc1.toByte()), + ALARM_BLE_QN_CRIT_VAR_FAIL(0xc2.toByte()), + UNKNOWN(0xff.toByte()); companion object { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt index a677a533ca..039433c2a0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt @@ -3,8 +3,16 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti import java.nio.ByteBuffer import kotlin.experimental.or -class AlertConfiguration(private val slot: AlertSlot, private val enabled: Boolean, private val durationInMinutes: Short, private val autoOff: Boolean, private val triggerType: AlertTriggerType, private val offsetInMinutesOrThresholdInMicroLiters: Short, private val beepType: BeepType, private val beepRepetition: BeepRepetitionType) : Encodable { - +class AlertConfiguration( + private val slot: AlertSlot, + private val enabled: Boolean, + private val durationInMinutes: Short, + private val autoOff: Boolean, + private val triggerType: AlertTriggerType, + private val offsetInMinutesOrThresholdInMicroLiters: Short, + private val beepType: BeepType, + private val beepRepetition: BeepRepetitionType +) : Encodable { override val encoded: ByteArray get() { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt index 15fa641c86..023502ca03 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt @@ -1,7 +1,15 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class AlertSlot(val value: Byte) { - AUTO_OFF(0x00.toByte()), MULTI_COMMAND(0x01.toByte()), EXPIRATION_IMMINENT(0x02.toByte()), USER_SET_EXPIRATION(0x03.toByte()), LOW_RESERVOIR(0x04.toByte()), SUSPEND_IN_PROGRESS(0x05.toByte()), SUSPEND_ENDED(0x06.toByte()), EXPIRATION(0x07.toByte()), UNKNOWN(0xff.toByte()); + AUTO_OFF(0x00.toByte()), + MULTI_COMMAND(0x01.toByte()), + EXPIRATION_IMMINENT(0x02.toByte()), + USER_SET_EXPIRATION(0x03.toByte()), + LOW_RESERVOIR(0x04.toByte()), + SUSPEND_IN_PROGRESS(0x05.toByte()), + SUSPEND_ENDED(0x06.toByte()), + EXPIRATION(0x07.toByte()), + UNKNOWN(0xff.toByte()); companion object { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt index 6410cc9cfd..7dc7a16f1a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class AlertTriggerType { - TIME_TRIGGER, RESERVOIR_VOLUME_TRIGGER + TIME_TRIGGER, + RESERVOIR_VOLUME_TRIGGER } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt index 7464a676c0..f13d6bedc5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt @@ -2,7 +2,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti // FIXME names enum class BeepRepetitionType( // Used in lump of coal alert - val value: Byte) { + val value: Byte +) { XXX(0x01.toByte()), // Used in low reservoir alert XXX2(0x03.toByte()), // Used in user pod expiration alert diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt index e72ef75b51..adcf4a9a5b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt @@ -1,8 +1,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class BeepType( // Used in stop delivery command - val value: Byte) { + val value: Byte +) { - SILENT(0x00.toByte()), FOUR_TIMES_BIP_BEEP(0x02.toByte()), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert + SILENT(0x00.toByte()), + FOUR_TIMES_BIP_BEEP(0x02.toByte()), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert LONG_SINGLE_BEEP(0x06.toByte()); } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt index e80564a839..14d6bc1be7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt @@ -1,7 +1,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class DeliveryStatus(private val value: Byte) { - SUSPENDED(0x00.toByte()), BASAL_ACTIVE(0x01.toByte()), TEMP_BASAL_ACTIVE(0x02.toByte()), PRIMING(0x04.toByte()), BOLUS_AND_BASAL_ACTIVE(0x05.toByte()), BOLUS_AND_TEMP_BASAL_ACTIVE(0x06.toByte()), UNKNOWN(0xff.toByte()); + SUSPENDED(0x00.toByte()), + BASAL_ACTIVE(0x01.toByte()), + TEMP_BASAL_ACTIVE(0x02.toByte()), + PRIMING(0x04.toByte()), + BOLUS_AND_BASAL_ACTIVE(0x05.toByte()), + BOLUS_AND_TEMP_BASAL_ACTIVE(0x06.toByte()), + UNKNOWN(0xff.toByte()); companion object { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt index 08e4275d48..4e45da8667 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt @@ -1,7 +1,36 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition enum class NakErrorType(private val value: Byte) { - FLASH_WRITE(0x01.toByte()), FLASH_ERASE(0x02.toByte()), FLASH_OPERATION(0x03.toByte()), FLASH_ADDR(0x04.toByte()), POD_STATE(0x05.toByte()), CRITICAL_VARIABLE(0x06.toByte()), ILLEGAL_PARAM(0x07.toByte()), BOLUS_CRITICAL_VAR(0x08.toByte()), INT_ILLEGAL_PARAM(0x09.toByte()), ILLEGAL_CHECKSUM(0x0a.toByte()), INVALID_MSG_LEN(0x0b.toByte()), PUMP_STATE(0x0c.toByte()), ILLEGAL_COMMAND(0x0d.toByte()), ILLEGAL_FILL_STATE(0x0e.toByte()), MAX_READWRITE_SIZE(0x0f.toByte()), ILLEGAL_READ_ADDRESS(0x10.toByte()), ILLEGAL_READ_MEM_TYPE(0x11.toByte()), INIT_POD(0x12.toByte()), ILLEGAL_CMD_STATE(0x13.toByte()), ILLEGAL_SECURITY_CODE(0x14.toByte()), POD_IN_ALARM(0x15.toByte()), COMD_NOT_SET(0x16.toByte()), ILLEGAL_RX_SENS_VALUE(0x17.toByte()), ILLEGAL_TX_PKT_SIZE(0x18.toByte()), OCCL_PARAMS_ALREADY_SET(0x19.toByte()), OCCL_PARAM(0x1a.toByte()), ILLEGAL_CDTHR_VALUE(0x1b.toByte()), IGNORE_COMMAND(0x1c.toByte()), INVALID_CRC(0x1d.toByte()), UNKNOWN(0xff.toByte()); + FLASH_WRITE(0x01.toByte()), + FLASH_ERASE(0x02.toByte()), + FLASH_OPERATION(0x03.toByte()), + FLASH_ADDR(0x04.toByte()), + POD_STATE(0x05.toByte()), + CRITICAL_VARIABLE(0x06.toByte()), + ILLEGAL_PARAM(0x07.toByte()), + BOLUS_CRITICAL_VAR(0x08.toByte()), + INT_ILLEGAL_PARAM(0x09.toByte()), + ILLEGAL_CHECKSUM(0x0a.toByte()), + INVALID_MSG_LEN(0x0b.toByte()), + PUMP_STATE(0x0c.toByte()), + ILLEGAL_COMMAND(0x0d.toByte()), + ILLEGAL_FILL_STATE(0x0e.toByte()), + MAX_READWRITE_SIZE(0x0f.toByte()), + ILLEGAL_READ_ADDRESS(0x10.toByte()), + ILLEGAL_READ_MEM_TYPE(0x11.toByte()), + INIT_POD(0x12.toByte()), + ILLEGAL_CMD_STATE(0x13.toByte()), + ILLEGAL_SECURITY_CODE(0x14.toByte()), + POD_IN_ALARM(0x15.toByte()), + COMD_NOT_SET(0x16.toByte()), + ILLEGAL_RX_SENS_VALUE(0x17.toByte()), + ILLEGAL_TX_PKT_SIZE(0x18.toByte()), + OCCL_PARAMS_ALREADY_SET(0x19.toByte()), + OCCL_PARAM(0x1a.toByte()), + ILLEGAL_CDTHR_VALUE(0x1b.toByte()), + IGNORE_COMMAND(0x1c.toByte()), + INVALID_CRC(0x1d.toByte()), + UNKNOWN(0xff.toByte()); companion object { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt deleted file mode 100644 index fb67205fad..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/OmnipodEvent.kt +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition - -class OmnipodEvent { - enum class OmnipodEventType { - CONNECTED, ALREADY_CONNECTED, FAILED_TO_CONNECT, DISCONNECTED, COMMAND_SENT, GOT_POD_VERSION, SET_UNIQUE_ID, PRIMED_PUMP, FINISHED_ACTIVATION_1, PROGRAMMED_BASAL, PROGRAMMED_ALERTS, SET_BEEPS, INSERTED_CANNULA, FINISHED_ACTIVATION_2, PROGRAMMED_TEMP_BASAL, STARTED_BOLUS, STOPPED_DELIVERY, SILENCED_ALERTS, DEACTIVATED, COMMAND_SENDING - } -} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt index 52a680273e..676bc85c07 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt @@ -2,4 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType -abstract class ActivationResponseBase(val activationResponseType: ActivationResponseType, encoded: ByteArray) : ResponseBase(ResponseType.ACTIVATION_RESPONSE, encoded) \ No newline at end of file +abstract class ActivationResponseBase( + val activationResponseType: ActivationResponseType, + encoded: ByteArray +) : ResponseBase(ResponseType.ACTIVATION_RESPONSE, encoded) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index fcfdeec13d..b761611cf9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -1,6 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.* +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.AdditionalStatusResponseType import java.nio.ByteBuffer import java.util.* @@ -38,6 +40,7 @@ class AlarmStatusResponse(encoded: ByteArray) : AdditionalStatusResponseBase(Add private val receiverLowerGain: Short private val podStatusWhenAlarmOccurred2: PodStatus private val returnAddressOfPodAlarmHandlerCaller: Short + fun getMessageType(): Byte { return messageType } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt index 82b368b60b..0f1a0f06a0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt @@ -1,6 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response -interface Response { +import java.io.Serializable + +interface Response : Serializable { val responseType: ResponseType val encoded: ByteArray diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt index 07b99e5b8e..1df5c6f988 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response -abstract class ResponseBase(override val responseType: ResponseType, encoded: ByteArray) : Response { +abstract class ResponseBase( + override val responseType: ResponseType, + encoded: ByteArray +) : Response { override val encoded: ByteArray = encoded.copyOf(encoded.size) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt index 2aad1ae23c..6c6c19ae80 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt @@ -1,7 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response -enum class ResponseType(private val value: Byte) { - ACTIVATION_RESPONSE(0x01.toByte()), DEFAULT_STATUS_RESPONSE(0x1d.toByte()), ADDITIONAL_STATUS_RESPONSE(0x02.toByte()), NAK_RESPONSE(0x06.toByte()), UNKNOWN(0xff.toByte()); +enum class ResponseType( + private val value: Byte +) { + + ACTIVATION_RESPONSE(0x01.toByte()), + DEFAULT_STATUS_RESPONSE(0x1d.toByte()), + ADDITIONAL_STATUS_RESPONSE(0x02.toByte()), + NAK_RESPONSE(0x06.toByte()), + UNKNOWN(0xff.toByte()); fun getValue(): Byte { return value diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt index d559043ac2..db304337f8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt @@ -27,6 +27,7 @@ class SetUniqueIdResponse(encoded: ByteArray) : ActivationResponseBase(Activatio private val lotNumber: Long private val podSequenceNumber: Long private val uniqueIdReceivedInCommand: Long + fun getMessageType(): Byte { return messageType } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt index 315adc5018..e62250b93f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt @@ -6,17 +6,19 @@ import java.nio.ByteBuffer import java.util.* import kotlin.experimental.and -class VersionResponse(encoded: ByteArray) : ActivationResponseBase(ActivationResponseType.GET_VERSION_RESPONSE, encoded) { +class VersionResponse( + encoded: ByteArray +) : ActivationResponseBase(ActivationResponseType.GET_VERSION_RESPONSE, encoded) { private val messageType: Byte = encoded[0] - private val messageLength: Short = (encoded[1].toInt() and 0xff) .toShort() - private val firmwareVersionMajor: Short = (encoded[2].toInt() and 0xff) .toShort() - private val firmwareVersionMinor: Short = (encoded[3].toInt() and 0xff) .toShort() - private val firmwareVersionInterim: Short = (encoded[4].toInt() and 0xff) .toShort() - private val bleVersionMajor: Short = (encoded[5].toInt() and 0xff) .toShort() - private val bleVersionMinor: Short = (encoded[6].toInt() and 0xff) .toShort() - private val bleVersionInterim: Short = (encoded[7].toInt() and 0xff) .toShort() - private val productId: Short = (encoded[8].toInt() and 0xff) .toShort() + private val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + private val firmwareVersionMajor: Short = (encoded[2].toInt() and 0xff).toShort() + private val firmwareVersionMinor: Short = (encoded[3].toInt() and 0xff).toShort() + private val firmwareVersionInterim: Short = (encoded[4].toInt() and 0xff).toShort() + private val bleVersionMajor: Short = (encoded[5].toInt() and 0xff).toShort() + private val bleVersionMinor: Short = (encoded[6].toInt() and 0xff).toShort() + private val bleVersionInterim: Short = (encoded[7].toInt() and 0xff).toShort() + private val productId: Short = (encoded[8].toInt() and 0xff).toShort() private val podStatus: PodStatus = PodStatus.byValue((encoded[9] and 0xf)) private val lotNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[10], encoded[11], encoded[12], encoded[13])).long private val podSequenceNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[14], encoded[15], encoded[16], encoded[17])).long From 04cd03f99f523a4d0bab2415d364beb742189bed Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 10:21:26 +0100 Subject: [PATCH 021/649] Address review comments --- .../dash/EventOmnipodDashPumpValuesChanged.kt | 3 +-- .../omnipod/dash/dagger/OmnipodDashModule.kt | 19 +++++++++---------- ...anager.kt => OmnipodDashBleManagerImpl.kt} | 2 +- 3 files changed, 11 insertions(+), 13 deletions(-) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{BleManager.kt => OmnipodDashBleManagerImpl.kt} (96%) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt index 4bc37cddf0..953819cad3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt @@ -2,5 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash import info.nightscout.androidaps.events.Event -class EventOmnipodDashPumpValuesChanged : Event() { -} \ No newline at end of file +class EventOmnipodDashPumpValuesChanged : Event() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index 38b571f922..a67a8dd570 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.dagger +import dagger.Binds import dagger.Module -import dagger.Provides import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.ActivityScope import info.nightscout.androidaps.plugins.pump.omnipod.common.dagger.OmnipodWizardModule import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManagerImpl -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.DashPodManagementActivity @@ -37,15 +37,14 @@ abstract class OmnipodDashModule { @ContributesAndroidInjector abstract fun contributesOmnipodDashOverviewFragment(): OmnipodDashOverviewFragment - companion object { + // MANAGERS - @Provides - fun providesBleManager(bleManager: BleManager): OmnipodDashBleManager = bleManager + @Binds + abstract fun bindsOmnipodDashBleManagerImpl(bleManager: OmnipodDashBleManagerImpl): OmnipodDashBleManager - @Provides - fun providesPodStateManager(podStateManager: OmnipodDashPodStateManagerImpl): OmnipodDashPodStateManager = podStateManager + @Binds + abstract fun bindsOmnipodDashPodStateManagerImpl(podStateManager: OmnipodDashPodStateManagerImpl): OmnipodDashPodStateManager - @Provides - fun providesOmnipodManager(omnipodManager: OmnipodDashManagerImpl): OmnipodDashManager = omnipodManager - } + @Binds + abstract fun bindsOmnipodDashManagerImpl(omnipodManager: OmnipodDashManagerImpl): OmnipodDashManager } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt similarity index 96% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index e624e3050f..54a89a9b3b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/BleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -20,7 +20,7 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class BleManager @Inject constructor(private val context: Context, private val aapsLogger: AAPSLogger) : OmnipodDashBleManager { +class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context, private val aapsLogger: AAPSLogger) : OmnipodDashBleManager { private val bluetoothManager: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter From 29617b5d8ca2f9c6a302a5fbe1dc6ded264d3f68 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 10:26:30 +0100 Subject: [PATCH 022/649] Remove redundant qualifiers --- .../pump/omnipod/dash/driver/comm/command/BleCommandType.kt | 2 +- .../pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt | 4 ++-- .../omnipod/dash/driver/pod/command/ProgramBasalCommand.kt | 4 ++-- .../omnipod/dash/driver/pod/command/ProgramBolusCommand.kt | 4 ++-- .../dash/driver/pod/command/ProgramTempBasalCommand.kt | 4 ++-- .../omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt | 4 ++-- .../omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt | 4 ++-- .../omnipod/dash/driver/pod/command/StopDeliveryCommand.kt | 4 ++-- .../omnipod/dash/driver/pod/response/AlarmStatusResponse.kt | 4 ++-- .../omnipod/dash/driver/pod/response/DefaultStatusResponse.kt | 2 +- .../pump/omnipod/dash/driver/pod/response/NakResponse.kt | 2 +- 11 files changed, 19 insertions(+), 19 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt index 9fb461b02d..5c096d4410 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt @@ -7,7 +7,7 @@ enum class BleCommandType(val value: Byte) { @JvmStatic fun byValue(value: Byte): BleCommandType = - BleCommandType.values().firstOrNull { it.value == value } + values().firstOrNull { it.value == value } ?: throw IllegalArgumentException("Unknown BleCommandType: $value") } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt index bca46f8342..16b3da0583 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt @@ -13,8 +13,8 @@ class GetVersionCommand internal constructor(uniqueId: Int, sequenceNumber: Shor // // override val encoded: ByteArray - get() = HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // - .put(HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // .put(commandType.value) // .put(BODY_LENGTH) // .putInt(uniqueId) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt index 3d05aada1b..bc4f724f69 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -47,8 +47,8 @@ class ProgramBasalCommand internal constructor(private val interlockCommand: Pro } val basalCommand = buffer.array() val interlockCommand = interlockCommand.encoded - val header: ByteArray = HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, (basalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) - return HeaderEnabledCommand.appendCrc(ByteBuffer.allocate(basalCommand.size + interlockCommand.size + header.size) // + val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (basalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + return appendCrc(ByteBuffer.allocate(basalCommand.size + interlockCommand.size + header.size) // .put(header) // .put(interlockCommand) // .put(basalCommand) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt index 70f75a4f11..41d1f15df8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -35,8 +35,8 @@ class ProgramBolusCommand internal constructor(private val interlockCommand: Pro .putInt(0) // Delay between tenth extended pulses in usec .array() val interlockCommand = interlockCommand.encoded - val header: ByteArray = HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, (bolusCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) - return HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + bolusCommand.size) // + val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (bolusCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + return appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + bolusCommand.size) // .put(header) // .put(interlockCommand) // .put(bolusCommand) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt index 601bf8eb2f..2e3b9d6624 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -84,8 +84,8 @@ class ProgramTempBasalCommand protected constructor(private val interlockCommand } val tempBasalCommand = buffer.array() val interlockCommand = interlockCommand.encoded - val header: ByteArray = HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) - return HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) // + val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + return appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) // .put(header) // .put(interlockCommand) // .put(tempBasalCommand) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt index 7772ecec53..f475558220 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -19,8 +19,8 @@ class SetUniqueIdCommand internal constructor(uniqueId: Int, sequenceNumber: Sho // // override val encoded: ByteArray - get() = HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // - .put(HeaderEnabledCommand.Companion.encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // + get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // .put(commandType.value) // .put(BODY_LENGTH) // .putInt(uniqueId) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index 78149ba1c4..ff7072fca6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -12,8 +12,8 @@ class SilenceAlertsCommand internal constructor(uniqueId: Int, sequenceNumber: S override val encoded: ByteArray get() = - HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // - .put(HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // .put(commandType.value) // .put(BODY_LENGTH) // .putInt(nonce) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt index 95828da199..368a630cb5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -13,8 +13,8 @@ class StopDeliveryCommand internal constructor(uniqueId: Int, sequenceNumber: Sh override val encoded: ByteArray get() { - return HeaderEnabledCommand.Companion.appendCrc(ByteBuffer.allocate(LENGTH + HeaderEnabledCommand.Companion.HEADER_LENGTH) // - .put(HeaderEnabledCommand.Companion.encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // .put(commandType.value) // .put(BODY_LENGTH) // .putInt(nonce) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index b761611cf9..cfec51058f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -204,11 +204,11 @@ class AlarmStatusResponse(encoded: ByteArray) : AdditionalStatusResponseBase(Add messageLength = (encoded[1].toInt() and 0xff).toShort() additionalStatusResponseType = encoded[2] podStatus = PodStatus.byValue((encoded[3] and 0x0f)) - deliveryStatus = DeliveryStatus.Companion.byValue((encoded[4] and 0x0f)) + deliveryStatus = DeliveryStatus.byValue((encoded[4] and 0x0f)) bolusPulsesRemaining = (ByteBuffer.wrap(byteArrayOf(encoded[5], encoded[6])).short and 2047) sequenceNumberOfLastProgrammingCommand = (encoded[7] and 0x0f).toShort() totalPulsesDelivered = ByteBuffer.wrap(byteArrayOf(encoded[8], encoded[9])).short - alarmType = AlarmType.Companion.byValue(encoded[10]) + alarmType = AlarmType.byValue(encoded[10]) alarmTime = ByteBuffer.wrap(byteArrayOf(encoded[11], encoded[12])).short reservoirPulsesRemaining = ByteBuffer.wrap(byteArrayOf(encoded[13], encoded[14])).short minutesSinceActivation = ByteBuffer.wrap(byteArrayOf(encoded[15], encoded[16])).short diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt index 33aa3b90e3..03dd1b7549 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt @@ -9,7 +9,7 @@ class DefaultStatusResponse(encoded: ByteArray) : ResponseBase(ResponseType.DEFA // TODO: Here is a lot of bitshifting that had to be changed. we should go over it. private val messageType: Byte = encoded[0] private val deliveryStatus: DeliveryStatus = DeliveryStatus.byValue((encoded[1].toInt() shr 4 and 0x0f).toByte()) - private val podStatus: PodStatus = PodStatus.Companion.byValue((encoded[1] and 0x0f) as Byte) + private val podStatus: PodStatus = PodStatus.byValue((encoded[1] and 0x0f) as Byte) private val totalPulsesDelivered: Short = ((encoded[2] and 0x0f shl 12 or (encoded[3].toInt() and 0xff shl 1) or (encoded[4].toInt() and 0xff ushr 7)).toShort()) private val sequenceNumberOfLastProgrammingCommand: Short = (encoded[4] ushr 3 and 0x0f).toShort() private val bolusPulsesRemaining: Short = ((encoded[4] and 0x07 shl 10 or (encoded[5].toInt() and 0xff) and 2047).toShort()) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt index 0c2f8940fc..8b304dec61 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt @@ -53,7 +53,7 @@ class NakResponse(encoded: ByteArray) : ResponseBase(ResponseType.NAK_RESPONSE, init { messageType = encoded[0] messageLength = encoded[1].toShort() - nakErrorType = NakErrorType.Companion.byValue(encoded[2]) + nakErrorType = NakErrorType.byValue(encoded[2]) val byte3 = encoded[3] val byte4 = encoded[4] if (nakErrorType == NakErrorType.ILLEGAL_SECURITY_CODE) { From 85140dfb0134732fef52a1f4faea69186578bc0f Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 10:41:13 +0100 Subject: [PATCH 023/649] More formatting --- .../driver/pod/command/DeactivateCommand.kt | 12 +++---- .../driver/pod/command/GetVersionCommand.kt | 11 +++---- .../pod/command/ProgramAlertsCommand.kt | 8 ++++- .../driver/pod/command/ProgramBasalCommand.kt | 25 ++++++++------- .../driver/pod/command/ProgramBolusCommand.kt | 24 ++++++-------- .../pod/command/ProgramInsulinCommand.kt | 13 +++++++- .../pod/command/ProgramTempBasalCommand.kt | 10 ++++-- .../driver/pod/command/SetUniqueIdCommand.kt | 19 +++++------ .../pod/command/SilenceAlertsCommand.kt | 9 ++++-- .../driver/pod/command/StopDeliveryCommand.kt | 10 ++++-- .../driver/pod/command/base/CommandType.kt | 5 ++- .../program/BasalInsulinProgramElement.kt | 10 +++--- .../BasalShortInsulinProgramElement.kt | 13 +++----- .../BolusShortInsulinProgramElement.kt | 4 ++- .../CurrentBasalInsulinProgramElement.kt | 8 ++++- .../command/insulin/program/CurrentSlot.kt | 8 ++++- .../program/ShortInsulinProgramElement.kt | 3 +- .../program/TempBasalInsulinProgramElement.kt | 8 +++-- .../dash/driver/pod/definition/AlarmType.kt | 5 ++- .../dash/driver/pod/definition/AlertSlot.kt | 5 ++- .../driver/pod/definition/BasalProgram.kt | 4 ++- .../pod/definition/BeepRepetitionType.kt | 12 +++---- .../driver/pod/definition/DeliveryStatus.kt | 5 ++- .../driver/pod/definition/NakErrorType.kt | 5 ++- .../dash/driver/pod/definition/PodStatus.kt | 5 ++- .../driver/pod/definition/ProgramReminder.kt | 7 +++- .../driver/pod/definition/SoftwareVersion.kt | 6 +++- .../response/AdditionalStatusResponseBase.kt | 5 ++- .../pod/response/AlarmStatusResponse.kt | 4 ++- .../pod/response/DefaultStatusResponse.kt | 4 ++- .../dash/driver/pod/response/NakResponse.kt | 5 +-- .../pod/response/SetUniqueIdResponse.kt | 32 +++++++++---------- 32 files changed, 192 insertions(+), 112 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt index e29fd1de16..8ae51e845a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt @@ -5,13 +5,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder import java.nio.ByteBuffer -class DeactivateCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, nonce: Int) : NonceEnabledCommand(CommandType.DEACTIVATE, uniqueId, sequenceNumber, multiCommandFlag, nonce) { +class DeactivateCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + nonce: Int +) : NonceEnabledCommand(CommandType.DEACTIVATE, uniqueId, sequenceNumber, multiCommandFlag, nonce) { - // - // - // - // - // override val encoded: ByteArray get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt index 16b3da0583..3300bde757 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt @@ -5,13 +5,12 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder import java.nio.ByteBuffer -class GetVersionCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean) : HeaderEnabledCommand(CommandType.GET_VERSION, uniqueId, sequenceNumber, multiCommandFlag) { +class GetVersionCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean +) : HeaderEnabledCommand(CommandType.GET_VERSION, uniqueId, sequenceNumber, multiCommandFlag) { - // - // - // - // - // override val encoded: ByteArray get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt index 7e8dcb7971..594dd1f57c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt @@ -7,7 +7,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import java.nio.ByteBuffer import java.util.* -class ProgramAlertsCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, alertConfigurations: List?, nonce: Int) : NonceEnabledCommand(CommandType.PROGRAM_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { +class ProgramAlertsCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + alertConfigurations: List?, + nonce: Int +) : NonceEnabledCommand(CommandType.PROGRAM_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { private val alertConfigurations: List diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt index bc4f724f69..af656989d8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -12,7 +12,17 @@ import java.nio.ByteBuffer import java.util.* // Always preceded by 0x1a ProgramInsulinCommand -class ProgramBasalCommand internal constructor(private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, insulinProgramElements: List?, programReminder: ProgramReminder, currentInsulinProgramElementIndex: Byte, remainingTenthPulsesInCurrentInsulinProgramElement: Short, delayUntilNextTenthPulseInUsec: Int) : HeaderEnabledCommand(CommandType.PROGRAM_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { +class ProgramBasalCommand internal constructor( + private val interlockCommand: ProgramInsulinCommand, + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + insulinProgramElements: List, + programReminder: ProgramReminder, + currentInsulinProgramElementIndex: Byte, + remainingTenthPulsesInCurrentInsulinProgramElement: Short, + delayUntilNextTenthPulseInUsec: Int +) : HeaderEnabledCommand(CommandType.PROGRAM_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { private val insulinProgramElements: List private val programReminder: ProgramReminder @@ -22,17 +32,8 @@ class ProgramBasalCommand internal constructor(private val interlockCommand: Pro val length: Short get() = (insulinProgramElements.size * 6 + 10).toShort() val bodyLength: Byte - get() = (insulinProgramElements.size * 6 + 8).toByte()// + get() = (insulinProgramElements.size * 6 + 8).toByte() - // - // - // - // - // - // - // - // - // override val encoded: ByteArray get() { val buffer = ByteBuffer.allocate(length.toInt()) // @@ -47,7 +48,7 @@ class ProgramBasalCommand internal constructor(private val interlockCommand: Pro } val basalCommand = buffer.array() val interlockCommand = interlockCommand.encoded - val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (basalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (basalCommand.size + interlockCommand.size).toShort(), multiCommandFlag) return appendCrc(ByteBuffer.allocate(basalCommand.size + interlockCommand.size + header.size) // .put(header) // .put(interlockCommand) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt index 41d1f15df8..dd0db15ee6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -9,20 +9,16 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.Mess import java.nio.ByteBuffer // NOT SUPPORTED: extended bolus -class ProgramBolusCommand internal constructor(private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val programReminder: ProgramReminder, private val numberOfTenthPulses: Short, // - private val delayUntilFirstTenthPulseInUsec: Int) : HeaderEnabledCommand(CommandType.PROGRAM_BOLUS, uniqueId, sequenceNumber, multiCommandFlag) { +class ProgramBolusCommand internal constructor( + private val interlockCommand: ProgramInsulinCommand, + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val programReminder: ProgramReminder, + private val numberOfTenthPulses: Short, + private val delayUntilFirstTenthPulseInUsec: Int +) : HeaderEnabledCommand(CommandType.PROGRAM_BOLUS, uniqueId, sequenceNumber, multiCommandFlag) { - // - // - // - // - // - // - // - // - // - // Extended bolus pulses - // Delay between tenth extended pulses in usec override val encoded: ByteArray get() { val bolusCommand = ByteBuffer.allocate(LENGTH.toInt()) // @@ -35,7 +31,7 @@ class ProgramBolusCommand internal constructor(private val interlockCommand: Pro .putInt(0) // Delay between tenth extended pulses in usec .array() val interlockCommand = interlockCommand.encoded - val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (bolusCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (bolusCommand.size + interlockCommand.size).toShort(), multiCommandFlag) return appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + bolusCommand.size) // .put(header) // .put(interlockCommand) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt index a357013027..c3b98f69fc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt @@ -7,7 +7,18 @@ import java.nio.ByteBuffer import java.util.* // Always followed by one of: 0x13, 0x16, 0x17 -class ProgramInsulinCommand(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, nonce: Int, insulinProgramElements: List, private val checksum: Short, private val byte9: Byte, private val byte10And11: Short, private val byte12And13: Short, private val deliveryType: DeliveryType) : NonceEnabledCommand(CommandType.PROGRAM_INSULIN, uniqueId, sequenceNumber, multiCommandFlag, nonce) { +class ProgramInsulinCommand( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + nonce: Int, insulinProgramElements: + List, + private val checksum: Short, + private val byte9: Byte, + private val byte10And11: Short, + private val byte12And13: Short, + private val deliveryType: DeliveryType +) : NonceEnabledCommand(CommandType.PROGRAM_INSULIN, uniqueId, sequenceNumber, multiCommandFlag, nonce) { private val insulinProgramElements: List = ArrayList(insulinProgramElements) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt index 2e3b9d6624..350136a661 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -11,8 +11,14 @@ import java.nio.ByteBuffer import java.util.* // NOT SUPPORTED: percentage temp basal -class ProgramTempBasalCommand protected constructor(private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, - private val programReminder: ProgramReminder, insulinProgramElements: List) : HeaderEnabledCommand(CommandType.PROGRAM_TEMP_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { +class ProgramTempBasalCommand protected constructor( + private val interlockCommand: ProgramInsulinCommand, + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val programReminder: ProgramReminder, + insulinProgramElements: List +) : HeaderEnabledCommand(CommandType.PROGRAM_TEMP_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { private val insulinProgramElements: List fun getBodyLength(): Byte = (insulinProgramElements.size * 6 + 8).toByte() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt index f475558220..6deb03a6ae 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -6,18 +6,15 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import java.nio.ByteBuffer import java.util.* -class SetUniqueIdCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val lotNumber: Int, private val podSequenceNumber: Int, private val initializationTime: Date) : HeaderEnabledCommand(CommandType.SET_UNIQUE_ID, uniqueId, sequenceNumber, multiCommandFlag) { +class SetUniqueIdCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val lotNumber: Int, + private val podSequenceNumber: Int, + private val initializationTime: Date +) : HeaderEnabledCommand(CommandType.SET_UNIQUE_ID, uniqueId, sequenceNumber, multiCommandFlag) { - // - // - // - // - // - // FIXME ?? - // FIXME ?? - // - // - // override val encoded: ByteArray get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // .put(encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index ff7072fca6..5db1c248cc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -1,14 +1,19 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable import java.nio.ByteBuffer import java.util.* -class SilenceAlertsCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val parameters: SilenceAlertCommandParameters, nonce: Int) : NonceEnabledCommand(CommandType.SILENCE_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { +class SilenceAlertsCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val parameters: SilenceAlertCommandParameters, + nonce: Int +) : NonceEnabledCommand(CommandType.SILENCE_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { override val encoded: ByteArray get() = diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt index 368a630cb5..b74a85dd02 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType @@ -9,7 +8,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import java.nio.ByteBuffer import java.util.* -class StopDeliveryCommand internal constructor(uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, private val deliveryType: DeliveryType, private val beepType: BeepType, nonce: Int) : NonceEnabledCommand(CommandType.STOP_DELIVERY, uniqueId, sequenceNumber, multiCommandFlag, nonce) { +class StopDeliveryCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val deliveryType: DeliveryType, + private val beepType: BeepType, + nonce: Int +) : NonceEnabledCommand(CommandType.STOP_DELIVERY, uniqueId, sequenceNumber, multiCommandFlag, nonce) { override val encoded: ByteArray get() { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt index c3715b32cf..57bd0962c8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base -enum class CommandType(var value: Byte) { +enum class CommandType( + val value: Byte +) { + SET_UNIQUE_ID(0x03.toByte()), GET_VERSION(0x07.toByte()), GET_STATUS(0x0e.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt index 7121b43a08..cb700d64f2 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt @@ -2,13 +2,15 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import java.io.Serializable import java.nio.ByteBuffer -open class BasalInsulinProgramElement(val startSlotIndex: Byte, val numberOfSlots: Byte, val totalTenthPulses: Short) : Encodable { +open class BasalInsulinProgramElement( + val startSlotIndex: Byte, + val numberOfSlots: Byte, + val totalTenthPulses: Short +) : Encodable, Serializable { - // - // - // override val encoded: ByteArray get() = ByteBuffer.allocate(6) // .putShort(totalTenthPulses) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt index 691c444ff2..f30c4a8170 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt @@ -3,15 +3,12 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import java.nio.ByteBuffer import kotlin.experimental.and -class BasalShortInsulinProgramElement(// 4 bits - private val numberOfSlots: Byte, // 10 bits - private val pulsesPerSlot: Short, // - private val extraAlternatePulse: Boolean) : ShortInsulinProgramElement { +class BasalShortInsulinProgramElement( + private val numberOfSlots: Byte, // 4 bits + private val pulsesPerSlot: Short, //10 bits + private val extraAlternatePulse: Boolean +) : ShortInsulinProgramElement { - // - // - // - // override val encoded: ByteArray get() { val firstByte = (numberOfSlots - 1 and 0x0f shl 4 // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt index 65938313ed..6a2948404b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt @@ -2,7 +2,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import java.nio.ByteBuffer -class BolusShortInsulinProgramElement(private val numberOfPulses: Short) : ShortInsulinProgramElement { +class BolusShortInsulinProgramElement( + private val numberOfPulses: Short +) : ShortInsulinProgramElement { override val encoded: ByteArray get() = ByteBuffer.allocate(2).putShort(numberOfPulses).array() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt index 87fe2b083b..04f27cf9bf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt @@ -1,6 +1,12 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program -class CurrentBasalInsulinProgramElement(val index: Byte, val delayUntilNextTenthPulseInUsec: Int, val remainingTenthPulses: Short) { +import java.io.Serializable + +class CurrentBasalInsulinProgramElement( + val index: Byte, + val delayUntilNextTenthPulseInUsec: Int, + val remainingTenthPulses: Short +) : Serializable { override fun toString(): String = "CurrentLongInsulinProgramElement{" + "index=" + index + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt index d8667fe04c..49b2af59dc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt @@ -1,6 +1,12 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program -class CurrentSlot(val index: Byte, val eighthSecondsRemaining: Short, val pulsesRemaining: Short) { +import java.io.Serializable + +class CurrentSlot( + val index: Byte, + val eighthSecondsRemaining: Short, + val pulsesRemaining: Short +) : Serializable { override fun toString(): String = "CurrentSlot{" + "index=" + index + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt index b5f01ec3df..2ff92c2c24 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import java.io.Serializable -interface ShortInsulinProgramElement : Encodable \ No newline at end of file +interface ShortInsulinProgramElement : Encodable, Serializable \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt index fc22bef671..4c58755591 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt @@ -2,10 +2,12 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import java.nio.ByteBuffer -class TempBasalInsulinProgramElement(startSlotIndex: Byte, numberOfSlots: Byte, totalTenthPulses: Short) : BasalInsulinProgramElement(startSlotIndex, numberOfSlots, totalTenthPulses) { +class TempBasalInsulinProgramElement( + startSlotIndex: Byte, + numberOfSlots: Byte, + totalTenthPulses: Short +) : BasalInsulinProgramElement(startSlotIndex, numberOfSlots, totalTenthPulses) { - // - // override val encoded: ByteArray get() { val buffer = ByteBuffer.allocate(6) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt index 6e80e8a676..795ddd19f1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class AlarmType(private val value: Byte) { +enum class AlarmType( + private val value: Byte +) { + NONE(0x00.toByte()), ALARM_PW_FLASH_ERASE(0x01.toByte()), ALARM_PW_FLASH_WRITE(0x02.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt index 023502ca03..f38a24d154 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class AlertSlot(val value: Byte) { +enum class AlertSlot( + val value: Byte +) { + AUTO_OFF(0x00.toByte()), MULTI_COMMAND(0x01.toByte()), EXPIRATION_IMMINENT(0x02.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt index 3b63ee207c..998e599805 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt @@ -2,7 +2,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti import java.util.* -class BasalProgram(segments: List) { +class BasalProgram( + segments: List +) { val segments: MutableList = segments.toMutableList() get() = Collections.unmodifiableList(field) // TODO Adrian: moved method here diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt index f13d6bedc5..402141e875 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition // FIXME names -enum class BeepRepetitionType( // Used in lump of coal alert +enum class BeepRepetitionType( val value: Byte ) { - XXX(0x01.toByte()), // Used in low reservoir alert - XXX2(0x03.toByte()), // Used in user pod expiration alert - XXX3(0x05.toByte()), // Used in pod expiration alert - XXX4(0x06.toByte()), // Used in imminent pod expiration alert - XXX5(0x08.toByte()); + XXX(0x01.toByte()), // Used in lump of coal alert + XXX2(0x03.toByte()), // Used in low reservoir alert + XXX3(0x05.toByte()), // Used in user pod expiration alert + XXX4(0x06.toByte()), // Used in pod expiration alert + XXX5(0x08.toByte()); // Used in imminent pod expiration alert } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt index 14d6bc1be7..08915f7f7e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class DeliveryStatus(private val value: Byte) { +enum class DeliveryStatus( + private val value: Byte +) { + SUSPENDED(0x00.toByte()), BASAL_ACTIVE(0x01.toByte()), TEMP_BASAL_ACTIVE(0x02.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt index 4e45da8667..81bbc53c7c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class NakErrorType(private val value: Byte) { +enum class NakErrorType( + private val value: Byte +) { + FLASH_WRITE(0x01.toByte()), FLASH_ERASE(0x02.toByte()), FLASH_OPERATION(0x03.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt index 9fc650caa5..cdb6ce9be1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class PodStatus(private val value: Byte) { +enum class PodStatus( + private val value: Byte +) { + UNINITIALIZED(0x00.toByte()), MFG_TEST(0x01.toByte()), FILLED(0x02.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt index 732cfb9e09..09a63370f0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt @@ -1,8 +1,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition +import java.io.Serializable import kotlin.experimental.and -class ProgramReminder(private val atStart: Boolean, private val atEnd: Boolean, private val atInterval: Byte) : Encodable { +class ProgramReminder( + private val atStart: Boolean, + private val atEnd: Boolean, + private val atInterval: Byte +) : Encodable, Serializable { override val encoded: ByteArray get() = byteArrayOf(((if (atStart) 1 else 0) shl 7 diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt index e373a1ba41..da619a0428 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/SoftwareVersion.kt @@ -2,7 +2,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti import java.io.Serializable -data class SoftwareVersion(private val major: Short, private val minor: Short, private val interim: Short) : Serializable { +data class SoftwareVersion( + private val major: Short, + private val minor: Short, + private val interim: Short +) : Serializable { override fun toString(): String { return "$major.$minor.$interim" diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt index 5db0f35b44..414a710723 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt @@ -2,4 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.AdditionalStatusResponseType -open class AdditionalStatusResponseBase internal constructor(val statusResponseType: AdditionalStatusResponseType, encoded: ByteArray) : ResponseBase(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded) \ No newline at end of file +open class AdditionalStatusResponseBase internal constructor( + val statusResponseType: AdditionalStatusResponseType, + encoded: ByteArray +) : ResponseBase(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index cfec51058f..4cce00a1c6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -8,7 +8,9 @@ import java.nio.ByteBuffer import java.util.* import kotlin.experimental.and -class AlarmStatusResponse(encoded: ByteArray) : AdditionalStatusResponseBase(AdditionalStatusResponseType.ALARM_STATUS, encoded) { +class AlarmStatusResponse( + encoded: ByteArray +) : AdditionalStatusResponseBase(AdditionalStatusResponseType.ALARM_STATUS, encoded) { private val messageType: Byte private val messageLength: Short diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt index 03dd1b7549..7e83e64ccf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt @@ -4,7 +4,9 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import kotlin.experimental.and -class DefaultStatusResponse(encoded: ByteArray) : ResponseBase(ResponseType.DEFAULT_STATUS_RESPONSE, encoded) { +class DefaultStatusResponse( + encoded: ByteArray +) : ResponseBase(ResponseType.DEFAULT_STATUS_RESPONSE, encoded) { // TODO: Here is a lot of bitshifting that had to be changed. we should go over it. private val messageType: Byte = encoded[0] diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt index 8b304dec61..a2090d5e58 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt @@ -3,9 +3,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import java.util.* -class NakResponse(encoded: ByteArray) : ResponseBase(ResponseType.NAK_RESPONSE, encoded) { +class NakResponse( + encoded: ByteArray +) : ResponseBase(ResponseType.NAK_RESPONSE, encoded) { private val messageType: Byte // TODO directly assign here private val messageLength: Short diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt index db304337f8..daf867f9fa 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt @@ -3,10 +3,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType import java.nio.ByteBuffer -import java.util.* -import kotlin.experimental.and -class SetUniqueIdResponse(encoded: ByteArray) : ActivationResponseBase(ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded) { +class SetUniqueIdResponse( + encoded: ByteArray +) : ActivationResponseBase(ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded) { private val messageType: Byte // TODO directly assign here private val messageLength: Short @@ -133,20 +133,20 @@ class SetUniqueIdResponse(encoded: ByteArray) : ActivationResponseBase(Activatio init { messageType = encoded[0] - messageLength = (encoded[1].toInt() and 0xff) .toShort() + messageLength = (encoded[1].toInt() and 0xff).toShort() pulseVolumeInTenThousandthMicroLiter = ByteBuffer.wrap(byteArrayOf(encoded[2], encoded[3])).short - pumpRate = (encoded[4].toInt() and 0xff) .toShort() - primePumpRate = (encoded[5].toInt() and 0xff) .toShort() - numberOfEngagingClutchDrivePulses = (encoded[6].toInt() and 0xff) .toShort() - numberOfPrimePulses = (encoded[7].toInt() and 0xff) .toShort() - podExpirationTimeInHours = (encoded[8].toInt() and 0xff) .toShort() - firmwareVersionMajor = (encoded[9].toInt() and 0xff) .toShort() - firmwareVersionMinor = (encoded[10].toInt() and 0xff) .toShort() - firmwareVersionInterim = (encoded[11].toInt() and 0xff) .toShort() - bleVersionMajor = (encoded[12].toInt() and 0xff) .toShort() - bleVersionMinor = (encoded[13].toInt() and 0xff) .toShort() - bleVersionInterim = (encoded[14].toInt() and 0xff) .toShort() - productId = (encoded[15].toInt() and 0xff) .toShort() + pumpRate = (encoded[4].toInt() and 0xff).toShort() + primePumpRate = (encoded[5].toInt() and 0xff).toShort() + numberOfEngagingClutchDrivePulses = (encoded[6].toInt() and 0xff).toShort() + numberOfPrimePulses = (encoded[7].toInt() and 0xff).toShort() + podExpirationTimeInHours = (encoded[8].toInt() and 0xff).toShort() + firmwareVersionMajor = (encoded[9].toInt() and 0xff).toShort() + firmwareVersionMinor = (encoded[10].toInt() and 0xff).toShort() + firmwareVersionInterim = (encoded[11].toInt() and 0xff).toShort() + bleVersionMajor = (encoded[12].toInt() and 0xff).toShort() + bleVersionMinor = (encoded[13].toInt() and 0xff).toShort() + bleVersionInterim = (encoded[14].toInt() and 0xff).toShort() + productId = (encoded[15].toInt() and 0xff).toShort() podStatus = PodStatus.byValue(encoded[16]) lotNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20])).long podSequenceNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24])).long From f2922057c0889214ef135bdf795be47726b74e66 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 13:21:27 +0100 Subject: [PATCH 024/649] Convert Omnipod Dash tests to Kotlin --- .../pod/command/DeactivateCommandTest.java | 21 ----- .../pod/command/DeactivateCommandTest.kt | 20 +++++ .../pod/command/GetVersionCommandTest.java | 20 ----- .../pod/command/GetVersionCommandTest.kt | 19 ++++ .../pod/command/ProgramAlertsCommandTest.java | 86 ------------------- .../pod/command/ProgramAlertsCommandTest.kt | 78 +++++++++++++++++ .../pod/command/ProgramBasalCommandTest.java | 38 -------- .../pod/command/ProgramBasalCommandTest.kt | 32 +++++++ .../pod/command/ProgramBolusCommandTest.java | 27 ------ .../pod/command/ProgramBolusCommandTest.kt | 24 ++++++ .../command/ProgramTempBasalCommandTest.java | 39 --------- .../command/ProgramTempBasalCommandTest.kt | 36 ++++++++ .../pod/command/SetUniqueIdCommandTest.java | 26 ------ .../pod/command/SetUniqueIdCommandTest.kt | 23 +++++ .../pod/command/SilenceAlertsCommandTest.java | 24 ------ .../pod/command/SilenceAlertsCommandTest.kt | 23 +++++ .../pod/command/StopDeliveryCommandTest.java | 41 --------- .../pod/command/StopDeliveryCommandTest.kt | 38 ++++++++ .../pod/response/AlarmStatusResponseTest.java | 56 ------------ .../pod/response/AlarmStatusResponseTest.kt | 52 +++++++++++ .../response/DefaultStatusResponseTest.java | 41 --------- .../pod/response/DefaultStatusResponseTest.kt | 36 ++++++++ .../driver/pod/response/NakResponseTest.java | 30 ------- .../driver/pod/response/NakResponseTest.kt | 27 ++++++ .../pod/response/SetUniqueIdResponseTest.java | 44 ---------- .../pod/response/SetUniqueIdResponseTest.kt | 40 +++++++++ .../pod/response/VersionResponseTest.java | 41 --------- .../pod/response/VersionResponseTest.kt | 36 ++++++++ 28 files changed, 484 insertions(+), 534 deletions(-) delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt delete mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.java create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.java deleted file mode 100644 index 4ffb19a702..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; - -public class DeactivateCommandTest { - @Test - public void testEncoding() throws DecoderException { - byte[] encoded = new DeactivateCommand.Builder() // - .setUniqueId(37879809) // - .setSequenceNumber((short) 5) // - .setNonce(1229869870) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("0242000114061C04494E532E001C"), encoded); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt new file mode 100644 index 0000000000..55dc2ff96e --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt @@ -0,0 +1,20 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class DeactivateCommandTest { + + @Test @Throws(DecoderException::class) fun testEncoding() { + val encoded = DeactivateCommand.Builder() // + .setUniqueId(37879809) // + .setSequenceNumber(5.toShort()) // + .setNonce(1229869870) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("0242000114061C04494E532E001C"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.java deleted file mode 100644 index 04191a4f67..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; - -public class GetVersionCommandTest { - @Test - public void testEncoding() throws DecoderException { - byte[] encoded = new GetVersionCommand.Builder() // - .setSequenceNumber((short) 0) // - .setUniqueId(GetVersionCommand.DEFAULT_UNIQUE_ID) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("FFFFFFFF00060704FFFFFFFF82B2"), encoded); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt new file mode 100644 index 0000000000..c092142361 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class GetVersionCommandTest { + + @Test @Throws(DecoderException::class) fun testEncoding() { + val encoded = GetVersionCommand.Builder() // + .setSequenceNumber(0.toShort()) // + .setUniqueId(GetVersionCommand.DEFAULT_UNIQUE_ID) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("FFFFFFFF00060704FFFFFFFF82B2"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.java deleted file mode 100644 index d137fed93b..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.java +++ /dev/null @@ -1,86 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTriggerType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepRepetitionType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType; - -import static org.junit.Assert.assertArrayEquals; - -public class ProgramAlertsCommandTest { - @Test - public void testExpirationAlerts() throws DecoderException { - List configurations = new ArrayList<>(); - configurations.add(new AlertConfiguration(AlertSlot.EXPIRATION, true, (short) 420, false, AlertTriggerType.TIME_TRIGGER, (short) 4305, BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX3)); - configurations.add(new AlertConfiguration(AlertSlot.EXPIRATION_IMMINENT, true, (short) 0, false, AlertTriggerType.TIME_TRIGGER, (short) 4725, BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX4)); - - byte[] encoded = new ProgramAlertsCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 3) // - .setMultiCommandFlag(true) // - .setNonce(1229869870) // - .setAlertConfigurations(configurations) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("024200038C121910494E532E79A410D1050228001275060280F5"), encoded); - } - - @Test - public void testLowReservoirAlert() throws DecoderException { - List configurations = new ArrayList<>(); - configurations.add(new AlertConfiguration(AlertSlot.LOW_RESERVOIR, true, (short) 0, false, AlertTriggerType.RESERVOIR_VOLUME_TRIGGER, (short) 200, BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX)); - - byte[] encoded = new ProgramAlertsCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 8) // - .setNonce(1229869870) // - .setAlertConfigurations(configurations) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("02420003200C190A494E532E4C0000C801020149"), encoded); - } - - @Test - public void testUserExpirationAlert() throws DecoderException { - List configurations = new ArrayList<>(); - configurations.add(new AlertConfiguration(AlertSlot.USER_SET_EXPIRATION, true, (short) 0, false, AlertTriggerType.TIME_TRIGGER, (short) 4079, BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX2)); - - byte[] encoded = new ProgramAlertsCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 15) // - .setNonce(1229869870) // - .setAlertConfigurations(configurations) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("024200033C0C190A494E532E38000FEF030203E2"), encoded); - } - - - @Test - public void testLumpOfCoalAlert() throws DecoderException { - List configurations = new ArrayList<>(); - configurations.add(new AlertConfiguration(AlertSlot.EXPIRATION, true, (short) 55, false, AlertTriggerType.TIME_TRIGGER, (short) 5, BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX5)); - - byte[] encoded = new ProgramAlertsCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 10) // - .setMultiCommandFlag(false) // - .setNonce(1229869870) // - .setAlertConfigurations(configurations) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("02420003280C190A494E532E7837000508020356"), encoded); - } -} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt new file mode 100644 index 0000000000..7fca25cfd7 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt @@ -0,0 +1,78 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTriggerType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepRepetitionType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test +import java.util.* + +class ProgramAlertsCommandTest { + + @Test @Throws(DecoderException::class) fun testExpirationAlerts() { + val configurations: MutableList = ArrayList() + configurations.add(AlertConfiguration(AlertSlot.EXPIRATION, true, 420.toShort(), false, AlertTriggerType.TIME_TRIGGER, 4305.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX3)) + configurations.add(AlertConfiguration(AlertSlot.EXPIRATION_IMMINENT, true, 0.toShort(), false, AlertTriggerType.TIME_TRIGGER, 4725.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX4)) + + val encoded = ProgramAlertsCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(3.toShort()) // + .setMultiCommandFlag(true) // + .setNonce(1229869870) // + .setAlertConfigurations(configurations) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("024200038C121910494E532E79A410D1050228001275060280F5"), encoded) + } + + @Test @Throws(DecoderException::class) fun testLowReservoirAlert() { + val configurations: MutableList = ArrayList() + configurations.add(AlertConfiguration(AlertSlot.LOW_RESERVOIR, true, 0.toShort(), false, AlertTriggerType.RESERVOIR_VOLUME_TRIGGER, 200.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX)) + + val encoded = ProgramAlertsCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(8.toShort()) // + .setNonce(1229869870) // + .setAlertConfigurations(configurations) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("02420003200C190A494E532E4C0000C801020149"), encoded) + } + + @Test @Throws(DecoderException::class) fun testUserExpirationAlert() { + val configurations: MutableList = ArrayList() + configurations.add(AlertConfiguration(AlertSlot.USER_SET_EXPIRATION, true, 0.toShort(), false, AlertTriggerType.TIME_TRIGGER, 4079.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX2)) + + val encoded = ProgramAlertsCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(15.toShort()) // + .setNonce(1229869870) // + .setAlertConfigurations(configurations) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("024200033C0C190A494E532E38000FEF030203E2"), encoded) + } + + @Test @Throws(DecoderException::class) fun testLumpOfCoalAlert() { + val configurations: MutableList = ArrayList() + configurations.add(AlertConfiguration(AlertSlot.EXPIRATION, true, 55.toShort(), false, AlertTriggerType.TIME_TRIGGER, 5.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX5)) + + val encoded = ProgramAlertsCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(10.toShort()) // + .setMultiCommandFlag(false) // + .setNonce(1229869870) // + .setAlertConfigurations(configurations) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("02420003280C190A494E532E7837000508020356"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.java deleted file mode 100644 index 16185fdbc4..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.java +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder; - -import static org.junit.Assert.assertArrayEquals; - -public class ProgramBasalCommandTest { - @Test - public void testProgramBasalCommand() throws DecoderException { - List segments = Arrays.asList( - new BasalProgram.Segment((short) 0, (short) 48, 300) - ); - BasalProgram basalProgram = new BasalProgram(segments); - Date date = new Date(2021, 1, 17, 14, 47, 43); - - byte[] encoded = new ProgramBasalCommand.Builder() // - .setUniqueId(37879809) // - .setNonce(1229869870) // - .setSequenceNumber((short) 10) // - .setBasalProgram(basalProgram) // - .setCurrentTime(date) // - .setProgramReminder(new ProgramReminder(false, true, (byte) 0)) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("0242000128241A12494E532E0005E81D1708000CF01EF01EF01E130E40001593004C4B403840005B8D80827C"), encoded); - } - -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt new file mode 100644 index 0000000000..ce33402475 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test +import java.util.* + +class ProgramBasalCommandTest { + + @Test @Throws(DecoderException::class) fun testProgramBasalCommand() { + val segments = listOf( + BasalProgram.Segment(0.toShort(), 48.toShort(), 300) + ) + val basalProgram = BasalProgram(segments) + val date = Date(2021, 1, 17, 14, 47, 43) + + val encoded = ProgramBasalCommand.Builder() // + .setUniqueId(37879809) // + .setNonce(1229869870) // + .setSequenceNumber(10.toShort()) // + .setBasalProgram(basalProgram) // + .setCurrentTime(date) // + .setProgramReminder(ProgramReminder(false, true, 0.toByte())) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("0242000128241A12494E532E0005E81D1708000CF01EF01EF01E130E40001593004C4B403840005B8D80827C"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.java deleted file mode 100644 index 2eea08c718..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder; - -import static org.junit.Assert.assertArrayEquals; - -public class ProgramBolusCommandTest { - @Test - public void testProgramBolusCommand() throws DecoderException { - byte[] encoded = new ProgramBolusCommand.Builder() // - .setNumberOfUnits(5) // - .setProgramReminder(new ProgramReminder(false, true, (byte) 0)) // - .setDelayBetweenPulsesInEighthSeconds((byte) 16) // - .setUniqueId(37879809) // - .setSequenceNumber((short) 14) // - .setNonce(1229869870) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("02420001381F1A0E494E532E02010F01064000640064170D4003E800030D4000000000000080F6"), encoded); - } - -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt new file mode 100644 index 0000000000..ce9ea9c24e --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class ProgramBolusCommandTest { + + @Test @Throws(DecoderException::class) fun testProgramBolusCommand() { + val encoded = ProgramBolusCommand.Builder() // + .setNumberOfUnits(5.0) // + .setProgramReminder(ProgramReminder(false, true, 0.toByte())) // + .setDelayBetweenPulsesInEighthSeconds(16.toByte()) // + .setUniqueId(37879809) // + .setSequenceNumber(14.toShort()) // + .setNonce(1229869870) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("02420001381F1A0E494E532E02010F01064000640064170D4003E800030D4000000000000080F6"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.java deleted file mode 100644 index b622174379..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.java +++ /dev/null @@ -1,39 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder; - -import static org.junit.Assert.assertArrayEquals; - -public class ProgramTempBasalCommandTest { - @Test - public void testExtraAlternateSegmentPulseTempBasal() throws DecoderException { - ProgramTempBasalCommand command = new ProgramTempBasalCommand.Builder() // - .setUniqueId(37879809) // - .setNonce(1229869870) // - .setSequenceNumber((short) 15) // - .setRateInUnitsPerHour(5.05d) // - .setDurationInMinutes((short) 60) // - .setProgramReminder(new ProgramReminder(false, true, (byte) 0)) // - .build(); - - assertArrayEquals(Hex.decodeHex("024200013C201A0E494E532E01011102384000321832160E400003F20036634403F20036634482A6"), command.getEncoded()); - } - - @Test - public void testZeroTempBasal() throws DecoderException { - ProgramTempBasalCommand command = new ProgramTempBasalCommand.Builder() // - .setUniqueId(37879809) // - .setNonce(1229869870) // - .setSequenceNumber((short) 7) // - .setRateInUnitsPerHour(0.0) // - .setDurationInMinutes((short) 300) // - .setProgramReminder(new ProgramReminder(true, true, (byte) 0)) // - .build(); - - assertArrayEquals(Hex.decodeHex("024200011C201A0E494E532E0100820A384000009000160EC000000A6B49D200000AEB49D20001DE"), command.getEncoded()); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt new file mode 100644 index 0000000000..f7875cf2b4 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class ProgramTempBasalCommandTest { + + @Test @Throws(DecoderException::class) fun testExtraAlternateSegmentPulseTempBasal() { + val command = ProgramTempBasalCommand.Builder() // + .setUniqueId(37879809) // + .setNonce(1229869870) // + .setSequenceNumber(15.toShort()) // + .setRateInUnitsPerHour(5.05) // + .setDurationInMinutes(60.toShort()) // + .setProgramReminder(ProgramReminder(false, true, 0.toByte())) // + .build() + + Assert.assertArrayEquals(Hex.decodeHex("024200013C201A0E494E532E01011102384000321832160E400003F20036634403F20036634482A6"), command.encoded) + } + + @Test @Throws(DecoderException::class) fun testZeroTempBasal() { + val command = ProgramTempBasalCommand.Builder() // + .setUniqueId(37879809) // + .setNonce(1229869870) // + .setSequenceNumber(7.toShort()) // + .setRateInUnitsPerHour(0.0) // + .setDurationInMinutes(300.toShort()) // + .setProgramReminder(ProgramReminder(true, true, 0.toByte())) // + .build() + + Assert.assertArrayEquals(Hex.decodeHex("024200011C201A0E494E532E0100820A384000009000160EC000000A6B49D200000AEB49D20001DE"), command.encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.java deleted file mode 100644 index 7965ebe0a1..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import java.util.Date; - -import static org.junit.Assert.assertArrayEquals; - -public class SetUniqueIdCommandTest { - @Test - public void testEncoding() throws DecoderException { - @SuppressWarnings("deprecation") - byte[] encoded = new SetUniqueIdCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 6) // - .setLotNumber(135556289) // - .setPodSequenceNumber(681767) // - .setInitializationTime(new Date(2021, 1, 10, 14, 41)) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("FFFFFFFF18150313024200031404020A150E2908146CC1000A67278344"), encoded); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt new file mode 100644 index 0000000000..4dda5f9a38 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test +import java.util.* + +class SetUniqueIdCommandTest { + + @Test @Throws(DecoderException::class) fun testEncoding() { + val encoded = SetUniqueIdCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(6.toShort()) // + .setLotNumber(135556289) // + .setPodSequenceNumber(681767) // + .setInitializationTime(Date(2021, 1, 10, 14, 41)) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("FFFFFFFF18150313024200031404020A150E2908146CC1000A67278344"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.java deleted file mode 100644 index a8447ed558..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; - -public class SilenceAlertsCommandTest { - @Test - public void testSilenceLowReservoirAlert() throws DecoderException { - byte[] encoded = new SilenceAlertsCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 1) // - .setNonce(1229869870) // - .setSilenceLowReservoirAlert(true) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("0242000304071105494E532E1081CE"), encoded); - } - - // TODO capture more silence alerts commands -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt new file mode 100644 index 0000000000..f901594225 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class SilenceAlertsCommandTest { + + @Test @Throws(DecoderException::class) fun testSilenceLowReservoirAlert() { + val encoded = SilenceAlertsCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(1.toShort()) // + .setNonce(1229869870) // + .setSilenceLowReservoirAlert(true) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("0242000304071105494E532E1081CE"), encoded) + } + + // TODO capture more silence alerts commands +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.java deleted file mode 100644 index 08576996bb..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType; - -import static org.junit.Assert.assertArrayEquals; - -public class StopDeliveryCommandTest { - @Test - public void testStopTempBasal() throws DecoderException { - byte[] encoded = new StopDeliveryCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 0) // - .setNonce(1229869870) // - .setDeliveryType(StopDeliveryCommand.DeliveryType.TEMP_BASAL) // - .setBeepType(BeepType.LONG_SINGLE_BEEP) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("0242000300071F05494E532E6201B1"), encoded); - } - - @Test - public void testSuspendDelivery() throws DecoderException { - byte[] encoded = new StopDeliveryCommand.Builder() // - .setUniqueId(37879811) // - .setSequenceNumber((short) 2) // - .setNonce(1229869870) // - .setDeliveryType(StopDeliveryCommand.DeliveryType.ALL) // - .setBeepType(BeepType.SILENT) // - .build() // - .getEncoded(); - - assertArrayEquals(Hex.decodeHex("0242000308071F05494E532E078287"), encoded); - } - - // TODO test cancel bolus -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt new file mode 100644 index 0000000000..a9463e1785 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt @@ -0,0 +1,38 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class StopDeliveryCommandTest { + + @Test @Throws(DecoderException::class) fun testStopTempBasal() { + val encoded = StopDeliveryCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(0.toShort()) // + .setNonce(1229869870) // + .setDeliveryType(StopDeliveryCommand.DeliveryType.TEMP_BASAL) // + .setBeepType(BeepType.LONG_SINGLE_BEEP) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("0242000300071F05494E532E6201B1"), encoded) + } + + @Test @Throws(DecoderException::class) fun testSuspendDelivery() { + val encoded = StopDeliveryCommand.Builder() // + .setUniqueId(37879811) // + .setSequenceNumber(2.toShort()) // + .setNonce(1229869870) // + .setDeliveryType(StopDeliveryCommand.DeliveryType.ALL) // + .setBeepType(BeepType.SILENT) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("0242000308071F05494E532E078287"), encoded) + } + + // TODO test cancel bolus +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.java deleted file mode 100644 index 892f22cdb2..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.java +++ /dev/null @@ -1,56 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; - -public class AlarmStatusResponseTest { - @Test - public void testValidResponse() throws DecoderException { - byte[] encoded = Hex.decodeHex("021602080100000501BD00000003FF01950000000000670A"); - AlarmStatusResponse response = new AlarmStatusResponse(encoded); - - assertArrayEquals(encoded, response.getEncoded()); - assertNotSame(encoded, response.getEncoded()); - assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE, response.getResponseType()); - assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.getValue(), response.getMessageType()); - assertEquals(ResponseType.AdditionalStatusResponseType.ALARM_STATUS, response.getStatusResponseType()); - assertEquals(ResponseType.AdditionalStatusResponseType.ALARM_STATUS.getValue(), response.getAdditionalStatusResponseType()); - assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()); - assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()); - assertEquals((short) 0, response.getBolusPulsesRemaining()); - assertEquals((short) 5, response.getSequenceNumberOfLastProgrammingCommand()); - assertEquals((short) 445, response.getTotalPulsesDelivered()); - assertEquals(AlarmType.NONE, response.getAlarmType()); - assertEquals((short) 0, response.getAlarmTime()); - assertEquals((short) 1023, response.getReservoirPulsesRemaining()); - assertEquals((short) 405, response.getMinutesSinceActivation()); - assertFalse(response.isAlert0Active()); - assertFalse(response.isAlert1Active()); - assertFalse(response.isAlert2Active()); - assertFalse(response.isAlert3Active()); - assertFalse(response.isAlert4Active()); - assertFalse(response.isAlert5Active()); - assertFalse(response.isAlert6Active()); - assertFalse(response.isAlert7Active()); - assertFalse(response.isOcclusionAlarm()); - assertFalse(response.isPulseInfoInvalid()); - assertEquals(PodStatus.UNINITIALIZED, response.getPodStatusWhenAlarmOccurred()); - assertFalse(response.isImmediateBolusWhenAlarmOccurred()); - assertEquals((byte) 0x00, response.getOcclusionType()); - assertFalse(response.isOccurredWhenFetchingImmediateBolusActiveInformation()); - assertEquals(0, response.getRssi()); - assertEquals(0, response.getReceiverLowerGain()); - assertEquals(PodStatus.UNINITIALIZED, response.getPodStatusWhenAlarmOccurred2()); - assertEquals((short) 26378, response.getReturnAddressOfPodAlarmHandlerCaller()); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt new file mode 100644 index 0000000000..0f4e850a8b --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt @@ -0,0 +1,52 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class AlarmStatusResponseTest { + + @Test @Throws(DecoderException::class) fun testValidResponse() { + val encoded = Hex.decodeHex("021602080100000501BD00000003FF01950000000000670A") + val response = AlarmStatusResponse(encoded) + + Assert.assertArrayEquals(encoded, response.encoded) + Assert.assertNotSame(encoded, response.encoded) + Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE, response.responseType) + Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(ResponseType.AdditionalStatusResponseType.ALARM_STATUS, response.statusResponseType) + Assert.assertEquals(ResponseType.AdditionalStatusResponseType.ALARM_STATUS.getValue(), response.getAdditionalStatusResponseType()) + Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()) + Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()) + Assert.assertEquals(0.toShort(), response.getBolusPulsesRemaining()) + Assert.assertEquals(5.toShort(), response.getSequenceNumberOfLastProgrammingCommand()) + Assert.assertEquals(445.toShort(), response.getTotalPulsesDelivered()) + Assert.assertEquals(AlarmType.NONE, response.getAlarmType()) + Assert.assertEquals(0.toShort(), response.getAlarmTime()) + Assert.assertEquals(1023.toShort(), response.getReservoirPulsesRemaining()) + Assert.assertEquals(405.toShort(), response.getMinutesSinceActivation()) + Assert.assertFalse(response.isAlert0Active()) + Assert.assertFalse(response.isAlert1Active()) + Assert.assertFalse(response.isAlert2Active()) + Assert.assertFalse(response.isAlert3Active()) + Assert.assertFalse(response.isAlert4Active()) + Assert.assertFalse(response.isAlert5Active()) + Assert.assertFalse(response.isAlert6Active()) + Assert.assertFalse(response.isAlert7Active()) + Assert.assertFalse(response.isOcclusionAlarm()) + Assert.assertFalse(response.isPulseInfoInvalid()) + Assert.assertEquals(PodStatus.UNINITIALIZED, response.getPodStatusWhenAlarmOccurred()) + Assert.assertFalse(response.isImmediateBolusWhenAlarmOccurred()) + Assert.assertEquals(0x00.toByte(), response.getOcclusionType()) + Assert.assertFalse(response.isOccurredWhenFetchingImmediateBolusActiveInformation()) + Assert.assertEquals(0.toShort(), response.getRssi()) + Assert.assertEquals(0.toShort(), response.getReceiverLowerGain()) + Assert.assertEquals(PodStatus.UNINITIALIZED, response.getPodStatusWhenAlarmOccurred2()) + Assert.assertEquals(26378.toShort(), response.getReturnAddressOfPodAlarmHandlerCaller()) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.java deleted file mode 100644 index 2e3ddbd7c1..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; - -public class DefaultStatusResponseTest { - @Test - public void testValidResponse() throws DecoderException { - byte[] encoded = Hex.decodeHex("1D1800A02800000463FF"); - DefaultStatusResponse response = new DefaultStatusResponse(encoded); - - assertArrayEquals(encoded, response.getEncoded()); - assertNotSame(encoded, response.getEncoded()); - assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE, response.getResponseType()); - assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE.getValue(), response.getMessageType()); - assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()); - assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()); - assertEquals((short) 320, response.getTotalPulsesDelivered()); - assertEquals((short) 5, response.getSequenceNumberOfLastProgrammingCommand()); - assertEquals((short) 0, response.getBolusPulsesRemaining()); - assertFalse(response.isOcclusionAlertActive()); - assertFalse(response.isAlert1Active()); - assertFalse(response.isAlert2Active()); - assertFalse(response.isAlert3Active()); - assertFalse(response.isAlert4Active()); - assertFalse(response.isAlert5Active()); - assertFalse(response.isAlert6Active()); - assertFalse(response.isAlert7Active()); - assertEquals((short) 280, response.getMinutesSinceActivation()); - assertEquals((short) 1023, response.getReservoirPulsesRemaining()); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt new file mode 100644 index 0000000000..392f87bf19 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class DefaultStatusResponseTest { + + @Test @Throws(DecoderException::class) fun testValidResponse() { + val encoded = Hex.decodeHex("1D1800A02800000463FF") + val response = DefaultStatusResponse(encoded) + Assert.assertArrayEquals(encoded, response.encoded) + Assert.assertNotSame(encoded, response.encoded) + Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE, response.responseType) + Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()) + Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()) + Assert.assertEquals(320.toShort(), response.getTotalPulsesDelivered()) + Assert.assertEquals(5.toShort(), response.getSequenceNumberOfLastProgrammingCommand()) + Assert.assertEquals(0.toShort(), response.getBolusPulsesRemaining()) + Assert.assertFalse(response.isOcclusionAlertActive()) + Assert.assertFalse(response.isAlert1Active()) + Assert.assertFalse(response.isAlert2Active()) + Assert.assertFalse(response.isAlert3Active()) + Assert.assertFalse(response.isAlert4Active()) + Assert.assertFalse(response.isAlert5Active()) + Assert.assertFalse(response.isAlert6Active()) + Assert.assertFalse(response.isAlert7Active()) + Assert.assertEquals(280.toShort(), response.getMinutesSinceActivation()) + Assert.assertEquals(1023.toShort(), response.getReservoirPulsesRemaining()) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.java deleted file mode 100644 index 06937a0e92..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType; -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -public class NakResponseTest { - @Test - public void testValidResponse() throws DecoderException { - byte[] encoded = Hex.decodeHex("0603070009"); - NakResponse response = new NakResponse(encoded); - - assertArrayEquals(encoded, response.getEncoded()); - assertNotSame(encoded, response.getEncoded()); - assertEquals(ResponseType.NAK_RESPONSE, response.getResponseType()); - assertEquals(ResponseType.NAK_RESPONSE.getValue(), response.getMessageType()); - assertEquals(NakErrorType.ILLEGAL_PARAM, response.getNakErrorType()); - assertEquals(AlarmType.NONE, response.getAlarmType()); - assertEquals(PodStatus.RUNNING_BELOW_MIN_VOLUME, response.getPodStatus()); - assertEquals((byte) 0x00, response.getSecurityNakSyncCount()); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt new file mode 100644 index 0000000000..545b9e9b3e --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class NakResponseTest { + + @Test @Throws(DecoderException::class) fun testValidResponse() { + val encoded = Hex.decodeHex("0603070009") + val response = NakResponse(encoded) + + Assert.assertArrayEquals(encoded, response.encoded) + Assert.assertNotSame(encoded, response.encoded) + Assert.assertEquals(ResponseType.NAK_RESPONSE, response.responseType) + Assert.assertEquals(ResponseType.NAK_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(NakErrorType.ILLEGAL_PARAM, response.getNakErrorType()) + Assert.assertEquals(AlarmType.NONE, response.getAlarmType()) + Assert.assertEquals(PodStatus.RUNNING_BELOW_MIN_VOLUME, response.getPodStatus()) + Assert.assertEquals(0x00.toShort(), response.getSecurityNakSyncCount()) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.java deleted file mode 100644 index 1de262db9d..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.java +++ /dev/null @@ -1,44 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -public class SetUniqueIdResponseTest { - @Test - public void testValidResponse() throws DecoderException { - byte[] encoded = Hex.decodeHex("011B13881008340A50040A00010300040308146CC1000954D402420001"); - SetUniqueIdResponse response = new SetUniqueIdResponse(encoded); - - assertArrayEquals(encoded, response.getEncoded()); - assertNotSame(encoded, response.getEncoded()); - assertEquals(ResponseType.ACTIVATION_RESPONSE, response.getResponseType()); - assertEquals(ResponseType.ActivationResponseType.SET_UNIQUE_ID_RESPONSE, response.getActivationResponseType()); - - assertEquals(ResponseType.ACTIVATION_RESPONSE.getValue(), response.getMessageType()); - assertEquals(27, response.getMessageLength()); - assertEquals(5000, response.getPulseVolumeInTenThousandthMicroLiter()); - assertEquals(16, response.getDeliveryRate()); - assertEquals(8, response.getPrimeRate()); - assertEquals(52, response.getNumberOfEngagingClutchDrivePulses()); - assertEquals(10, response.getNumberOfPrimePulses()); - assertEquals(80, response.getPodExpirationTimeInHours()); - assertEquals(4, response.getFirmwareVersionMajor()); - assertEquals(10, response.getFirmwareVersionMinor()); - assertEquals(0, response.getFirmwareVersionInterim()); - assertEquals(1, response.getBleVersionMajor()); - assertEquals(3, response.getBleVersionMinor()); - assertEquals(0, response.getBleVersionInterim()); - assertEquals(4, response.getProductId()); - assertEquals(PodStatus.UID_SET, response.getPodStatus()); - assertEquals(135556289L, response.getLotNumber()); - assertEquals(611540L, response.getPodSequenceNumber()); - assertEquals(37879809L, response.getUniqueIdReceivedInCommand()); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt new file mode 100644 index 0000000000..ef10e5d39d --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt @@ -0,0 +1,40 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class SetUniqueIdResponseTest { + + @Test @Throws(DecoderException::class) fun testValidResponse() { + val encoded = Hex.decodeHex("011B13881008340A50040A00010300040308146CC1000954D402420001") + val response = SetUniqueIdResponse(encoded) + + Assert.assertArrayEquals(encoded, response.encoded) + Assert.assertNotSame(encoded, response.encoded) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE, response.responseType) + Assert.assertEquals(ResponseType.ActivationResponseType.SET_UNIQUE_ID_RESPONSE, response.activationResponseType) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(27.toShort(), response.getMessageLength()) + Assert.assertEquals(5000.toShort(), response.getPulseVolumeInTenThousandthMicroLiter()) + Assert.assertEquals(16.toShort(), response.getDeliveryRate()) + Assert.assertEquals(8.toShort(), response.getPrimeRate()) + Assert.assertEquals(52.toShort(), response.getNumberOfEngagingClutchDrivePulses()) + Assert.assertEquals(10.toShort(), response.getNumberOfPrimePulses()) + Assert.assertEquals(80.toShort(), response.getPodExpirationTimeInHours()) + Assert.assertEquals(4.toShort(), response.getFirmwareVersionMajor()) + Assert.assertEquals(10.toShort(), response.getFirmwareVersionMinor()) + Assert.assertEquals(0.toShort(), response.getFirmwareVersionInterim()) + Assert.assertEquals(1.toShort(), response.getBleVersionMajor()) + Assert.assertEquals(3.toShort(), response.getBleVersionMinor()) + Assert.assertEquals(0.toShort(), response.getBleVersionInterim()) + Assert.assertEquals(4.toShort(), response.getProductId()) + Assert.assertEquals(PodStatus.UID_SET, response.getPodStatus()) + Assert.assertEquals(135556289L, response.getLotNumber()) + Assert.assertEquals(611540L, response.getPodSequenceNumber()) + Assert.assertEquals(37879809L, response.getUniqueIdReceivedInCommand()) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.java b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.java deleted file mode 100644 index c88142a715..0000000000 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response; - -import org.apache.commons.codec.DecoderException; -import org.apache.commons.codec.binary.Hex; -import org.junit.Test; - -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - -public class VersionResponseTest { - - @Test - public void testValidResponse() throws DecoderException { - byte[] encoded = Hex.decodeHex("0115040A00010300040208146CC1000954D400FFFFFFFF"); - VersionResponse response = new VersionResponse(encoded); - - assertArrayEquals(encoded, response.getEncoded()); - assertNotSame(encoded, response.getEncoded()); - assertEquals(ResponseType.ACTIVATION_RESPONSE, response.getResponseType()); - assertEquals(ResponseType.ActivationResponseType.GET_VERSION_RESPONSE, response.getActivationResponseType()); - - assertEquals(ResponseType.ACTIVATION_RESPONSE.getValue(), response.getMessageType()); - assertEquals(21, response.getMessageLength()); - assertEquals(4, response.getFirmwareVersionMajor()); - assertEquals(10, response.getFirmwareVersionMinor()); - assertEquals(0, response.getFirmwareVersionInterim()); - assertEquals(1, response.getBleVersionMajor()); - assertEquals(3, response.getBleVersionMinor()); - assertEquals(0, response.getBleVersionInterim()); - assertEquals(4, response.getProductId()); - assertEquals(PodStatus.FILLED, response.getPodStatus()); - assertEquals(135556289, response.getLotNumber()); - assertEquals(611540, response.getPodSequenceNumber()); - assertEquals(0L, response.getRssi()); - assertEquals(0L, response.getReceiverLowerGain()); - assertEquals(4294967295L, response.getUniqueIdReceivedInCommand()); - } -} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt new file mode 100644 index 0000000000..58cce6336a --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class VersionResponseTest { + + @Test @Throws(DecoderException::class) fun testValidResponse() { + val encoded = Hex.decodeHex("0115040A00010300040208146CC1000954D400FFFFFFFF") + val response = VersionResponse(encoded) + + Assert.assertArrayEquals(encoded, response.encoded) + Assert.assertNotSame(encoded, response.encoded) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE, response.responseType) + Assert.assertEquals(ResponseType.ActivationResponseType.GET_VERSION_RESPONSE, response.activationResponseType) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(21.toShort(), response.getMessageLength()) + Assert.assertEquals(4.toShort(), response.getFirmwareVersionMajor()) + Assert.assertEquals(10.toShort(), response.getFirmwareVersionMinor()) + Assert.assertEquals(0.toShort(), response.getFirmwareVersionInterim()) + Assert.assertEquals(1.toShort(), response.getBleVersionMajor()) + Assert.assertEquals(3.toShort(), response.getBleVersionMinor()) + Assert.assertEquals(0.toShort(), response.getBleVersionInterim()) + Assert.assertEquals(4.toShort(), response.getProductId()) + Assert.assertEquals(PodStatus.FILLED, response.getPodStatus()) + Assert.assertEquals(135556289L, response.getLotNumber()) + Assert.assertEquals(611540L, response.getPodSequenceNumber()) + Assert.assertEquals(0.toByte(), response.getRssi()) + Assert.assertEquals(0.toByte(), response.getReceiverLowerGain()) + Assert.assertEquals(4294967295L, response.getUniqueIdReceivedInCommand()) + } +} \ No newline at end of file From 2c9e9e7e740e8696da06ef7ed4e04d0f5adb2d3e Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 13:33:13 +0100 Subject: [PATCH 025/649] Define OmnipodDashBleManager interface --- .../dash/driver/comm/OmnipodDashBleManager.kt | 13 +++++++++-- .../driver/comm/OmnipodDashBleManagerImpl.kt | 22 +++++++++++++++++-- .../driver/comm/status/ConnectionStatus.kt | 4 ++++ 3 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index c90e0438b4..005fa74e45 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -1,7 +1,16 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response + interface OmnipodDashBleManager { - // TODO should we keep this method? - fun activateNewPod() + fun sendCommand(cmd: Command): Response; + + fun getStatus(): ConnectionStatus; + + fun connect() + + fun disconnect() } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 54a89a9b3b..f2d0936b90 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -13,6 +13,9 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException @@ -26,7 +29,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - override fun activateNewPod() { + fun activateNewPod() { aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") val podScanner = PodScanner(aapsLogger, bluetoothAdapter) val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address @@ -64,8 +67,23 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context bleIO.readyToRead() } - companion object { + override fun sendCommand(cmd: Command): Response { + TODO("not implemented") + } + override fun getStatus(): ConnectionStatus { + TODO("not implemented") + } + + override fun connect() { + TODO("not implemented") + } + + override fun disconnect() { + TODO("not implemented") + } + + companion object { private const val CONNECT_TIMEOUT_MS = 5000 private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt new file mode 100644 index 0000000000..76d9ec5eed --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status + +interface ConnectionStatus { +} \ No newline at end of file From 2675592a54f782d6e64e9013162351a66c3db225 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 13:34:16 +0100 Subject: [PATCH 026/649] Revert "Define OmnipodDashBleManager interface" This reverts commit 2c9e9e7e740e8696da06ef7ed4e04d0f5adb2d3e. --- .../dash/driver/comm/OmnipodDashBleManager.kt | 13 ++--------- .../driver/comm/OmnipodDashBleManagerImpl.kt | 22 ++----------------- .../driver/comm/status/ConnectionStatus.kt | 4 ---- 3 files changed, 4 insertions(+), 35 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index 005fa74e45..c90e0438b4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -1,16 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response - interface OmnipodDashBleManager { - fun sendCommand(cmd: Command): Response; - - fun getStatus(): ConnectionStatus; - - fun connect() - - fun disconnect() + // TODO should we keep this method? + fun activateNewPod() } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index f2d0936b90..54a89a9b3b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -13,9 +13,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException @@ -29,7 +26,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - fun activateNewPod() { + override fun activateNewPod() { aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") val podScanner = PodScanner(aapsLogger, bluetoothAdapter) val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address @@ -67,23 +64,8 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context bleIO.readyToRead() } - override fun sendCommand(cmd: Command): Response { - TODO("not implemented") - } - - override fun getStatus(): ConnectionStatus { - TODO("not implemented") - } - - override fun connect() { - TODO("not implemented") - } - - override fun disconnect() { - TODO("not implemented") - } - companion object { + private const val CONNECT_TIMEOUT_MS = 5000 private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt deleted file mode 100644 index 76d9ec5eed..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status - -interface ConnectionStatus { -} \ No newline at end of file From a23c3f2cd860d1192359f945a62e5cf3155f7006 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 13:33:13 +0100 Subject: [PATCH 027/649] Define OmnipodDashBleManager interface --- .../dash/driver/comm/OmnipodDashBleManager.kt | 13 +++++++++-- .../driver/comm/OmnipodDashBleManagerImpl.kt | 22 +++++++++++++++++-- .../driver/comm/status/ConnectionStatus.kt | 4 ++++ 3 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index c90e0438b4..005fa74e45 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -1,7 +1,16 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response + interface OmnipodDashBleManager { - // TODO should we keep this method? - fun activateNewPod() + fun sendCommand(cmd: Command): Response; + + fun getStatus(): ConnectionStatus; + + fun connect() + + fun disconnect() } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 54a89a9b3b..f2d0936b90 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -13,6 +13,9 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException @@ -26,7 +29,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - override fun activateNewPod() { + fun activateNewPod() { aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") val podScanner = PodScanner(aapsLogger, bluetoothAdapter) val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address @@ -64,8 +67,23 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context bleIO.readyToRead() } - companion object { + override fun sendCommand(cmd: Command): Response { + TODO("not implemented") + } + override fun getStatus(): ConnectionStatus { + TODO("not implemented") + } + + override fun connect() { + TODO("not implemented") + } + + override fun disconnect() { + TODO("not implemented") + } + + companion object { private const val CONNECT_TIMEOUT_MS = 5000 private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt new file mode 100644 index 0000000000..76d9ec5eed --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status + +interface ConnectionStatus { +} \ No newline at end of file From f0e333da6cb2b31ac0b39dd91d006a0d2fac75c9 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 13:37:44 +0100 Subject: [PATCH 028/649] format --- .../pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index 005fa74e45..e673818629 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response. interface OmnipodDashBleManager { - fun sendCommand(cmd: Command): Response; + fun sendCommand(cmd: Command): Response - fun getStatus(): ConnectionStatus; + fun getStatus(): ConnectionStatus fun connect() From 69c0b5afa7f5ac93b8d46d4aea06572593698e82 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 14:41:18 +0100 Subject: [PATCH 029/649] Add Omnipod Dash GetStatusCommand and ProgramBeepsCommand --- .../omnipod/dash/driver/OmnipodDashManager.kt | 11 ++- .../dash/driver/OmnipodDashManagerImpl.kt | 17 ++++- .../driver/pod/command/GetStatusCommand.kt | 46 ++++++++++++ .../driver/pod/command/ProgramBeepsCommand.kt | 73 +++++++++++++++++++ .../response/AdditionalStatusResponseBase.kt | 4 +- .../pod/response/AlarmStatusResponse.kt | 4 +- .../dash/driver/pod/response/ResponseType.kt | 38 ++++++---- .../pod/command/GetStatusCommandTest.kt | 21 ++++++ .../pod/command/ProgramBeepsCommandTest.kt | 25 +++++++ .../pod/response/AlarmStatusResponseTest.kt | 7 +- .../pod/response/DefaultStatusResponseTest.kt | 2 +- .../driver/pod/response/NakResponseTest.kt | 2 +- .../pod/response/SetUniqueIdResponseTest.kt | 2 +- .../pod/response/VersionResponseTest.kt | 2 +- 14 files changed, 225 insertions(+), 29 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index fdb08804b3..3063c6de12 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -1,8 +1,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import io.reactivex.Observable +import java.util.* interface OmnipodDashManager { @@ -26,7 +29,11 @@ interface OmnipodDashManager { fun cancelBolus(): Observable - fun silenceAlerts(): Observable + fun programBeeps(): Observable + + fun programAlerts(alertConfigurations: List): Observable + + fun silenceAlerts(alerts: EnumSet): Observable fun deactivatePod(): Observable } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 2b2e968b55..0385a74619 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -2,10 +2,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import io.reactivex.Observable +import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -66,7 +69,17 @@ class OmnipodDashManagerImpl @Inject constructor( return Observable.empty() } - override fun silenceAlerts(): Observable { + override fun programBeeps(): Observable { + // TODO + return Observable.empty() + } + + override fun programAlerts(alertConfigurations: List): Observable { + // TODO + return Observable.empty() + } + + override fun silenceAlerts(alerts: EnumSet): Observable { // TODO return Observable.empty() } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt new file mode 100644 index 0000000000..c08b251cb4 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt @@ -0,0 +1,46 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import java.nio.ByteBuffer + +class GetStatusCommand( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val statusResponseType: ResponseType.StatusResponseType +) : HeaderEnabledCommand(CommandType.GET_STATUS, uniqueId, sequenceNumber, multiCommandFlag) { + + override val encoded: ByteArray + get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .put(statusResponseType.value) // + .array()) + + class Builder : HeaderEnabledCommandBuilder() { + + private var statusResponseType: ResponseType.StatusResponseType? = null + + fun setStatusResponseType(statusResponseType: ResponseType.StatusResponseType): Builder { + this.statusResponseType = statusResponseType + return this + } + + override fun buildCommand(): GetStatusCommand { + requireNotNull(statusResponseType) { "immediateBeepType can not be null" } + + return GetStatusCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, statusResponseType!!) + } + + } + + companion object { + + private const val LENGTH: Short = 3 + private const val BODY_LENGTH: Byte = 1 + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt new file mode 100644 index 0000000000..f000270bd5 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt @@ -0,0 +1,73 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.HeaderEnabledCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import java.nio.ByteBuffer + +class ProgramBeepsCommand internal constructor( + uniqueId: Int, + sequenceNumber: Short, + multiCommandFlag: Boolean, + private val immediateBeepType: BeepType, + private val basalReminder: ProgramReminder, + private val tempBasalReminder: ProgramReminder, + private val bolusReminder: ProgramReminder +) : HeaderEnabledCommand(CommandType.PROGRAM_BEEPS, uniqueId, sequenceNumber, multiCommandFlag) { + + override val encoded: ByteArray + get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .put(immediateBeepType.value) // + .put(basalReminder.encoded) // + .put(tempBasalReminder.encoded) // + .put(bolusReminder.encoded) // + .array()) + + class Builder : HeaderEnabledCommandBuilder() { + + private var immediateBeepType: BeepType? = null + private var basalReminder: ProgramReminder? = null + private var tempBasalReminder: ProgramReminder? = null + private var bolusReminder: ProgramReminder? = null + + fun setImmediateBeepType(beepType: BeepType): Builder { + this.immediateBeepType = beepType + return this + } + + fun setBasalReminder(programReminder: ProgramReminder): Builder { + this.basalReminder = programReminder + return this + } + + fun setTempBasalReminder(programReminder: ProgramReminder): Builder { + this.tempBasalReminder = programReminder + return this + } + + fun setBolusReminder(programReminder: ProgramReminder): Builder { + this.bolusReminder = programReminder + return this + } + + override fun buildCommand(): ProgramBeepsCommand { + requireNotNull(immediateBeepType) { "immediateBeepType can not be null" } + requireNotNull(basalReminder) { "basalReminder can not be null" } + requireNotNull(tempBasalReminder) { "tempBasalReminder can not be null" } + requireNotNull(bolusReminder) { "bolusReminder can not be null" } + + return ProgramBeepsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, immediateBeepType!!, basalReminder!!, tempBasalReminder!!, bolusReminder!!) + } + } + + companion object { + + private const val LENGTH: Short = 6 + private const val BODY_LENGTH: Byte = 4 + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt index 414a710723..0ce01d962d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.AdditionalStatusResponseType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.StatusResponseType open class AdditionalStatusResponseBase internal constructor( - val statusResponseType: AdditionalStatusResponseType, + val statusResponseType: StatusResponseType, encoded: ByteArray ) : ResponseBase(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index 4cce00a1c6..736213161a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -3,14 +3,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.AdditionalStatusResponseType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.StatusResponseType import java.nio.ByteBuffer import java.util.* import kotlin.experimental.and class AlarmStatusResponse( encoded: ByteArray -) : AdditionalStatusResponseBase(AdditionalStatusResponseType.ALARM_STATUS, encoded) { +) : AdditionalStatusResponseBase(StatusResponseType.ALARM_STATUS, encoded) { private val messageType: Byte private val messageLength: Short diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt index 6c6c19ae80..ad08b4b3ec 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response enum class ResponseType( - private val value: Byte + val value: Byte ) { ACTIVATION_RESPONSE(0x01.toByte()), @@ -10,20 +10,25 @@ enum class ResponseType( NAK_RESPONSE(0x06.toByte()), UNKNOWN(0xff.toByte()); - fun getValue(): Byte { - return value - } + enum class StatusResponseType( + val value: Byte + ) { - enum class AdditionalStatusResponseType(private val value: Byte) { - STATUS_RESPONSE_PAGE_1(0x01.toByte()), ALARM_STATUS(0x02.toByte()), STATUS_RESPONSE_PAGE_3(0x03.toByte()), STATUS_RESPONSE_PAGE_5(0x05.toByte()), STATUS_RESPONSE_PAGE_6(0x06.toByte()), STATUS_RESPONSE_PAGE_70(0x46.toByte()), STATUS_RESPONSE_PAGE_80(0x50.toByte()), STATUS_RESPONSE_PAGE_81(0x51.toByte()), UNKNOWN(0xff.toByte()); - - fun getValue(): Byte { - return value - } + DEFAULT_STATUS_RESPONSE(0x00.toByte()), + STATUS_RESPONSE_PAGE_1(0x01.toByte()), + ALARM_STATUS(0x02.toByte()), + STATUS_RESPONSE_PAGE_3(0x03.toByte()), + STATUS_RESPONSE_PAGE_5(0x05.toByte()), + STATUS_RESPONSE_PAGE_6(0x06.toByte()), + STATUS_RESPONSE_PAGE_70(0x46.toByte()), + STATUS_RESPONSE_PAGE_80(0x50.toByte()), + STATUS_RESPONSE_PAGE_81(0x51.toByte()), + UNKNOWN(0xff.toByte()); companion object { - fun byValue(value: Byte): AdditionalStatusResponseType { + @JvmStatic + fun byValue(value: Byte): StatusResponseType { for (type in values()) { if (type.value == value) { return type @@ -34,11 +39,17 @@ enum class ResponseType( } } - enum class ActivationResponseType(private val length: Byte) { - GET_VERSION_RESPONSE(0x15.toByte()), SET_UNIQUE_ID_RESPONSE(0x1b.toByte()), UNKNOWN(0xff.toByte()); + enum class ActivationResponseType( + val length: Byte + ) { + + GET_VERSION_RESPONSE(0x15.toByte()), + SET_UNIQUE_ID_RESPONSE(0x1b.toByte()), + UNKNOWN(0xff.toByte()); companion object { + @JvmStatic fun byLength(length: Byte): ActivationResponseType { for (type in values()) { if (type.length == length) { @@ -52,6 +63,7 @@ enum class ResponseType( companion object { + @JvmStatic fun byValue(value: Byte): ResponseType { for (type in values()) { if (type.value == value) { diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt new file mode 100644 index 0000000000..4a73a9ebb4 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class GetStatusCommandTest { + + @Test @Throws(DecoderException::class) fun testGetDefaultStatusResponse() { + val encoded = GetStatusCommand.Builder() // + .setUniqueId(37879810) // + .setSequenceNumber(15.toShort()) // + .setStatusResponseType(ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("024200023C030E0100024C"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt new file mode 100644 index 0000000000..cd5d06c451 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt @@ -0,0 +1,25 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder +import org.apache.commons.codec.DecoderException +import org.apache.commons.codec.binary.Hex +import org.junit.Assert +import org.junit.Test + +class ProgramBeepsCommandTest { + + @Test @Throws(DecoderException::class) fun testPlayTestBeep() { + val encoded = ProgramBeepsCommand.Builder() // + .setUniqueId(37879810) // + .setSequenceNumber(11.toShort()) // + .setImmediateBeepType(BeepType.FOUR_TIMES_BIP_BEEP) // + .setBasalReminder(ProgramReminder(false, false, 0.toByte())) // + .setTempBasalReminder(ProgramReminder(false, false, 0.toByte())) // + .setBolusReminder(ProgramReminder(false, false, 0.toByte())) // + .build() // + .encoded + + Assert.assertArrayEquals(Hex.decodeHex("024200022C061E0402000000800F"), encoded) + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt index 0f4e850a8b..1621faccb2 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert @@ -18,9 +17,9 @@ class AlarmStatusResponseTest { Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE, response.responseType) - Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.getValue(), response.getMessageType()) - Assert.assertEquals(ResponseType.AdditionalStatusResponseType.ALARM_STATUS, response.statusResponseType) - Assert.assertEquals(ResponseType.AdditionalStatusResponseType.ALARM_STATUS.getValue(), response.getAdditionalStatusResponseType()) + Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.value, response.getMessageType()) + Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS, response.statusResponseType) + Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS.value, response.getAdditionalStatusResponseType()) Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()) Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()) Assert.assertEquals(0.toShort(), response.getBolusPulsesRemaining()) diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt index 392f87bf19..6ccbdfd13e 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt @@ -16,7 +16,7 @@ class DefaultStatusResponseTest { Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE, response.responseType) - Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE.value, response.getMessageType()) Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()) Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()) Assert.assertEquals(320.toShort(), response.getTotalPulsesDelivered()) diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt index 545b9e9b3e..c4dc703f79 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt @@ -18,7 +18,7 @@ class NakResponseTest { Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.NAK_RESPONSE, response.responseType) - Assert.assertEquals(ResponseType.NAK_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(ResponseType.NAK_RESPONSE.value, response.getMessageType()) Assert.assertEquals(NakErrorType.ILLEGAL_PARAM, response.getNakErrorType()) Assert.assertEquals(AlarmType.NONE, response.getAlarmType()) Assert.assertEquals(PodStatus.RUNNING_BELOW_MIN_VOLUME, response.getPodStatus()) diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt index ef10e5d39d..fa0d1dac73 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt @@ -17,7 +17,7 @@ class SetUniqueIdResponseTest { Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE, response.responseType) Assert.assertEquals(ResponseType.ActivationResponseType.SET_UNIQUE_ID_RESPONSE, response.activationResponseType) - Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.value, response.getMessageType()) Assert.assertEquals(27.toShort(), response.getMessageLength()) Assert.assertEquals(5000.toShort(), response.getPulseVolumeInTenThousandthMicroLiter()) Assert.assertEquals(16.toShort(), response.getDeliveryRate()) diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt index 58cce6336a..32612070fd 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt @@ -17,7 +17,7 @@ class VersionResponseTest { Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE, response.responseType) Assert.assertEquals(ResponseType.ActivationResponseType.GET_VERSION_RESPONSE, response.activationResponseType) - Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.getValue(), response.getMessageType()) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.value, response.getMessageType()) Assert.assertEquals(21.toShort(), response.getMessageLength()) Assert.assertEquals(4.toShort(), response.getFirmwareVersionMajor()) Assert.assertEquals(10.toShort(), response.getFirmwareVersionMinor()) From 72d0ca774f4a835a11b144e831dd707cd83974b8 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 16:04:26 +0100 Subject: [PATCH 030/649] define connection status as enum class --- .../pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt index 76d9ec5eed..3f11ca87b5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt @@ -1,4 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status -interface ConnectionStatus { +enum class ConnectionStatus { + CONNECTED, + NOT_CONNECTED; } \ No newline at end of file From 08ff02dd4f0a3129244507c41fc62885cc602606 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Thu, 25 Feb 2021 19:03:38 +0100 Subject: [PATCH 031/649] ble: start implementing message splitting and sending --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 16 ++++- .../dash/driver/comm/ServiceDiscoverer.kt | 2 + .../driver/comm/callbacks/BleCommCallbacks.kt | 4 +- .../dash/driver/comm/command/BleCommand.kt | 36 +++++++--- .../driver/comm/command/BleCommandNack.kt | 4 ++ .../exceptions/CouldNotEnableNotifications.kt | 2 +- .../exceptions/UnexpectedCommandException.kt | 7 ++ .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 1 - .../comm/{ => io}/CharacteristicType.kt | 2 +- .../dash/driver/comm/io/PayloadJoiner.kt | 16 +++++ .../dash/driver/comm/io/PayloadSplitter.kt | 69 +++++++++++++++++++ .../pump/omnipod/dash/driver/comm/ltk/LTK.kt | 12 ++++ .../dash/driver/comm/ltk/LTKExchanger.kt | 23 +++++++ .../dash/driver/comm/message/Address.kt | 7 ++ .../dash/driver/comm/message/Message.kt | 23 +++++++ .../dash/driver/comm/message/MessageIO.kt | 43 ++++++++++++ .../dash/driver/comm/message/MessageType.kt | 14 ++++ .../dash/driver/comm/message/PairMessage.kt | 8 +++ .../dash/driver/comm/packet/BlePacket.kt | 33 ++++++++- .../driver/comm/scan/BleDiscoveredDevice.kt | 15 ++-- .../dash/driver/comm/scan/ScanCollector.kt | 8 ++- 21 files changed, 316 insertions(+), 29 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{ => io}/CharacteristicType.kt (98%) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index f2d0936b90..6cbcf60436 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -12,6 +12,9 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callback import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk.LTKExchanger +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command @@ -34,16 +37,21 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context val podScanner = PodScanner(aapsLogger, bluetoothAdapter) val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - connect(podAddress) + val bleIO = connect(podAddress) + val msgIO = MessageIO(aapsLogger, bleIO) + val ltkExchanger = LTKExchanger(aapsLogger, msgIO) + val ltk = ltkExchanger.negociateLTKAndNonce() + + aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") } @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - private fun connect(podAddress: String) { + private fun connect(podAddress: String): BleIO { // TODO: locking? val podDevice = bluetoothAdapter.getRemoteDevice(podAddress) val incomingPackets: Map> = mapOf(CharacteristicType.CMD to LinkedBlockingDeque(), - CharacteristicType.DATA to LinkedBlockingDeque()); + CharacteristicType.DATA to LinkedBlockingDeque()) val bleCommCallbacks = BleCommCallbacks(aapsLogger, incomingPackets) aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to $podAddress") var autoConnect = true @@ -65,6 +73,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context aapsLogger.debug(LTag.PUMPBTCOMM, "Saying hello to the pod") bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandHello(CONTROLLER_ID).data) bleIO.readyToRead() + return bleIO } override fun sendCommand(cmd: Command): Response { @@ -84,6 +93,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context } companion object { + private const val CONNECT_TIMEOUT_MS = 5000 private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt index 997a3ee1cf..a86173507f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt @@ -4,9 +4,11 @@ import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag + import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType import java.math.BigInteger import java.util.* diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index daf3db26a4..491f26c326 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -7,8 +7,8 @@ import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothProfile import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType.Companion.byValue +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType.Companion.byValue import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWriteException import java.util.concurrent.BlockingQueue diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt index 47389b0a05..3ba0178b2e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt @@ -1,17 +1,33 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command -abstract class BleCommand { +open class BleCommand(val data: ByteArray) { - val data: ByteArray + constructor(type: BleCommandType) : this(byteArrayOf(type.value)) {} - constructor(type: BleCommandType) { - data = byteArrayOf(type.value) + constructor(type: BleCommandType, payload: ByteArray): this( + byteArrayOf(type.value) + payload + ) {} + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is BleCommand) return false + + if (!data.contentEquals(other.data)) return false + + return true } - constructor(type: BleCommandType, payload: ByteArray) { - val n = payload.size + 1 - data = ByteArray(n) - data[0] = type.value - System.arraycopy(payload, 0, data, 1, payload.size) + override fun hashCode(): Int { + return data.contentHashCode() } -} \ No newline at end of file +} + +class BleCommandRTS(): BleCommand(BleCommandType.RTS) {} + +class BleCommandCTS(): BleCommand(BleCommandType.CTS) {} + +class BleCommandAbort(): BleCommand(BleCommandType.ABORT) {} + +class BleCommandSuccess(): BleCommand(BleCommandType.SUCCESS) {} + +class BleCommandFail(): BleCommand(BleCommandType.FAIL) {} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt new file mode 100644 index 0000000000..0beabce09d --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt @@ -0,0 +1,4 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command + +class BleCommandNack { +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt index 7564ab32e1..b9987da037 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt @@ -1,5 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType class CouldNotEnableNotifications(cmd: CharacteristicType) : Exception(cmd.value) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt new file mode 100644 index 0000000000..dc7a0d7c27 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommand +import java.lang.Exception + +class UnexpectedCommandException(val cmd: BleCommand): Exception("Unexpected command: ${cmd}") { +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index 39cca93aea..c1f2c89aef 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -5,7 +5,6 @@ import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.CharacteristicType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import java.util.concurrent.BlockingQueue diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/CharacteristicType.kt similarity index 98% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/CharacteristicType.kt index c241a6f43b..b5b10e6f9a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/CharacteristicType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/CharacteristicType.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io import java.math.BigInteger import java.util.* diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt new file mode 100644 index 0000000000..a3b440d29f --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt @@ -0,0 +1,16 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket +import java.io.ByteArrayOutputStream + +class PayloadJoiner() { + private val payload = ByteArrayOutputStream() + + fun accumulate(packet: BlePacket) { + + } + + fun bytes(): ByteArray { + return ByteArray(0); + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt new file mode 100644 index 0000000000..f2eb8f3b85 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt @@ -0,0 +1,69 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.FirstBlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.LastBlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.LastOptionalPlusOneBlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.MiddleBlePacket +import java.lang.Integer.min +import java.util.zip.CRC32 + +internal class PayloadSplitter(private val payload: ByteArray) { + fun splitInPackets(): List { + val ret = ArrayList() + val crc32 = payload.crc32(); + if (payload.size <= 18) { + val end = min(14, payload.size) + ret.add(FirstBlePacket( + totalFragments = 0, + payload = payload.copyOfRange(0, end), + size = payload.size.toByte(), + crc32 = crc32, + )) + if (payload.size > 14) { + ret.add(LastOptionalPlusOneBlePacket( + index = 1, + payload = payload.copyOfRange(end, payload.size), + )) + } + return ret; + } + val middleFragments = (payload.size-18)/19 + val rest = ((payload.size - middleFragments.toInt() * 19) - 18).toByte() + ret.add(FirstBlePacket( + totalFragments = (middleFragments + 1).toByte(), + payload = payload.copyOfRange(0, 18), + )) + for( i in 1..middleFragments ) { + val p = if (i ==1 ) { + payload.copyOfRange(18,37) + }else { + payload.copyOfRange((i-1)*19+18, (i-1)*19+18+19) + } + ret.add(MiddleBlePacket( + index = i.toByte(), + payload = p, + )) + } + val end = min(14, rest.toInt()) + ret.add(LastBlePacket( + index = (middleFragments+1).toByte(), + size = rest, + payload = payload.copyOfRange(middleFragments*19+18,middleFragments*19+18+end), + crc32 = crc32, + )) + if (rest > 14) { + ret.add(LastOptionalPlusOneBlePacket( + index = (middleFragments+2).toByte(), + payload = payload.copyOfRange(middleFragments*19+18+14, payload.size), + )) + } + return ret; + } +} + +internal fun ByteArray.crc32(): Long { + val crc = CRC32() + crc.update(this) + return crc.value +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt new file mode 100644 index 0000000000..3784ae9ffa --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt @@ -0,0 +1,12 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk + +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO + +data class LTK(val ltk: ByteArray, val noncePrefix: ByteArray) { + init{ + require(ltk.size == 16) + require(noncePrefix.size == 16) + } +} + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt new file mode 100644 index 0000000000..1b0d690ae5 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk + +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Address +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.PairMessage +import info.nightscout.androidaps.utils.extensions.hexStringToByteArray + +internal class LTKExchanger(private val aapsLogger: AAPSLogger,private val msgIO: MessageIO) { + + fun negociateLTKAndNonce(): LTK? { + val msg = PairMessage( + destination = Address(byteArrayOf(1,2,3,4)), + source = Address(byteArrayOf(5,6,7,8)), + payload = "5350313d0004024200032c5350323d000bffc32dbd20030e01000016".hexStringToByteArray(), + sequenceNumber = 1, + ) + msgIO.sendMesssage(msg) + + return null + } + +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt new file mode 100644 index 0000000000..62dc6ae156 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt @@ -0,0 +1,7 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +data class Address(val address: ByteArray) { + init { + require(address.size == 4) + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt new file mode 100644 index 0000000000..c733cd42ef --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +abstract class Message( + val type: MessageType, + val source: Address, + val destination: Address, + val payload: ByteArray, + val sequenceNumber: Byte, + val ack: Boolean = false, + val ackNumber: Byte = 0.toByte(), + val eqos: Short = 0.toShort(), // TODO: understand + val priority: Boolean = false, + val lastMessage: Boolean= false, + val gateway: Boolean = false, + val sas: Boolean = false, // TODO: understand + val tfs: Boolean = false, // TODO: understand + val version: Short = 0.toShort(), + ) { + + fun asByteArray(): ByteArray { + return payload; // TODO implement + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt new file mode 100644 index 0000000000..185f3d4a7b --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -0,0 +1,43 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.BleManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandCTS +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandHello +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandRTS +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.UnexpectedCommandException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadSplitter + +class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { + fun sendMesssage(msg: Message) { + bleIO.flushIncomingQueues(); + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandRTS().data) + val expectCTS = bleIO.receivePacket(CharacteristicType.CMD) + if (BleCommand(expectCTS) != BleCommandCTS()) { + throw UnexpectedCommandException(BleCommand(expectCTS)) + } + val payload = msg.asByteArray() + val splitter = PayloadSplitter(payload) + val packets = splitter.splitInPackets() + for (packet in packets) { + bleIO.sendAndConfirmPacket(CharacteristicType.DATA, packet.asByteArray()) + } + // TODO: peek for NACKs + val expectSuccess = bleIO.receivePacket(CharacteristicType.CMD) + if (BleCommand(expectSuccess) != BleCommandCTS()) { + throw UnexpectedCommandException(BleCommand(expectSuccess)) + } + // TODO: handle NACKS/FAILS/etc + bleIO.flushIncomingQueues(); + } + + + fun receiveMessage(): Message? { + // do the RTS/CTS/data/success dance + return null + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt new file mode 100644 index 0000000000..f0a68e5cba --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt @@ -0,0 +1,14 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +enum class MessageType(val value: Byte) { + CLEAR(0), + ENCRYPTED(1), + SESSION_ESTABLISHMENT(2), + PAIRING(3); + + companion object { + fun byValue(value: Byte): MessageType = + MessageType.values().firstOrNull() {it.value == value} + ?: throw IllegalArgumentException("Unknown MessageType: $value") + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt new file mode 100644 index 0000000000..76e7802f20 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt @@ -0,0 +1,8 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +class PairMessage(source: Address, destination: Address, payload: ByteArray, sequenceNumber: Byte +) : Message( + type=MessageType.PAIRING, source, destination, payload, sequenceNumber, +) { + +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index 6e8e7de891..525ca45d88 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -1,3 +1,34 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet -class BlePacket \ No newline at end of file +sealed class BlePacket { + + abstract fun asByteArray(): ByteArray +} + +data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val size: Byte = 0, val crc32: Long? = null) : BlePacket() { + + override fun asByteArray(): ByteArray { + TODO("Not yet implemented") + } +} + +data class MiddleBlePacket(val index: Byte, val payload: ByteArray) : BlePacket() { + + override fun asByteArray(): ByteArray { + TODO("Not yet implemented") + } +} + +data class LastBlePacket(val index: Byte, val size: Byte, val payload: ByteArray, val crc32: Long) : BlePacket() { + + override fun asByteArray(): ByteArray { + TODO("Not yet implemented") + } +} + +data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray) : BlePacket() { + + override fun asByteArray(): ByteArray { + TODO("Not yet implemented") + } +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt index 64e04630a0..bae65ab044 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -1,33 +1,34 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan +import android.bluetooth.le.ScanRecord import android.bluetooth.le.ScanResult import android.os.ParcelUuid import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException -class BleDiscoveredDevice(val scanResult: ScanResult, private val podId: Long) { +class BleDiscoveredDevice(val scanResult: ScanResult, val scanRecord: ScanRecord, private val podId: Long) { private val sequenceNo: Int private val lotNo: Long @Throws(DiscoveredInvalidPodException::class) private fun validateServiceUUIDs() { - val scanRecord = scanResult.scanRecord - ?: throw DiscoveredInvalidPodException("Scan record is null"); val serviceUuids = scanRecord.serviceUuids if (serviceUuids.size != 9) { throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUuids.size, serviceUuids) + } if (extractUUID16(serviceUuids[0]) != MAIN_SERVICE_UUID) { // this is the service that we filtered for throw DiscoveredInvalidPodException("The first exposed service UUID should be 4024, got " + extractUUID16(serviceUuids[0]), serviceUuids) } // TODO understand what is serviceUUIDs[1]. 0x2470. Alarms? - if (extractUUID16(serviceUuids[2]) != "000a") { + if (extractUUID16(serviceUuids[2]) != UNKNOWN_THIRD_SERVICE_UUID) { // constant? throw DiscoveredInvalidPodException("The third exposed service UUID should be 000a, got " + serviceUuids[2], serviceUuids) } } @Throws(DiscoveredInvalidPodException::class) + private fun validatePodId() { val scanRecord = scanResult.scanRecord val serviceUUIDs = scanRecord.serviceUuids @@ -39,7 +40,6 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podId: Long) { } private fun parseLotNo(): Long { - val scanRecord = scanResult.scanRecord val serviceUUIDs = scanRecord.serviceUuids val lotSeq = extractUUID16(serviceUUIDs[5]) + extractUUID16(serviceUUIDs[6]) + @@ -48,7 +48,6 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podId: Long) { } private fun parseSeqNo(): Int { - val scanRecord = scanResult.scanRecord val serviceUUIDs = scanRecord.serviceUuids val lotSeq = extractUUID16(serviceUUIDs[7]) + extractUUID16(serviceUUIDs[8]) @@ -57,8 +56,9 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podId: Long) { override fun toString(): String { return "BleDiscoveredDevice{" + - "scanResult=" + scanResult + + "scanRecord=" + scanRecord + ", podID=" + podId + + "scanResult=" + scanResult + ", sequenceNo=" + sequenceNo + ", lotNo=" + lotNo + '}' @@ -66,6 +66,7 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val podId: Long) { companion object { const val MAIN_SERVICE_UUID = "4024"; + const val UNKNOWN_THIRD_SERVICE_UUID = "000a" // FIXME: why is this 000a? private fun extractUUID16(uuid: ParcelUuid): String { return uuid.toString().substring(4, 8) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt index 0030c755eb..95286d9423 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt @@ -33,9 +33,11 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S logger.debug(LTag.PUMPBTCOMM, "ScanCollector looking for podID: $podID") for (result in found.values) { try { - val device = BleDiscoveredDevice(result, podID) - ret.add(device) - logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + podID) + result.scanRecord?.let { + val device = BleDiscoveredDevice(result, result.scanRecord, podID) + ret.add(device) + logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + podID) + } } catch (e: DiscoveredInvalidPodException) { logger.debug(LTag.PUMPBTCOMM, "ScanCollector: pod not matching$e") // this is not the POD we are looking for From af1d505e360ecfaf0163d945fc69bf3702c6e386 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Thu, 25 Feb 2021 19:19:06 +0100 Subject: [PATCH 032/649] ble: - address review comments: renames and removed unused vars - implement serialization for BlePackets - improve logging, add .toHex() where we have []byte ``` INFO[0009] Received SP1 SP2 payload 5350313d0004024200032c5350323d000bffc32dbd20030e01000016 TRAC[0009] Read field: SP1= :: 02420003 :: 4 TRAC[0009] Read field: ,SP2= :: ffc32dbd20030e01000016 :: 11 INFO[0009] Received SP1 SP2: 02420003 :: ffc32dbd20030e01000016 ``` --- .../driver/comm/callbacks/BleCommCallbacks.kt | 11 ++--- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 4 +- .../dash/driver/comm/io/PayloadJoiner.kt | 1 - .../dash/driver/comm/io/PayloadSplitter.kt | 2 +- .../dash/driver/comm/ltk/LTKExchanger.kt | 2 +- .../dash/driver/comm/message/Message.kt | 6 +-- .../dash/driver/comm/message/MessageIO.kt | 10 ++--- .../dash/driver/comm/packet/BlePacket.kt | 40 ++++++++++++++++--- .../action/DashInitializePodViewModel.kt | 6 ++- 9 files changed, 58 insertions(+), 24 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index 491f26c326..5580ef31ca 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -11,6 +11,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.Chara import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType.Companion.byValue import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWriteException +import info.nightscout.androidaps.utils.extensions.toHex import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch import java.util.concurrent.LinkedBlockingQueue @@ -63,10 +64,10 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP private fun confirmWritePayload(expectedPayload: ByteArray, received: CharacteristicWriteConfirmationPayload) { if (!expectedPayload.contentEquals(received.payload)) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload + ".Excepted: " + expectedPayload) + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm write. Got " + received.payload.toHex() + ".Excepted: " + expectedPayload.toHex()) throw CouldNotConfirmWriteException(expectedPayload, received.payload) } - aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload) + aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed write with value: " + received.payload.toHex()) } override fun onCharacteristicWrite(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, status: Int) { @@ -77,7 +78,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP CharacteristicWriteConfirmationError(status) } aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite with status/char/value " + - status + "/" + byValue(characteristic.uuid.toString()) + "/" + characteristic.value) + status + "/" + byValue(characteristic.uuid.toString()) + "/" + characteristic.value.toHex()) try { if (writeQueue.size > 0) { aapsLogger.warn(LTag.PUMPBTCOMM, "Write confirm queue should be empty. found: " + writeQueue.size) @@ -98,7 +99,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP val characteristicType = byValue(characteristic.uuid.toString()) aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicChanged with char/value " + characteristicType + "/" + - payload) + payload.toHex()) incomingPackets[characteristicType]!!.add(payload) } @@ -120,7 +121,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP override fun onDescriptorWrite(gatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int) { super.onDescriptorWrite(gatt, descriptor, status) val writeConfirmation = if (status == BluetoothGatt.GATT_SUCCESS) { - aapsLogger.debug(LTag.PUMPBTCOMM, "OnDescriptor value " + descriptor.value) + aapsLogger.debug(LTag.PUMPBTCOMM, "OnDescriptor value " + descriptor.value.toHex()) DescriptorWriteConfirmationUUID(descriptor.uuid.toString()) } else { DescriptorWriteConfirmationError(status) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index c1f2c89aef..a763193b77 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* +import info.nightscout.androidaps.utils.extensions.toHex import java.util.concurrent.BlockingQueue import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException @@ -48,7 +49,8 @@ class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map Date: Fri, 26 Feb 2021 11:18:02 +0100 Subject: [PATCH 033/649] ble: start implementing message reading --- .../driver/comm/command/BleCommandNack.kt | 5 ++- .../dash/driver/comm/io/PayloadJoiner.kt | 21 +++++++++- .../dash/driver/comm/ltk/LTKExchanger.kt | 4 +- .../dash/driver/comm/ltk/PairMessage.kt | 3 ++ .../dash/driver/comm/message/MessageIO.kt | 42 +++++++++++++++---- .../message/{Message.kt => MessagePacket.kt} | 14 +++++-- .../dash/driver/comm/message/PairMessage.kt | 8 ---- .../dash/driver/comm/packet/BlePacket.kt | 2 +- 8 files changed, 72 insertions(+), 27 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/{Message.kt => MessagePacket.kt} (67%) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt index 0beabce09d..166ba616e4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt @@ -1,4 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command -class BleCommandNack { -} \ No newline at end of file +import java.nio.ByteBuffer + +class BleCommandNack(idx: Byte): BleCommand(BleCommandType.NACK, byteArrayOf(idx)) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt index de4aab89d3..8e00168def 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt @@ -3,13 +3,32 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket import java.io.ByteArrayOutputStream +sealed class PayloadJoinerAction + +class PayloadJoinerActionAccept(): PayloadJoinerAction() +class PayloadJoinerActionReject(val idx: Byte): PayloadJoinerAction() + class PayloadJoiner() { + var oneExtra: Boolean=false + private val payload = ByteArrayOutputStream() - fun accumulate(packet: BlePacket) { + fun start(payload: ByteArray): Int { + return 0; } + fun accumulate(payload: ByteArray): PayloadJoinerAction { + return PayloadJoinerActionAccept() + } + + fun finalize(): PayloadJoinerAction { + return PayloadJoinerActionAccept() + + } + fun bytes(): ByteArray { return ByteArray(0); } + + } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 6c2adcfb0a..34df8508e4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -3,13 +3,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Address import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.PairMessage +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket import info.nightscout.androidaps.utils.extensions.hexStringToByteArray internal class LTKExchanger(private val aapsLogger: AAPSLogger,private val msgIO: MessageIO) { fun negociateLTKAndNonce(): LTK? { - val msg = PairMessage( + val msg = MessagePacket( destination = Address(byteArrayOf(1,2,3,4)), source = Address(byteArrayOf(5,6,7,8)), payload = "545710030100038002420000fffffffe5350313d0004024200032c5350323d000bffc32dbd20030e01000016".hexStringToByteArray(), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt new file mode 100644 index 0000000000..ef6cce1221 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk + +class PairMessage diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt index de7b12a92b..73f31a7f62 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -2,18 +2,15 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommand -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandCTS -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommandRTS +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.UnexpectedCommandException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadSplitter import info.nightscout.androidaps.utils.extensions.toHex class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { - fun sendMesssage(msg: Message) { + fun sendMesssage(msg: MessagePacket) { bleIO.flushIncomingQueues() bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandRTS().data) val expectCTS = bleIO.receivePacket(CharacteristicType.CMD) @@ -36,8 +33,35 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { bleIO.flushIncomingQueues() } - fun receiveMessage(): Message? { - // do the RTS/CTS/data/success dance - return null + fun receiveMessage(): MessagePacket { + val expectRTS = bleIO.receivePacket(CharacteristicType.CMD) + if (BleCommand(expectRTS) != BleCommandCTS()) { + throw UnexpectedCommandException(BleCommand(expectRTS)) + } + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandCTS().data) + val joiner = PayloadJoiner() + var data = bleIO.receivePacket(CharacteristicType.DATA) + val fragments = joiner.start(data) + for (i in 1 until fragments) { + data = bleIO.receivePacket(CharacteristicType.DATA) + val accumlateAction = joiner.accumulate(data) + if (accumlateAction is PayloadJoinerActionReject) { + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandNack(accumlateAction.idx).data) + } + } + if (joiner.oneExtra) { + var data = bleIO.receivePacket(CharacteristicType.DATA) + val accumulateAction = joiner.accumulate(data) + if (accumulateAction is PayloadJoinerActionReject) { + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandNack(accumulateAction.idx).data) + } + } + val finalCmd = when (joiner.finalize()) { + is PayloadJoinerActionAccept -> BleCommandSuccess() + is PayloadJoinerActionReject -> BleCommandFail() + } + bleIO.sendAndConfirmPacket(CharacteristicType.CMD, finalCmd.data) + val fullPayload = joiner.bytes() + return MessagePacket.parse(fullPayload) } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt similarity index 67% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index 13849815fb..1d77e313db 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message -abstract class Message( +data class MessagePacket( val type: MessageType, val source: Address, val destination: Address, @@ -14,10 +14,16 @@ abstract class Message( val gateway: Boolean = false, val sas: Boolean = false, // TODO: understand val tfs: Boolean = false, // TODO: understand - val version: Short = 0.toShort(), -) { + val version: Short = 0.toShort()) { fun asByteArray(): ByteArray { - return payload; // TODO implement + // TODO: implement proper serialization + return this.payload + } + + companion object { + fun parse(payload: ByteArray): MessagePacket { + TODO("implement message header parsing") + } } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt deleted file mode 100644 index 76e7802f20..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PairMessage.kt +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message - -class PairMessage(source: Address, destination: Address, payload: ByteArray, sequenceNumber: Byte -) : Message( - type=MessageType.PAIRING, source, destination, payload, sequenceNumber, -) { - -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index c19fdfe52d..e517790bee 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -7,7 +7,6 @@ sealed class BlePacket { abstract fun asByteArray(): ByteArray companion object { - const val MAX_BLE_PACKET_LEN = 30 // we use this as the size allocated for the ByteBuffer } } @@ -62,3 +61,4 @@ data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray) return byteArrayOf(index) + payload } } + From 1661d978d0ae56eb624181702024538a192a0e03 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 11:47:42 +0100 Subject: [PATCH 034/649] mark not implemented yet functions --- .../dash/driver/comm/io/PayloadJoiner.kt | 23 ++++++++----------- .../dash/driver/comm/ltk/LTKExchanger.kt | 2 ++ .../driver/comm/scan/BleDiscoveredDevice.kt | 2 +- 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt index 8e00168def..d2f754e396 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt @@ -1,34 +1,31 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket import java.io.ByteArrayOutputStream sealed class PayloadJoinerAction -class PayloadJoinerActionAccept(): PayloadJoinerAction() -class PayloadJoinerActionReject(val idx: Byte): PayloadJoinerAction() +class PayloadJoinerActionAccept : PayloadJoinerAction() +class PayloadJoinerActionReject(val idx: Byte) : PayloadJoinerAction() -class PayloadJoiner() { - var oneExtra: Boolean=false +class PayloadJoiner { + + var oneExtra: Boolean = false private val payload = ByteArrayOutputStream() fun start(payload: ByteArray): Int { - return 0; + TODO("not implemented") } fun accumulate(payload: ByteArray): PayloadJoinerAction { - return PayloadJoinerActionAccept() + TODO("not implemented") } fun finalize(): PayloadJoinerAction { - return PayloadJoinerActionAccept() - + TODO("not implemented") } - + fun bytes(): ByteArray { - return ByteArray(0); + TODO("not implemented") } - - } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 34df8508e4..fd436ce86a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -4,6 +4,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Address import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageType import info.nightscout.androidaps.utils.extensions.hexStringToByteArray internal class LTKExchanger(private val aapsLogger: AAPSLogger,private val msgIO: MessageIO) { @@ -14,6 +15,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger,private val msgIO source = Address(byteArrayOf(5,6,7,8)), payload = "545710030100038002420000fffffffe5350313d0004024200032c5350323d000bffc32dbd20030e01000016".hexStringToByteArray(), sequenceNumber = 1, + type = MessageType.PAIRING, ) msgIO.sendMesssage(msg) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt index bae65ab044..88e4733eed 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -5,7 +5,7 @@ import android.bluetooth.le.ScanResult import android.os.ParcelUuid import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.DiscoveredInvalidPodException -class BleDiscoveredDevice(val scanResult: ScanResult, val scanRecord: ScanRecord, private val podId: Long) { +class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: ScanRecord, private val podId: Long) { private val sequenceNo: Int private val lotNo: Long From 4e6ad3f1132c498df3bb66c3c8e9ddab3fbc9054 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 13:23:03 +0100 Subject: [PATCH 035/649] add comments with the LTK steps --- .../pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index fd436ce86a..e5c516fec8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -10,6 +10,16 @@ import info.nightscout.androidaps.utils.extensions.hexStringToByteArray internal class LTKExchanger(private val aapsLogger: AAPSLogger,private val msgIO: MessageIO) { fun negociateLTKAndNonce(): LTK? { + // send SP1, SP2 + // send SPS1 + // read SPS1 + + // send SPS2 + // read SPS2 + + // send SP0GP0 + // read P0 + val msg = MessagePacket( destination = Address(byteArrayOf(1,2,3,4)), source = Address(byteArrayOf(5,6,7,8)), From 318c0c642cf55e5649ea28bccedb19cd01995d0f Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 16:00:20 +0100 Subject: [PATCH 036/649] WIP: sp1sp2 --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 2 +- .../dash/driver/comm/ltk/LTKExchanger.kt | 60 ++++++++++++++----- .../dash/driver/comm/ltk/PairMessage.kt | 20 ++++++- .../dash/driver/comm/message/Address.kt | 7 --- .../omnipod/dash/driver/comm/message/Id.kt | 36 +++++++++++ .../dash/driver/comm/message/Message.kt | 9 +++ .../dash/driver/comm/message/MessagePacket.kt | 41 ++++++++++++- .../message/StringLengthPrefixEncoding.kt | 17 ++++++ 8 files changed, 165 insertions(+), 27 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 6cbcf60436..00f440ac73 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -95,7 +95,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context companion object { private const val CONNECT_TIMEOUT_MS = 5000 - private const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. + public const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index e5c516fec8..0d7e255543 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -1,35 +1,65 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Address +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageType import info.nightscout.androidaps.utils.extensions.hexStringToByteArray +import info.nightscout.androidaps.utils.extensions.toHex +import java.nio.ByteBuffer -internal class LTKExchanger(private val aapsLogger: AAPSLogger,private val msgIO: MessageIO) { +internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { fun negociateLTKAndNonce(): LTK? { // send SP1, SP2 + // TODO: get this from somewhere(preferences?) + var seq: Byte = 1 + val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) + val nodeId = controllerId.increment() + + var sp1sp2 = sp1sp2(nodeId.address, sp2(), seq, controllerId, nodeId) + msgIO.sendMesssage(sp1sp2.messagePacket) +/* + var sps1 = + msgIO.sendMesssage(sps1.messagePacket) // send SPS1 // read SPS1 + val podSps1 = msgIO.receiveMessage() // send SPS2 + var sps2 = PairMessage() + msgIO.sendMesssage(sps2.messagePacket) // read SPS2 + val podSps2 = msgIO.receiveMessage() // send SP0GP0 + msgIO.sendMesssage(sps2.messagePacket) // read P0 - - val msg = MessagePacket( - destination = Address(byteArrayOf(1,2,3,4)), - source = Address(byteArrayOf(5,6,7,8)), - payload = "545710030100038002420000fffffffe5350313d0004024200032c5350323d000bffc32dbd20030e01000016".hexStringToByteArray(), - sequenceNumber = 1, - type = MessageType.PAIRING, - ) - msgIO.sendMesssage(msg) - + val p0 = msgIO.receiveMessage() +*/ return null } -} + private fun sp2(): ByteArray { + // This is GetPodStatus command, with page 0 parameter. + // We could replace that in the future with the serialized GetPodStatus() + return GET_POD_STATUS_HEX_COMMAND.hexStringToByteArray() + } + + fun sp1sp2(sp1: ByteArray, sp2: ByteArray, seq: Byte, controllerId: Id, nodeId: Id): PairMessage { + val payload = "SP1=".toByteArray() + sp1 + ",SP2=".toByteArray() + sp2 + return PairMessage( + sequenceNumber = seq, + source = controllerId, + destination = nodeId, + payload = payload, + ) + } + + companion object { + + private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt index ef6cce1221..bb88c60831 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt @@ -1,3 +1,21 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk -class PairMessage +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Id +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageType + +data class PairMessage( + val sequenceNumber: Byte, + val source: Id, + val destination: Id, + val payload: ByteArray, + val messagePacket: MessagePacket = MessagePacket( + type=MessageType.PAIRING, + source=source, + destination = destination, + encryptedPayload=false, + payload=payload, + sequenceNumber=sequenceNumber, + sas=true, // TODO: understand why this is true for PairMessages + ), +) {} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt deleted file mode 100644 index 62dc6ae156..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Address.kt +++ /dev/null @@ -1,7 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message - -data class Address(val address: ByteArray) { - init { - require(address.size == 4) - } -} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt new file mode 100644 index 0000000000..baa4964c23 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk.LTKExchanger +import info.nightscout.androidaps.utils.extensions.toHex +import java.nio.ByteBuffer + +data class Id(val address: ByteArray) { + init { + require(address.size == 4) + } + + /** + * Used to obtain podId from controllerId + */ + fun increment(): Id { + val nodeId = address.copyOf() + nodeId[3] = (nodeId[3].toInt() and -4).toByte() + nodeId[3] = (nodeId[3].toInt() or PERIPHERAL_NODE_INDEX).toByte() + return Id(nodeId) + } + + override fun toString(): String { + val asInt = ByteBuffer.wrap(address).getInt() + return "${asInt}/${address.toHex()}" + } + + companion object { + private val PERIPHERAL_NODE_INDEX = 1 // TODO: understand the meaning of this value. It comes from preferences + + fun fromInt(v: Int): Id { + return Id(ByteBuffer.allocate(4).putInt(v).array()) + } + } + +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt new file mode 100644 index 0000000000..8b157a4399 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message + +interface Message { + + /** + * + */ + fun messagePacket(): MessagePacket +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index 1d77e313db..a918a2b551 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -1,9 +1,38 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message +import java.io.DataOutput +import java.nio.ByteBuffer + +/*** + * MessagePacket contains header and raw payload for a message + */ + +class Flag:Byte{ + fun set(idx: Byte, val: Boolean) { + val mask = 1 ): List { + TODO("not implemented") + } + + fun formatKeys(keys: List, payload: List, addLength: Boolean): ByteArray { + TODO("not implemented") + } + } +} \ No newline at end of file From badf8fe24d47d24dc4d7a0d2d0b7b9fce8eeaf17 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 16:52:55 +0100 Subject: [PATCH 037/649] ble: sending the first SP1/SP2 pairing command from the fake pod logs ``` INFO[0007] Received SP1 SP2 payload 5350313d0004000010912c5350323d000bffc32dbd08030e0100008a TRAC[0007] Read field: SP1= :: 00001091 :: 4 TRAC[0007] Read field: ,SP2= :: ffc32dbd08030e0100008a :: 11 INFO[0007] Received SP1 SP2: 00001091 :: ffc32dbd08030e0100008a ``` --- .../pump/omnipod/dash/driver/comm/ltk/LTK.kt | 2 +- .../dash/driver/comm/ltk/LTKExchanger.kt | 10 +-- .../dash/driver/comm/ltk/PairMessage.kt | 1 - .../dash/driver/comm/message/MessageIO.kt | 2 +- .../dash/driver/comm/message/MessagePacket.kt | 83 ++++++++++++------- .../message/StringLengthPrefixEncoding.kt | 23 ++++- 6 files changed, 83 insertions(+), 38 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt index 3784ae9ffa..1f83940f2e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt @@ -4,7 +4,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO data class LTK(val ltk: ByteArray, val noncePrefix: ByteArray) { - init{ + init { require(ltk.size == 16) require(noncePrefix.size == 16) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 0d7e255543..526d9cfc42 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -1,13 +1,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding import info.nightscout.androidaps.utils.extensions.hexStringToByteArray -import info.nightscout.androidaps.utils.extensions.toHex -import java.nio.ByteBuffer internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { @@ -48,8 +46,10 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI } fun sp1sp2(sp1: ByteArray, sp2: ByteArray, seq: Byte, controllerId: Id, nodeId: Id): PairMessage { - val payload = "SP1=".toByteArray() + sp1 - ",SP2=".toByteArray() + sp2 + val payload = StringLengthPrefixEncoding.formatKeys( + arrayOf("SP1=", ",SP2="), + arrayOf(sp1, sp2), + ) return PairMessage( sequenceNumber = seq, source = controllerId, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt index bb88c60831..99466e3b4e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt @@ -13,7 +13,6 @@ data class PairMessage( type=MessageType.PAIRING, source=source, destination = destination, - encryptedPayload=false, payload=payload, sequenceNumber=sequenceNumber, sas=true, // TODO: understand why this is true for PairMessages diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt index 73f31a7f62..d64d693edc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -26,7 +26,7 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { } // TODO: peek for NACKs val expectSuccess = bleIO.receivePacket(CharacteristicType.CMD) - if (BleCommand(expectSuccess) != BleCommandCTS()) { + if (BleCommand(expectSuccess) != BleCommandSuccess()) { throw UnexpectedCommandException(BleCommand(expectSuccess)) } // TODO: handle NACKS/FAILS/etc diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index a918a2b551..f18cbc9369 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -1,34 +1,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message -import java.io.DataOutput import java.nio.ByteBuffer /*** * MessagePacket contains header and raw payload for a message */ - -class Flag:Byte{ - fun set(idx: Byte, val: Boolean) { - val mask = 1 ): List { TODO("not implemented") } - fun formatKeys(keys: List, payload: List, addLength: Boolean): ByteArray { - TODO("not implemented") + fun formatKeys(keys: Array, payloads: Array): ByteArray { + val payloadTotalSize = payloads.fold(0) { acc, i -> acc + i.size } + val keyTotalSize = keys.fold(0) { acc, i -> acc + i.length } + + val bb = ByteBuffer.allocate(2 * keys.size + keyTotalSize + payloadTotalSize) + for (idx in keys.indices) { + val k = keys[idx] + val payload = payloads[idx] + bb.put(k.toByteArray()) + bb.putShort(payload.size.toShort()) + bb.put(payload) + } + + val ret = ByteArray(bb.position()) + bb.flip() + bb.get(ret) + + return ret } } } \ No newline at end of file From 4664d21ddffb385c3450920ac69084b2c0763987 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 17:00:36 +0100 Subject: [PATCH 038/649] format, cleanups --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 2 +- .../dash/driver/comm/ServiceDiscoverer.kt | 4 +-- .../pump/omnipod/dash/driver/comm/ltk/LTK.kt | 4 --- .../dash/driver/comm/ltk/PairMessage.kt | 12 +++---- .../dash/driver/comm/message/Message.kt | 9 ----- .../dash/driver/comm/message/MessageIO.kt | 9 +++-- .../dash/driver/comm/message/MessagePacket.kt | 2 +- .../dash/driver/comm/message/MessageType.kt | 3 +- .../comm/{io => message}/PayloadJoiner.kt | 0 .../comm/{io => message}/PayloadSplitter.kt | 33 ++++++++++--------- .../dash/driver/comm/packet/BlePacket.kt | 1 + .../driver/comm/scan/BleDiscoveredDevice.kt | 4 ++- 12 files changed, 39 insertions(+), 44 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{io => message}/PayloadJoiner.kt (100%) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{io => message}/PayloadSplitter.kt (71%) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 00f440ac73..243cb0f59b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -95,7 +95,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context companion object { private const val CONNECT_TIMEOUT_MS = 5000 - public const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. + const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt index a86173507f..8ebde34478 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt @@ -30,17 +30,17 @@ class ServiceDiscoverer(private val logger: AAPSLogger, private val gatt: Blueto val dataChar = service.getCharacteristic(CharacteristicType.DATA.uuid) // TODO: this is never used ?: throw CharacteristicNotFoundException(CharacteristicType.DATA.value) var chars = mapOf(CharacteristicType.CMD to cmdChar, - CharacteristicType.DATA to dataChar) + CharacteristicType.DATA to dataChar) return chars } - private fun String.toUuid(): UUID = UUID( BigInteger(replace("-", "").substring(0, 16), 16).toLong(), BigInteger(replace("-", "").substring(16), 16).toLong() ) companion object { + private const val SERVICE_UUID = "1a7e-4024-e3ed-4464-8b7e-751e03d0dc5f" private const val DISCOVER_SERVICES_TIMEOUT_MS = 5000 } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt index 1f83940f2e..407d00a289 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt @@ -1,12 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO - data class LTK(val ltk: ByteArray, val noncePrefix: ByteArray) { init { require(ltk.size == 16) require(noncePrefix.size == 16) } } - diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt index 99466e3b4e..1879626479 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt @@ -10,11 +10,11 @@ data class PairMessage( val destination: Id, val payload: ByteArray, val messagePacket: MessagePacket = MessagePacket( - type=MessageType.PAIRING, - source=source, + type = MessageType.PAIRING, + source = source, destination = destination, - payload=payload, - sequenceNumber=sequenceNumber, - sas=true, // TODO: understand why this is true for PairMessages + payload = payload, + sequenceNumber = sequenceNumber, + sas = true, // TODO: understand why this is true for PairMessages ), -) {} \ No newline at end of file +) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt deleted file mode 100644 index 8b157a4399..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Message.kt +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message - -interface Message { - - /** - * - */ - fun messagePacket(): MessagePacket -} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt index d64d693edc..7f742a4aca 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -4,8 +4,11 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.UnexpectedCommandException -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.* -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadSplitter +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadJoiner +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadJoinerActionAccept +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadJoinerActionReject import info.nightscout.androidaps.utils.extensions.toHex class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { @@ -57,7 +60,7 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { } } val finalCmd = when (joiner.finalize()) { - is PayloadJoinerActionAccept -> BleCommandSuccess() + is PayloadJoinerActionAccept -> BleCommandSuccess() is PayloadJoinerActionReject -> BleCommandFail() } bleIO.sendAndConfirmPacket(CharacteristicType.CMD, finalCmd.data) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index f18cbc9369..125219b866 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -75,7 +75,7 @@ data class MessagePacket( } } -private class Flag(var value: Int=0) { +private class Flag(var value: Int = 0) { fun set(idx: Byte, set: Boolean) { val mask = 1 shl (7 - idx) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt index f0a68e5cba..6d4ce0314f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageType.kt @@ -7,8 +7,9 @@ enum class MessageType(val value: Byte) { PAIRING(3); companion object { + fun byValue(value: Byte): MessageType = - MessageType.values().firstOrNull() {it.value == value} + MessageType.values().firstOrNull { it.value == value } ?: throw IllegalArgumentException("Unknown MessageType: $value") } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt similarity index 100% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadJoiner.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt similarity index 71% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt index 4257011fa5..8a5be5bafb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/PayloadSplitter.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.FirstBlePacket @@ -9,16 +9,17 @@ import java.lang.Integer.min import java.util.zip.CRC32 internal class PayloadSplitter(private val payload: ByteArray) { + fun splitInPackets(): List { val ret = ArrayList() - val crc32 = payload.crc32(); + val crc32 = payload.crc32() if (payload.size <= 18) { val end = min(14, payload.size) ret.add(FirstBlePacket( totalFragments = 0, - payload = payload.copyOfRange(0, end), + payload = payload.copyOfRange(0, end), size = payload.size.toByte(), - crc32 = crc32, + crc32 = crc32, )) if (payload.size > 14) { ret.add(LastOptionalPlusOneBlePacket( @@ -26,19 +27,19 @@ internal class PayloadSplitter(private val payload: ByteArray) { payload = payload.copyOfRange(end, payload.size), )) } - return ret; + return ret } - val middleFragments = (payload.size-18)/19 + val middleFragments = (payload.size - 18) / 19 val rest = ((payload.size - middleFragments.toInt() * 19) - 18).toByte() ret.add(FirstBlePacket( totalFragments = (middleFragments + 1).toByte(), payload = payload.copyOfRange(0, 18), )) - for( i in 1..middleFragments ) { - val p = if (i ==1 ) { - payload.copyOfRange(18,37) - }else { - payload.copyOfRange((i-1)*19+18, (i-1)*19+18+19) + for (i in 1..middleFragments) { + val p = if (i == 1) { + payload.copyOfRange(18, 37) + } else { + payload.copyOfRange((i - 1) * 19 + 18, (i - 1) * 19 + 18 + 19) } ret.add(MiddleBlePacket( index = i.toByte(), @@ -47,18 +48,18 @@ internal class PayloadSplitter(private val payload: ByteArray) { } val end = min(14, rest.toInt()) ret.add(LastBlePacket( - index = (middleFragments+1).toByte(), + index = (middleFragments + 1).toByte(), size = rest, - payload = payload.copyOfRange(middleFragments*19+18,middleFragments*19+18+end), + payload = payload.copyOfRange(middleFragments * 19 + 18, middleFragments * 19 + 18 + end), crc32 = crc32, )) if (rest > 14) { ret.add(LastOptionalPlusOneBlePacket( - index = (middleFragments+2).toByte(), - payload = payload.copyOfRange(middleFragments*19+18+14, payload.size), + index = (middleFragments + 2).toByte(), + payload = payload.copyOfRange(middleFragments * 19 + 18 + 14, payload.size), )) } - return ret; + return ret } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index e517790bee..0c3fda1b8c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -7,6 +7,7 @@ sealed class BlePacket { abstract fun asByteArray(): ByteArray companion object { + const val MAX_BLE_PACKET_LEN = 30 // we use this as the size allocated for the ByteBuffer } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt index 88e4733eed..1b4a2cee2a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -9,6 +9,7 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: Sc private val sequenceNo: Int private val lotNo: Long + @Throws(DiscoveredInvalidPodException::class) private fun validateServiceUUIDs() { val serviceUuids = scanRecord.serviceUuids @@ -65,7 +66,8 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: Sc } companion object { - const val MAIN_SERVICE_UUID = "4024"; + + const val MAIN_SERVICE_UUID = "4024" const val UNKNOWN_THIRD_SERVICE_UUID = "000a" // FIXME: why is this 000a? private fun extractUUID16(uuid: ParcelUuid): String { return uuid.toString().substring(4, 8) From 9170cc6f76723d6013d7c0a4b9f1e6093ec44e09 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 17:06:03 +0100 Subject: [PATCH 039/649] move the test code to "connect" this is wrong, for now I just need an easy way to test the initial handshake --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 26 +++++++++---------- .../action/DashInitializePodViewModel.kt | 2 +- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 243cb0f59b..3d39ce0b0f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -31,19 +31,6 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context private val bluetoothManager: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter - @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - fun activateNewPod() { - aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") - val podScanner = PodScanner(aapsLogger, bluetoothAdapter) - val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address - // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - val bleIO = connect(podAddress) - val msgIO = MessageIO(aapsLogger, bleIO) - val ltkExchanger = LTKExchanger(aapsLogger, msgIO) - val ltk = ltkExchanger.negociateLTKAndNonce() - - aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") - } @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) private fun connect(podAddress: String): BleIO { @@ -84,8 +71,19 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context TODO("not implemented") } + @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) override fun connect() { - TODO("not implemented") + // TODO: this is wrong and I know it + aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") + val podScanner = PodScanner(aapsLogger, bluetoothAdapter) + val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address + // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; + val bleIO = connect(podAddress) + val msgIO = MessageIO(aapsLogger, bleIO) + val ltkExchanger = LTKExchanger(aapsLogger, msgIO) + val ltk = ltkExchanger.negociateLTKAndNonce() + + aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") } override fun disconnect() { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index 692a75df06..44ae7232a5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -26,7 +26,7 @@ class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAP // TODO FIRST STEP OF ACTIVATION AsyncTask.execute { try { - bleManager.activateNewPod() + bleManager.connect() } catch (e: Exception) { aapsLogger.error(LTag.PUMP, "TEST ACTIVATE Exception" + e.toString() + ExceptionUtils.getStackTrace(e)) From dbff1c6e50e5245331c7e62653a08a60a8057b5a Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 17:38:45 +0100 Subject: [PATCH 040/649] Add Profile to BasalProgram mapper function, add some preliminary code in OmnipodDashManagerImpl --- .../dash/driver/OmnipodDashManagerImpl.kt | 33 ++++- .../driver/pod/definition/BasalProgram.kt | 41 +++++- .../action/DashInitializePodViewModel.kt | 17 ++- .../pump/omnipod/dash/util/Functions.kt | 63 ++++++++++ .../pump/omnipod/dash/util/FunctionsTest.kt | 118 ++++++++++++++++++ 5 files changed, 260 insertions(+), 12 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt create mode 100644 omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 0385a74619..335ee0f372 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -3,6 +3,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEventType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand.Companion.DEFAULT_UNIQUE_ID +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram @@ -19,9 +23,36 @@ class OmnipodDashManagerImpl @Inject constructor( private val bleManager: OmnipodDashBleManager ) : OmnipodDashManager { + private val observePodReadyForActivationPart1: Observable + get() { + if (podStateManager.activationProgress.isBefore(ActivationProgress.PHASE_1_COMPLETED)) { + return Observable.empty() + } + return Observable.error(IllegalStateException("Pod is in an incorrect state")) + } + + private val observeConnectToPod: Observable = Observable.defer { + // TODO + // send CONNECTING event here + bleManager.connect() + Observable.just(PodEvent(PodEventType.CONNECTED, null)) + } + override fun activatePodPart1(): Observable { // TODO - return Observable.empty() + return Observable.concat( + observePodReadyForActivationPart1, + observeConnectToPod, + Observable.defer { + bleManager.sendCommand(GetVersionCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(DEFAULT_UNIQUE_ID) // + .build() + ) + Observable.just(PodEvent(PodEventType.COMMAND_SENT, null)) + } + // ... Send more commands + ) } override fun activatePodPart2(): Observable { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt index 998e599805..45bbc93b3d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt @@ -19,7 +19,11 @@ class BasalProgram( fun rateAt(date: Date): Double = 0.0 // TODO - class Segment(val startSlotIndex: Short, val endSlotIndex: Short, val basalRateInHundredthUnitsPerHour: Int) { + class Segment( + val startSlotIndex: Short, + val endSlotIndex: Short, + val basalRateInHundredthUnitsPerHour: Int + ) { fun getPulsesPerHour(): Short { return (basalRateInHundredthUnitsPerHour * PULSES_PER_UNIT / 100).toShort() @@ -37,6 +41,26 @@ class BasalProgram( '}' } + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as Segment + + if (startSlotIndex != other.startSlotIndex) return false + if (endSlotIndex != other.endSlotIndex) return false + if (basalRateInHundredthUnitsPerHour != other.basalRateInHundredthUnitsPerHour) return false + + return true + } + + override fun hashCode(): Int { + var result: Int = startSlotIndex.toInt() + result = 31 * result + endSlotIndex + result = 31 * result + basalRateInHundredthUnitsPerHour + return result + } + companion object { private const val PULSES_PER_UNIT: Byte = 20 @@ -48,4 +72,19 @@ class BasalProgram( "segments=" + segments + '}' } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as BasalProgram + + if (segments != other.segments) return false + + return true + } + + override fun hashCode(): Int { + return segments.hashCode() + } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index 396d56d009..94e9db497d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action -import android.os.AsyncTask import androidx.annotation.StringRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult @@ -8,12 +7,12 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager import javax.inject.Inject class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger, private val injector: HasAndroidInjector, - private val bleManager: OmnipodDashBleManager) : InitializePodViewModel() { + private val omnipodManager: OmnipodDashManager) : InitializePodViewModel() { override fun isPodInAlarm(): Boolean = false // TODO @@ -23,13 +22,11 @@ class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAP override fun doExecuteAction(): PumpEnactResult { // TODO FIRST STEP OF ACTIVATION - AsyncTask.execute { - try { - bleManager.activateNewPod() - } catch (e: Exception) { - aapsLogger.error(LTag.PUMP, "TEST ACTIVATE Exception" + e.toString()) - } - } + val disposable = omnipodManager.activatePodPart1().subscribe( + { podEvent -> aapsLogger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") }, + { throwable -> aapsLogger.error(LTag.PUMP, "Error in Pod activation part 1: $throwable") }, + { aapsLogger.debug("Pod activation part 1 completed") } + ) return PumpEnactResult(injector).success(false).comment("not implemented") } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt new file mode 100644 index 0000000000..96d8fbf667 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt @@ -0,0 +1,63 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.util + +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import java.util.* +import kotlin.math.roundToInt + +fun mapProfileToBasalProgram(profile: Profile): BasalProgram { + val basalValues = profile.basalValues + ?: throw IllegalArgumentException("Basal values can not be null") + if (basalValues.isEmpty()) { + throw IllegalArgumentException("Basal values should contain values") + } + + val entries: MutableList = ArrayList() + + var previousBasalValue: Profile.ProfileValue? = null + + for (basalValue in basalValues) { + if (basalValue.timeAsSeconds >= 86_400) { + throw IllegalArgumentException("Basal segment start time can not be greater than 86400") + } + if (basalValue.timeAsSeconds < 0) { + throw IllegalArgumentException("Basal segment start time can not be less than 0") + } + if (basalValue.timeAsSeconds % 1_800 != 0) { + throw IllegalArgumentException("Basal segment time should be dividable by 30 minutes") + } + + val startSlotIndex = (basalValue.timeAsSeconds / 1800).toShort() + + if (previousBasalValue != null) { + entries.add( + BasalProgram.Segment( + (previousBasalValue!!.timeAsSeconds / 1800).toShort(), + startSlotIndex, + (PumpType.Omnipod_Dash.determineCorrectBasalSize(previousBasalValue.value) * 100).roundToInt() + ) + ) + } + + if (entries.size == 0 && basalValue.timeAsSeconds != 0) { + throw java.lang.IllegalArgumentException("First basal segment start time should be 0") + } + + if (entries.size > 0 && entries[entries.size - 1].endSlotIndex != startSlotIndex) { + throw IllegalArgumentException("Illegal start time for basal segment: does not match previous previous segment's end time") + } + + previousBasalValue = basalValue + } + + entries.add( + BasalProgram.Segment( + (previousBasalValue!!.timeAsSeconds / 1800).toShort(), + 48, + (PumpType.Omnipod_Dash.determineCorrectBasalSize(previousBasalValue.value) * 100).roundToInt() + ) + ) + + return BasalProgram(entries) +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt new file mode 100644 index 0000000000..a046e21e17 --- /dev/null +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt @@ -0,0 +1,118 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.util + +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.Profile.ProfileValue +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import org.junit.rules.ExpectedException +import org.mockito.Mockito +import org.powermock.api.mockito.PowerMockito + +class FunctionsTest { + + @Rule + @JvmField var thrown = ExpectedException.none() + + @Test fun validProfile() { + val profile = Mockito.mock(Profile::class.java) + val value1 = Mockito.mock(ProfileValue::class.java) + value1.timeAsSeconds = 0 + value1.value = 0.5 + val value2 = Mockito.mock(ProfileValue::class.java) + value2.timeAsSeconds = 18000 + value2.value = 1.0 + val value3 = Mockito.mock(ProfileValue::class.java) + value3.timeAsSeconds = 50400 + value3.value = 3.05 + PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( + value1, + value2, + value3 + )) + val basalProgram: BasalProgram = mapProfileToBasalProgram(profile) + val entries: List = basalProgram.segments + assertEquals(3, entries.size) + val entry1: BasalProgram.Segment = entries[0] + assertEquals(0.toShort(), entry1.startSlotIndex) + assertEquals(50, entry1.basalRateInHundredthUnitsPerHour) + assertEquals(10.toShort(), entry1.endSlotIndex) + val entry2: BasalProgram.Segment = entries[1] + assertEquals(10.toShort(), entry2.startSlotIndex) + assertEquals(100, entry2.basalRateInHundredthUnitsPerHour) + assertEquals(28.toShort(), entry2.endSlotIndex) + val entry3: BasalProgram.Segment = entries[2] + assertEquals(28.toShort(), entry3.startSlotIndex) + assertEquals(305, entry3.basalRateInHundredthUnitsPerHour) + assertEquals(48.toShort(), entry3.endSlotIndex) + } + + @Test fun invalidProfileNullEntries() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage("Basal values can not be null") + mapProfileToBasalProgram(Mockito.mock(Profile::class.java)) + } + + @Test fun invalidProfileZeroEntries() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage("Basal values should contain values") + val profile = Mockito.mock(Profile::class.java) + PowerMockito.`when`(profile.basalValues).thenReturn(arrayOfNulls(0)) + mapProfileToBasalProgram(profile) + } + + @Test fun invalidProfileNonZeroOffset() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage("First basal segment start time should be 0") + val profile = Mockito.mock(Profile::class.java) + val value = Mockito.mock(ProfileValue::class.java) + value.timeAsSeconds = 1800 + value.value = 0.5 + PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( + value)) + mapProfileToBasalProgram(profile) + } + + @Test fun invalidProfileMoreThan24Hours() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage("Basal segment start time can not be greater than 86400") + + val profile = Mockito.mock(Profile::class.java) + val value1 = Mockito.mock(ProfileValue::class.java) + value1.timeAsSeconds = 0 + value1.value = 0.5 + val value2 = Mockito.mock(ProfileValue::class.java) + value2.timeAsSeconds = 86400 + value2.value = 0.5 + PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( + value1, + value2 + )) + mapProfileToBasalProgram(profile) + } + + @Test fun invalidProfileNegativeOffset() { + thrown.expect(IllegalArgumentException::class.java) + thrown.expectMessage("Basal segment start time can not be less than 0") + val profile = Mockito.mock(Profile::class.java) + val value = Mockito.mock(ProfileValue::class.java) + value.timeAsSeconds = -1 + value.value = 0.5 + PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( + value)) + mapProfileToBasalProgram(profile) + } + + @Test fun roundsToSupportedPrecision() { + val profile = Mockito.mock(Profile::class.java) + val value = Mockito.mock(ProfileValue::class.java) + value.timeAsSeconds = 0 + value.value = 0.04 + PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( + value)) + val basalProgram: BasalProgram = mapProfileToBasalProgram(profile) + val basalProgramElement: BasalProgram.Segment = basalProgram.segments[0] + assertEquals(5, basalProgramElement.basalRateInHundredthUnitsPerHour) + } +} \ No newline at end of file From 358748654e02771122a6467ed422b59b11887f7e Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 18:30:59 +0100 Subject: [PATCH 041/649] ble: reformat(Ctrl+Alt+L) --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 1 - .../driver/comm/callbacks/BleCommCallbacks.kt | 5 +++-- .../callbacks/DescriptorWriteConfirmation.kt | 4 ++-- .../dash/driver/comm/command/BleCommand.kt | 16 ++++++++-------- .../dash/driver/comm/command/BleCommandNack.kt | 4 +--- .../CouldNotConfirmDescriptorWriteException.kt | 4 ++-- .../exceptions/CouldNotConfirmWriteException.kt | 4 ++-- .../exceptions/DiscoveredInvalidPodException.kt | 6 +++--- .../comm/exceptions/FailedToConnectException.kt | 4 ++-- .../driver/comm/exceptions/ScanFailException.kt | 4 ++-- .../exceptions/UnexpectedCommandException.kt | 4 +--- .../omnipod/dash/driver/comm/ltk/PairMessage.kt | 2 +- .../pump/omnipod/dash/driver/comm/message/Id.kt | 5 ++--- 13 files changed, 29 insertions(+), 34 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 3d39ce0b0f..b46a990e47 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -31,7 +31,6 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context private val bluetoothManager: BluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter - @Throws(FailedToConnectException::class, CouldNotSendBleException::class, InterruptedException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) private fun connect(podAddress: String): BleIO { // TODO: locking? diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index 5580ef31ca..b921f34254 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -7,10 +7,10 @@ import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothProfile import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType.Companion.byValue import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmDescriptorWriteException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotConfirmWriteException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType.Companion.byValue import info.nightscout.androidaps.utils.extensions.toHex import java.util.concurrent.BlockingQueue import java.util.concurrent.CountDownLatch @@ -141,6 +141,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP } companion object { + private const val WRITE_CONFIRM_TIMEOUT_MS = 10 // the confirmation queue should be empty anyway } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt index 3c7b4f4f9f..fbbb5b7f1b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt @@ -2,6 +2,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbac sealed class DescriptorWriteConfirmation -data class DescriptorWriteConfirmationUUID(val uuid: String): DescriptorWriteConfirmation() +data class DescriptorWriteConfirmationUUID(val uuid: String) : DescriptorWriteConfirmation() -data class DescriptorWriteConfirmationError(val status: Int): DescriptorWriteConfirmation() \ No newline at end of file +data class DescriptorWriteConfirmationError(val status: Int) : DescriptorWriteConfirmation() \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt index 3ba0178b2e..a51e738df4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt @@ -2,11 +2,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command open class BleCommand(val data: ByteArray) { - constructor(type: BleCommandType) : this(byteArrayOf(type.value)) {} + constructor(type: BleCommandType) : this(byteArrayOf(type.value)) - constructor(type: BleCommandType, payload: ByteArray): this( + constructor(type: BleCommandType, payload: ByteArray) : this( byteArrayOf(type.value) + payload - ) {} + ) override fun equals(other: Any?): Boolean { if (this === other) return true @@ -22,12 +22,12 @@ open class BleCommand(val data: ByteArray) { } } -class BleCommandRTS(): BleCommand(BleCommandType.RTS) {} +class BleCommandRTS : BleCommand(BleCommandType.RTS) -class BleCommandCTS(): BleCommand(BleCommandType.CTS) {} +class BleCommandCTS : BleCommand(BleCommandType.CTS) -class BleCommandAbort(): BleCommand(BleCommandType.ABORT) {} +class BleCommandAbort : BleCommand(BleCommandType.ABORT) -class BleCommandSuccess(): BleCommand(BleCommandType.SUCCESS) {} +class BleCommandSuccess : BleCommand(BleCommandType.SUCCESS) -class BleCommandFail(): BleCommand(BleCommandType.FAIL) {} +class BleCommandFail : BleCommand(BleCommandType.FAIL) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt index 166ba616e4..14e0705c2b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandNack.kt @@ -1,5 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command -import java.nio.ByteBuffer - -class BleCommandNack(idx: Byte): BleCommand(BleCommandType.NACK, byteArrayOf(idx)) +class BleCommandNack(idx: Byte) : BleCommand(BleCommandType.NACK, byteArrayOf(idx)) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt index 2bc86e92a7..75c9f82344 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions class CouldNotConfirmDescriptorWriteException(override val message: String?) : Exception(message) { - constructor(sent: String, confirmed: String): this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") - constructor(status: Int): this("Could not confirm write. Write status: ${status}") + constructor(sent: String, confirmed: String) : this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") + constructor(status: Int) : this("Could not confirm write. Write status: ${status}") } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt index a3c15bfb05..9217668e77 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions class CouldNotConfirmWriteException(override val message: String?) : Exception(message) { - constructor(sent: ByteArray, confirmed: ByteArray): this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") - constructor(status: Int): this("Could not confirm write. Write status: ${status}") + constructor(sent: ByteArray, confirmed: ByteArray) : this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") + constructor(status: Int) : this("Could not confirm write. Write status: ${status}") } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt index f7f6b08630..a4f7b52f75 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import android.os.ParcelUuid -class DiscoveredInvalidPodException: Exception { - constructor(message: String) : super(message) {} - constructor(message: String, serviceUUIds: List) : super("$message service UUIDs: $serviceUUIds"){} +class DiscoveredInvalidPodException : Exception { + constructor(message: String) : super(message) + constructor(message: String, serviceUUIds: List) : super("$message service UUIDs: $serviceUUIds") } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt index c720724ceb..8d6782aadb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions open class FailedToConnectException : Exception { - constructor() : super() {} - constructor(message: String?) : super(message) {} + constructor() : super() + constructor(message: String?) : super(message) } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt index 6c6dcc2f49..ccaaf5a758 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions open class ScanFailException : Exception { - constructor() {} - constructor(errorCode: Int) : super("errorCode$errorCode") {} + constructor() + constructor(errorCode: Int) : super("errorCode$errorCode") } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt index dc7a0d7c27..149909032d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommand -import java.lang.Exception -class UnexpectedCommandException(val cmd: BleCommand): Exception("Unexpected command: ${cmd}") { -} \ No newline at end of file +class UnexpectedCommandException(val cmd: BleCommand) : Exception("Unexpected command: ${cmd}") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt index 1879626479..1e170fc5f1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt @@ -15,6 +15,6 @@ data class PairMessage( destination = destination, payload = payload, sequenceNumber = sequenceNumber, - sas = true, // TODO: understand why this is true for PairMessages + sas = true // TODO: understand why this is true for PairMessages ), ) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt index baa4964c23..ae8c732661 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk.LTKExchanger import info.nightscout.androidaps.utils.extensions.toHex import java.nio.ByteBuffer @@ -21,11 +19,12 @@ data class Id(val address: ByteArray) { } override fun toString(): String { - val asInt = ByteBuffer.wrap(address).getInt() + val asInt = ByteBuffer.wrap(address).int return "${asInt}/${address.toHex()}" } companion object { + private val PERIPHERAL_NODE_INDEX = 1 // TODO: understand the meaning of this value. It comes from preferences fun fromInt(v: Int): Id { From fb7a84bdf78565463ff9b34aa9b81a8caf822b54 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 19:10:11 +0100 Subject: [PATCH 042/649] ble: add meaninful constants in the PayloadSplitter and getPodId --- .../dash/driver/comm/{message => }/Id.kt | 4 +++- .../dash/driver/comm/OmnipodDashBleManager.kt | 2 ++ .../driver/comm/OmnipodDashBleManagerImpl.kt | 6 +++++ .../dash/driver/comm/ltk/LTKExchanger.kt | 3 ++- .../dash/driver/comm/ltk/PairMessage.kt | 2 +- .../dash/driver/comm/message/MessagePacket.kt | 1 + .../driver/comm/message/PayloadSplitter.kt | 22 +++++++++---------- .../dash/driver/comm/packet/BlePacket.kt | 22 +++++++++++++++---- 8 files changed, 44 insertions(+), 18 deletions(-) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{message => }/Id.kt (88%) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt similarity index 88% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt index ae8c732661..866c65b922 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/Id.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm import info.nightscout.androidaps.utils.extensions.toHex import java.nio.ByteBuffer @@ -10,6 +10,8 @@ data class Id(val address: ByteArray) { /** * Used to obtain podId from controllerId + * The original PDM seems to rotate over 3 Ids: + * controllerID+1, controllerID+2 and controllerID+3 */ fun increment(): Id { val nodeId = address.copyOf() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index e673818629..ef445e8563 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -13,4 +13,6 @@ interface OmnipodDashBleManager { fun connect() fun disconnect() + + fun getPodId(): Id } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index b46a990e47..1f88eb69cb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -89,6 +89,12 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context TODO("not implemented") } + + override fun getPodId(): Id { + // TODO: return something meaningful here + return Id.fromInt(4243); + } + companion object { private const val CONNECT_TIMEOUT_MS = 5000 diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 526d9cfc42..cd4cdb1540 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Id +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding import info.nightscout.androidaps.utils.extensions.hexStringToByteArray @@ -18,6 +18,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI var sp1sp2 = sp1sp2(nodeId.address, sp2(), seq, controllerId, nodeId) msgIO.sendMesssage(sp1sp2.messagePacket) + /* var sps1 = msgIO.sendMesssage(sps1.messagePacket) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt index 1e170fc5f1..af7fea3adb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.Id +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageType diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index 125219b866..d9cd686b4c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import java.nio.ByteBuffer /*** diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt index 8a5be5bafb..d74032e6fe 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt @@ -13,15 +13,15 @@ internal class PayloadSplitter(private val payload: ByteArray) { fun splitInPackets(): List { val ret = ArrayList() val crc32 = payload.crc32() - if (payload.size <= 18) { - val end = min(14, payload.size) + if (payload.size <= FirstBlePacket.CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET) { + val end = min(FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS, payload.size) ret.add(FirstBlePacket( totalFragments = 0, payload = payload.copyOfRange(0, end), size = payload.size.toByte(), crc32 = crc32, )) - if (payload.size > 14) { + if (payload.size > FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS) { ret.add(LastOptionalPlusOneBlePacket( index = 1, payload = payload.copyOfRange(end, payload.size), @@ -29,34 +29,34 @@ internal class PayloadSplitter(private val payload: ByteArray) { } return ret } - val middleFragments = (payload.size - 18) / 19 - val rest = ((payload.size - middleFragments.toInt() * 19) - 18).toByte() + val middleFragments = (payload.size - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS) / MiddleBlePacket.CAPACITY + val rest = ((payload.size - middleFragments * MiddleBlePacket.CAPACITY) - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS).toByte() ret.add(FirstBlePacket( totalFragments = (middleFragments + 1).toByte(), - payload = payload.copyOfRange(0, 18), + payload = payload.copyOfRange(0, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS), )) for (i in 1..middleFragments) { val p = if (i == 1) { - payload.copyOfRange(18, 37) + payload.copyOfRange(FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + MiddleBlePacket.CAPACITY) } else { - payload.copyOfRange((i - 1) * 19 + 18, (i - 1) * 19 + 18 + 19) + payload.copyOfRange(FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + (i - 1) * MiddleBlePacket.CAPACITY, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + i * MiddleBlePacket.CAPACITY) } ret.add(MiddleBlePacket( index = i.toByte(), payload = p, )) } - val end = min(14, rest.toInt()) + val end = min(LastBlePacket.CAPACITY, rest.toInt()) ret.add(LastBlePacket( index = (middleFragments + 1).toByte(), size = rest, - payload = payload.copyOfRange(middleFragments * 19 + 18, middleFragments * 19 + 18 + end), + payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + end), crc32 = crc32, )) if (rest > 14) { ret.add(LastOptionalPlusOneBlePacket( index = (middleFragments + 2).toByte(), - payload = payload.copyOfRange(middleFragments * 19 + 18 + 14, payload.size), + payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + LastBlePacket.CAPACITY, payload.size), )) } return ret diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index 0c3fda1b8c..b9bd30a252 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -7,8 +7,8 @@ sealed class BlePacket { abstract fun asByteArray(): ByteArray companion object { - - const val MAX_BLE_PACKET_LEN = 30 // we use this as the size allocated for the ByteBuffer + const val MAX_BLE_PACKET_LEN = 20 + const val MAX_BLE_BUFFER_LEN = MAX_BLE_PACKET_LEN + 1 // we use this as the size allocated for the ByteBuffer } } @@ -16,7 +16,7 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val override fun asByteArray(): ByteArray { val bb = ByteBuffer - .allocate(MAX_BLE_PACKET_LEN) + .allocate(MAX_BLE_BUFFER_LEN) .put(0) // index .put(totalFragments) // # of fragments except FirstBlePacket and LastOptionalPlusOneBlePacket crc32?.let { @@ -31,6 +31,12 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val bb.get(ret) return ret } + + companion object { + internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = 13 // we are using all fields + internal const val CAPACITY_WITH_MIDDLE_PACKETS = 18 // we are not using crc32 or size + internal const val CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET = 18 + } } data class MiddleBlePacket(val index: Byte, val payload: ByteArray) : BlePacket() { @@ -38,13 +44,17 @@ data class MiddleBlePacket(val index: Byte, val payload: ByteArray) : BlePacket( override fun asByteArray(): ByteArray { return byteArrayOf(index) + payload } + + companion object { + internal const val CAPACITY = 19 + } } data class LastBlePacket(val index: Byte, val size: Byte, val payload: ByteArray, val crc32: Long) : BlePacket() { override fun asByteArray(): ByteArray { val bb = ByteBuffer - .allocate(MAX_BLE_PACKET_LEN) + .allocate(MAX_BLE_BUFFER_LEN) .put(index) .put(size) .putInt(crc32.toInt()) @@ -54,6 +64,10 @@ data class LastBlePacket(val index: Byte, val size: Byte, val payload: ByteArray bb.get(ret) return ret } + + companion object { + internal const val CAPACITY = 14 + } } data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray) : BlePacket() { From ae30387a25ee175ce60d8273d9d0893ad55499c8 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Fri, 26 Feb 2021 21:45:17 +0100 Subject: [PATCH 043/649] cleanups --- .../driver/comm/callbacks/BleCommCallbacks.kt | 4 +- .../driver/pod/command/DeactivateCommand.kt | 2 +- .../driver/pod/command/GetStatusCommand.kt | 2 +- .../driver/pod/command/GetVersionCommand.kt | 2 +- .../pod/command/ProgramAlertsCommand.kt | 2 +- .../driver/pod/command/ProgramBasalCommand.kt | 2 +- .../driver/pod/command/ProgramBeepsCommand.kt | 2 +- .../driver/pod/command/ProgramBolusCommand.kt | 2 +- .../pod/command/ProgramInsulinCommand.kt | 4 +- .../pod/command/ProgramTempBasalCommand.kt | 17 +- .../driver/pod/command/SetUniqueIdCommand.kt | 2 +- .../pod/command/SilenceAlertsCommand.kt | 2 +- .../driver/pod/command/StopDeliveryCommand.kt | 4 +- .../driver/pod/command/base/CommandType.kt | 4 +- .../builder/HeaderEnabledCommandBuilder.kt | 1 + .../builder/NonceEnabledCommandBuilder.kt | 1 + .../insulin/program/util/ProgramBasalUtil.kt | 4 +- .../program/util/ProgramTempBasalUtil.kt | 2 +- .../dash/driver/pod/definition/AlarmType.kt | 17 +- .../pod/definition/AlertConfiguration.kt | 2 +- .../dash/driver/pod/definition/AlertSlot.kt | 18 +- .../driver/pod/definition/DeliveryStatus.kt | 18 +- .../driver/pod/definition/NakErrorType.kt | 18 +- .../dash/driver/pod/definition/PodStatus.kt | 18 +- .../pod/response/AlarmStatusResponse.kt | 248 ++++-------------- .../pod/response/DefaultStatusResponse.kt | 106 ++------ .../dash/driver/pod/response/NakResponse.kt | 65 ++--- .../dash/driver/pod/response/ResponseType.kt | 53 +--- .../pod/response/SetUniqueIdResponse.kt | 3 +- .../driver/pod/response/VersionResponse.kt | 3 +- .../state/OmnipodDashPodStateManagerImpl.kt | 16 +- .../omnipod/dash/driver/pod/util/HasValue.kt | 10 + .../dash/driver/pod/util/MessageUtil.kt | 4 +- .../pod/response/AlarmStatusResponseTest.kt | 58 ++-- .../pod/response/DefaultStatusResponseTest.kt | 32 +-- .../driver/pod/response/NakResponseTest.kt | 10 +- 36 files changed, 223 insertions(+), 535 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index daf3db26a4..1dac78a389 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -109,7 +109,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP when (confirmed) { is DescriptorWriteConfirmationError -> throw CouldNotConfirmWriteException(confirmed.status) is DescriptorWriteConfirmationUUID -> if (confirmed.uuid != descriptorUUID) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got ${confirmed.uuid}. Expected: ${descriptorUUID}") + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got ${confirmed.uuid}. Expected: $descriptorUUID") throw CouldNotConfirmDescriptorWriteException(descriptorUUID, confirmed.uuid) } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed descriptor write : " + confirmed.uuid) @@ -127,7 +127,7 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP } try { if (descriptorWriteQueue.size > 0) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Descriptor write queue should be empty, found: " + descriptorWriteQueue.size) + aapsLogger.warn(LTag.PUMPBTCOMM, "Descriptor write queue should be empty, found: ${descriptorWriteQueue.size}") descriptorWriteQueue.clear() } val offered = descriptorWriteQueue.offer(writeConfirmation, WRITE_CONFIRM_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt index 8ae51e845a..ec122495bc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder import java.nio.ByteBuffer -class DeactivateCommand internal constructor( +class DeactivateCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt index c08b251cb4..ac9228125a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType import java.nio.ByteBuffer -class GetStatusCommand( +class GetStatusCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt index 3300bde757..a06a3624e6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.HeaderEnabledCommandBuilder import java.nio.ByteBuffer -class GetVersionCommand internal constructor( +class GetVersionCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt index 594dd1f57c..3ba15675f8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import java.nio.ByteBuffer import java.util.* -class ProgramAlertsCommand internal constructor( +class ProgramAlertsCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt index af656989d8..3495f94566 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -12,7 +12,7 @@ import java.nio.ByteBuffer import java.util.* // Always preceded by 0x1a ProgramInsulinCommand -class ProgramBasalCommand internal constructor( +class ProgramBasalCommand private constructor( private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt index f000270bd5..d9412e7363 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ProgramReminder import java.nio.ByteBuffer -class ProgramBeepsCommand internal constructor( +class ProgramBeepsCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt index dd0db15ee6..79d57534a0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.Mess import java.nio.ByteBuffer // NOT SUPPORTED: extended bolus -class ProgramBolusCommand internal constructor( +class ProgramBolusCommand private constructor( private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt index c3b98f69fc..eb41e68bda 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt @@ -7,7 +7,7 @@ import java.nio.ByteBuffer import java.util.* // Always followed by one of: 0x13, 0x16, 0x17 -class ProgramInsulinCommand( +class ProgramInsulinCommand internal constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, @@ -37,7 +37,7 @@ class ProgramInsulinCommand( fun calculateChecksum(bytes: ByteArray): Short { var sum: Short = 0 for (b in bytes) { - sum = ((b.toInt() and 0xff) + sum).toShort() // TODO Adrian: int conversion ok? + sum = ((b.toInt() and 0xff) + sum).toShort() } return sum } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt index 350136a661..37c4597ae9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -11,7 +11,7 @@ import java.nio.ByteBuffer import java.util.* // NOT SUPPORTED: percentage temp basal -class ProgramTempBasalCommand protected constructor( +class ProgramTempBasalCommand private constructor( private val interlockCommand: ProgramInsulinCommand, uniqueId: Int, sequenceNumber: Short, @@ -20,10 +20,11 @@ class ProgramTempBasalCommand protected constructor( insulinProgramElements: List ) : HeaderEnabledCommand(CommandType.PROGRAM_TEMP_BASAL, uniqueId, sequenceNumber, multiCommandFlag) { - private val insulinProgramElements: List - fun getBodyLength(): Byte = (insulinProgramElements.size * 6 + 8).toByte() + private val insulinProgramElements: List = ArrayList(insulinProgramElements) - fun getLength(): Short = (getBodyLength() + 2).toShort() + private fun getBodyLength(): Byte = (insulinProgramElements.size * 6 + 8).toByte() + + private fun getLength(): Short = (getBodyLength() + 2).toShort() class Builder : NonceEnabledCommandBuilder() { @@ -56,16 +57,12 @@ class ProgramTempBasalCommand protected constructor( val shortInsulinProgramElements = ProgramTempBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) val insulinProgramElements = ProgramTempBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, shortInsulinProgramElements, - ProgramTempBasalUtil.calculateChecksum(durationInSlots, pulsesPerSlot!![0], pulsesPerSlot), durationInSlots, + ProgramTempBasalUtil.calculateChecksum(durationInSlots, pulsesPerSlot[0], pulsesPerSlot), durationInSlots, 0x3840.toShort(), pulsesPerSlot[0], ProgramInsulinCommand.DeliveryType.TEMP_BASAL) return ProgramTempBasalCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, programReminder!!, insulinProgramElements) } } - init { - this.insulinProgramElements = ArrayList(insulinProgramElements) - } - override val encoded: ByteArray get() { val firstProgramElement = insulinProgramElements[0] @@ -90,7 +87,7 @@ class ProgramTempBasalCommand protected constructor( } val tempBasalCommand = buffer.array() val interlockCommand = interlockCommand.encoded - val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand!!.size).toShort(), multiCommandFlag) + val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand.size).toShort(), multiCommandFlag) return appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) // .put(header) // .put(interlockCommand) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt index 6deb03a6ae..83c0fbc6f4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b import java.nio.ByteBuffer import java.util.* -class SetUniqueIdCommand internal constructor( +class SetUniqueIdCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index 5db1c248cc..d9c32e8f7a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import java.nio.ByteBuffer import java.util.* -class SilenceAlertsCommand internal constructor( +class SilenceAlertsCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt index b74a85dd02..e941909a66 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import java.nio.ByteBuffer import java.util.* -class StopDeliveryCommand internal constructor( +class StopDeliveryCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, @@ -24,7 +24,7 @@ class StopDeliveryCommand internal constructor( .put(commandType.value) // .put(BODY_LENGTH) // .putInt(nonce) // - .put((beepType.value.toInt() shl 4 or deliveryType.encoded[0].toInt()).toByte()) // TODO bitstuff + .put((beepType.value.toInt() shl 4 or deliveryType.encoded[0].toInt()).toByte()) // .array()) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt index 57bd0962c8..1cc50ff135 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt @@ -1,8 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base -enum class CommandType( - val value: Byte -) { +enum class CommandType(val value: Byte) { SET_UNIQUE_ID(0x03.toByte()), GET_VERSION(0x07.toByte()), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt index 21969aa5f5..27dcf630e4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +@Suppress("UNCHECKED_CAST") abstract class HeaderEnabledCommandBuilder, R : Command> : CommandBuilder { protected var uniqueId: Int? = null diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt index 64bd7eb4e6..04ee98a2d3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +@Suppress("UNCHECKED_CAST") abstract class NonceEnabledCommandBuilder, R : Command> : HeaderEnabledCommandBuilder() { protected var nonce: Int? = null diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt index d16dc83b27..93b144787f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt @@ -17,10 +17,10 @@ object ProgramBasalUtil { private const val MAX_NUMBER_OF_SLOTS_IN_INSULIN_PROGRAM_ELEMENT: Byte = 16 fun mapTenthPulsesPerSlotToLongInsulinProgramElements( - tenthPulsesPerSlot: ShortArray?, + tenthPulsesPerSlot: ShortArray, insulinProgramElementFactory: (Byte, Byte, Short) -> BasalInsulinProgramElement = ::BasalInsulinProgramElement ): List { - require(tenthPulsesPerSlot!!.size <= NUMBER_OF_BASAL_SLOTS) { "Basal program must contain at most 48 slots" } + require(tenthPulsesPerSlot.size <= NUMBER_OF_BASAL_SLOTS) { "Basal program must contain at most 48 slots" } val elements: MutableList = ArrayList() var previousTenthPulsesPerSlot: Short = 0 var numberOfSlotsInCurrentElement: Byte = 0 diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt index 29652e3e97..8c66abc626 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt @@ -9,7 +9,7 @@ import kotlin.math.roundToInt object ProgramTempBasalUtil { - fun mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot: ShortArray?): List { + fun mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot: ShortArray): List { return ProgramBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) { startSlotIndex: Byte, numberOfSlots: Byte, totalTenthPulses: Short -> TempBasalInsulinProgramElement(startSlotIndex, numberOfSlots, totalTenthPulses) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt index 795ddd19f1..90f794a3cb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class AlarmType( - private val value: Byte -) { +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue + +enum class AlarmType(override val value: Byte) : HasValue { NONE(0x00.toByte()), ALARM_PW_FLASH_ERASE(0x01.toByte()), @@ -160,15 +160,4 @@ enum class AlarmType( ALARM_BLE_QN_CRIT_VAR_FAIL(0xc2.toByte()), UNKNOWN(0xff.toByte()); - companion object { - - fun byValue(value: Byte): AlarmType { - for (type in values()) { - if (type.value == value) { - return type - } - } - return UNKNOWN - } - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt index 039433c2a0..9b1b3a8d4c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt @@ -26,7 +26,7 @@ class AlertConfiguration( if (autoOff) { firstByte = firstByte or (1 shl 1) } - firstByte = firstByte or ((durationInMinutes.toInt() shr 8 and 0x01).toByte()) //Todo bitstuff + firstByte = firstByte or ((durationInMinutes.toInt() shr 8 and 0x01).toByte()) return ByteBuffer.allocate(6) // .put(firstByte) .put(durationInMinutes.toByte()) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt index f38a24d154..3735e550cd 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class AlertSlot( - val value: Byte -) { +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue + +enum class AlertSlot(override val value: Byte) : HasValue { AUTO_OFF(0x00.toByte()), MULTI_COMMAND(0x01.toByte()), @@ -13,16 +13,4 @@ enum class AlertSlot( SUSPEND_ENDED(0x06.toByte()), EXPIRATION(0x07.toByte()), UNKNOWN(0xff.toByte()); - - companion object { - - fun byValue(value: Byte): AlertSlot { - for (slot in values()) { - if (slot.value == value) { - return slot - } - } - return UNKNOWN - } - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt index 08915f7f7e..daaedab7db 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class DeliveryStatus( - private val value: Byte -) { +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue + +enum class DeliveryStatus(override val value: Byte) : HasValue { SUSPENDED(0x00.toByte()), BASAL_ACTIVE(0x01.toByte()), @@ -11,16 +11,4 @@ enum class DeliveryStatus( BOLUS_AND_BASAL_ACTIVE(0x05.toByte()), BOLUS_AND_TEMP_BASAL_ACTIVE(0x06.toByte()), UNKNOWN(0xff.toByte()); - - companion object { - - fun byValue(value: Byte): DeliveryStatus { - for (status in values()) { - if (status.value == value) { - return status - } - } - return UNKNOWN - } - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt index 81bbc53c7c..e3f110e565 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class NakErrorType( - private val value: Byte -) { +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue + +enum class NakErrorType(override val value: Byte) : HasValue { FLASH_WRITE(0x01.toByte()), FLASH_ERASE(0x02.toByte()), @@ -34,16 +34,4 @@ enum class NakErrorType( IGNORE_COMMAND(0x1c.toByte()), INVALID_CRC(0x1d.toByte()), UNKNOWN(0xff.toByte()); - - companion object { - - fun byValue(value: Byte): NakErrorType { - for (type in values()) { - if (type.value == value) { - return type - } - } - return UNKNOWN - } - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt index cdb6ce9be1..b5d0dadacf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class PodStatus( - private val value: Byte -) { +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue + +enum class PodStatus(override val value: Byte) : HasValue { UNINITIALIZED(0x00.toByte()), MFG_TEST(0x01.toByte()), @@ -22,17 +22,5 @@ enum class PodStatus( DEACTIVATED(0x0f.toByte()), UNKNOWN(0xff.toByte()); - companion object { - - fun byValue(value: Byte): PodStatus { - for (status in values()) { - if (status.value == value) { - return status - } - } - return UNKNOWN - } - } - fun isRunning(): Boolean = this == RUNNING_ABOVE_MIN_VOLUME || this == RUNNING_BELOW_MIN_VOLUME } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index 736213161a..df22e3a23a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -4,163 +4,68 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.StatusResponseType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import java.nio.ByteBuffer -import java.util.* import kotlin.experimental.and class AlarmStatusResponse( encoded: ByteArray ) : AdditionalStatusResponseBase(StatusResponseType.ALARM_STATUS, encoded) { - private val messageType: Byte - private val messageLength: Short - private val additionalStatusResponseType: Byte - private val podStatus: PodStatus - private val deliveryStatus: DeliveryStatus - private val bolusPulsesRemaining: Short - private val sequenceNumberOfLastProgrammingCommand: Short - private val totalPulsesDelivered: Short - private val alarmType: AlarmType - private val alarmTime: Short - private val reservoirPulsesRemaining: Short - private val minutesSinceActivation: Short - private val alert0Active: Boolean - private val alert1Active: Boolean - private val alert2Active: Boolean - private val alert3Active: Boolean - private val alert4Active: Boolean - private val alert5Active: Boolean - private val alert6Active: Boolean - private val alert7Active: Boolean - private val occlusionAlarm: Boolean - private val pulseInfoInvalid: Boolean - private val podStatusWhenAlarmOccurred: PodStatus - private val immediateBolusWhenAlarmOccurred: Boolean - private val occlusionType: Byte - private val occurredWhenFetchingImmediateBolusActiveInformation: Boolean - private val rssi: Short - private val receiverLowerGain: Short - private val podStatusWhenAlarmOccurred2: PodStatus - private val returnAddressOfPodAlarmHandlerCaller: Short + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val additionalStatusResponseType: Byte = encoded[2] + val podStatus: PodStatus = byValue((encoded[3] and 0x0f), PodStatus.UNKNOWN) + val deliveryStatus: DeliveryStatus = byValue((encoded[4] and 0x0f), DeliveryStatus.UNKNOWN) + val bolusPulsesRemaining: Short = (ByteBuffer.wrap(byteArrayOf(encoded[5], encoded[6])).short and 2047) + val sequenceNumberOfLastProgrammingCommand: Short = (encoded[7] and 0x0f).toShort() + val totalPulsesDelivered: Short = ByteBuffer.wrap(byteArrayOf(encoded[8], encoded[9])).short + val alarmType: AlarmType = byValue(encoded[10], AlarmType.UNKNOWN) + val alarmTime: Short = ByteBuffer.wrap(byteArrayOf(encoded[11], encoded[12])).short + val reservoirPulsesRemaining: Short = ByteBuffer.wrap(byteArrayOf(encoded[13], encoded[14])).short + val minutesSinceActivation: Short = ByteBuffer.wrap(byteArrayOf(encoded[15], encoded[16])).short + val alert0Active: Boolean + val alert1Active: Boolean + val alert2Active: Boolean + val alert3Active: Boolean + val alert4Active: Boolean + val alert5Active: Boolean + val alert6Active: Boolean + val alert7Active: Boolean + val occlusionAlarm: Boolean + val pulseInfoInvalid: Boolean + val podStatusWhenAlarmOccurred: PodStatus + val immediateBolusWhenAlarmOccurred: Boolean + val occlusionType: Byte + val occurredWhenFetchingImmediateBolusActiveInformation: Boolean + val rssi: Short + val receiverLowerGain: Short + val podStatusWhenAlarmOccurred2: PodStatus + val returnAddressOfPodAlarmHandlerCaller: Short - fun getMessageType(): Byte { - return messageType - } - - fun getMessageLength(): Short { - return messageLength - } - - fun getAdditionalStatusResponseType(): Byte { - return additionalStatusResponseType - } - - fun getPodStatus(): PodStatus { - return podStatus - } - - fun getDeliveryStatus(): DeliveryStatus { - return deliveryStatus - } - - fun getBolusPulsesRemaining(): Short { - return bolusPulsesRemaining - } - - fun getSequenceNumberOfLastProgrammingCommand(): Short { - return sequenceNumberOfLastProgrammingCommand - } - - fun getTotalPulsesDelivered(): Short { - return totalPulsesDelivered - } - - fun getAlarmType(): AlarmType { - return alarmType - } - - fun getAlarmTime(): Short { - return alarmTime - } - - fun getReservoirPulsesRemaining(): Short { - return reservoirPulsesRemaining - } - - fun getMinutesSinceActivation(): Short { - return minutesSinceActivation - } - - fun isAlert0Active(): Boolean { - return alert0Active - } - - fun isAlert1Active(): Boolean { - return alert1Active - } - - fun isAlert2Active(): Boolean { - return alert2Active - } - - fun isAlert3Active(): Boolean { - return alert3Active - } - - fun isAlert4Active(): Boolean { - return alert4Active - } - - fun isAlert5Active(): Boolean { - return alert5Active - } - - fun isAlert6Active(): Boolean { - return alert6Active - } - - fun isAlert7Active(): Boolean { - return alert7Active - } - - fun isOcclusionAlarm(): Boolean { - return occlusionAlarm - } - - fun isPulseInfoInvalid(): Boolean { - return pulseInfoInvalid - } - - fun getPodStatusWhenAlarmOccurred(): PodStatus { - return podStatusWhenAlarmOccurred - } - - fun isImmediateBolusWhenAlarmOccurred(): Boolean { - return immediateBolusWhenAlarmOccurred - } - - fun getOcclusionType(): Byte { - return occlusionType - } - - fun isOccurredWhenFetchingImmediateBolusActiveInformation(): Boolean { - return occurredWhenFetchingImmediateBolusActiveInformation - } - - fun getRssi(): Short { - return rssi - } - - fun getReceiverLowerGain(): Short { - return receiverLowerGain - } - - fun getPodStatusWhenAlarmOccurred2(): PodStatus { - return podStatusWhenAlarmOccurred2 - } - - fun getReturnAddressOfPodAlarmHandlerCaller(): Short { - return returnAddressOfPodAlarmHandlerCaller + init { + val activeAlerts = encoded[17].toInt() + alert0Active = activeAlerts and 1 == 1 + alert1Active = activeAlerts ushr 1 and 1 == 1 + alert2Active = activeAlerts ushr 2 and 1 == 1 + alert3Active = activeAlerts ushr 3 and 1 == 1 + alert4Active = activeAlerts ushr 4 and 1 == 1 + alert5Active = activeAlerts ushr 5 and 1 == 1 + alert6Active = activeAlerts ushr 6 and 1 == 1 + alert7Active = activeAlerts ushr 7 and 1 == 1 + val alarmFlags = encoded[18] + occlusionAlarm = (alarmFlags.toInt() and 1) == 1 + pulseInfoInvalid = alarmFlags shr 1 and 1 == 1 + val byte19 = encoded[19] + val byte20 = encoded[20] + podStatusWhenAlarmOccurred = byValue((byte19 and 0x0f), PodStatus.UNKNOWN) + immediateBolusWhenAlarmOccurred = byte19 shr 4 and 1 == 1 + occlusionType = ((byte19 shr 5 and 3).toByte()) + occurredWhenFetchingImmediateBolusActiveInformation = byte19 shr 7 and 1 == 1 + rssi = (byte20 and 0x3f).toShort() + receiverLowerGain = ((byte20 shr 6 and 0x03).toShort()) + podStatusWhenAlarmOccurred2 = byValue((encoded[21] and 0x0f), PodStatus.UNKNOWN) + returnAddressOfPodAlarmHandlerCaller = ByteBuffer.wrap(byteArrayOf(encoded[22], encoded[23])).short } override fun toString(): String { @@ -197,52 +102,11 @@ class AlarmStatusResponse( ", returnAddressOfPodAlarmHandlerCaller=" + returnAddressOfPodAlarmHandlerCaller + ", statusResponseType=" + statusResponseType + ", responseType=" + responseType + - ", encoded=" + Arrays.toString(encoded) + + ", encoded=" + encoded.contentToString() + '}' } - init { - messageType = encoded[0] - messageLength = (encoded[1].toInt() and 0xff).toShort() - additionalStatusResponseType = encoded[2] - podStatus = PodStatus.byValue((encoded[3] and 0x0f)) - deliveryStatus = DeliveryStatus.byValue((encoded[4] and 0x0f)) - bolusPulsesRemaining = (ByteBuffer.wrap(byteArrayOf(encoded[5], encoded[6])).short and 2047) - sequenceNumberOfLastProgrammingCommand = (encoded[7] and 0x0f).toShort() - totalPulsesDelivered = ByteBuffer.wrap(byteArrayOf(encoded[8], encoded[9])).short - alarmType = AlarmType.byValue(encoded[10]) - alarmTime = ByteBuffer.wrap(byteArrayOf(encoded[11], encoded[12])).short - reservoirPulsesRemaining = ByteBuffer.wrap(byteArrayOf(encoded[13], encoded[14])).short - minutesSinceActivation = ByteBuffer.wrap(byteArrayOf(encoded[15], encoded[16])).short - val activeAlerts = encoded[17].toInt() // TODO: toInt()? - alert0Active = activeAlerts and 1 == 1 - alert1Active = activeAlerts ushr 1 and 1 == 1 - alert2Active = activeAlerts ushr 2 and 1 == 1 - alert3Active = activeAlerts ushr 3 and 1 == 1 - alert4Active = activeAlerts ushr 4 and 1 == 1 - alert5Active = activeAlerts ushr 5 and 1 == 1 - alert6Active = activeAlerts ushr 6 and 1 == 1 - alert7Active = activeAlerts ushr 7 and 1 == 1 - val alarmFlags = encoded[18] - occlusionAlarm = (alarmFlags.toInt() and 1) == 1 - pulseInfoInvalid = alarmFlags shr 1 and 1 == 1 - val byte19 = encoded[19] - val byte20 = encoded[20] - podStatusWhenAlarmOccurred = PodStatus.byValue((byte19 and 0x0f)) - immediateBolusWhenAlarmOccurred = byte19 shr 4 and 1 == 1 - occlusionType = ((byte19 shr 5 and 3).toByte()) - occurredWhenFetchingImmediateBolusActiveInformation = byte19 shr 7 and 1 == 1 - rssi = (byte20 and 0x3f).toShort() - receiverLowerGain = ((byte20 shr 6 and 0x03).toShort()) - podStatusWhenAlarmOccurred2 = PodStatus.byValue((encoded[21] and 0x0f)) - returnAddressOfPodAlarmHandlerCaller = ByteBuffer.wrap(byteArrayOf(encoded[22], encoded[23])).short - } - - //TODO autoconvert to Int ok? - private infix fun Byte.ushr(i: Int) = toInt() ushr i - private infix fun Short.shr(i: Int): Int = toInt() shr i - private infix fun Byte.shl(i: Int): Int = toInt() shl i - private infix fun Byte.shr(i: Int): Int = toInt() shr i + infix fun Byte.shr(i: Int): Int = toInt() shr i } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt index 7e83e64ccf..cfe5a0af70 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt @@ -2,93 +2,30 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import kotlin.experimental.and class DefaultStatusResponse( encoded: ByteArray ) : ResponseBase(ResponseType.DEFAULT_STATUS_RESPONSE, encoded) { - // TODO: Here is a lot of bitshifting that had to be changed. we should go over it. - private val messageType: Byte = encoded[0] - private val deliveryStatus: DeliveryStatus = DeliveryStatus.byValue((encoded[1].toInt() shr 4 and 0x0f).toByte()) - private val podStatus: PodStatus = PodStatus.byValue((encoded[1] and 0x0f) as Byte) - private val totalPulsesDelivered: Short = ((encoded[2] and 0x0f shl 12 or (encoded[3].toInt() and 0xff shl 1) or (encoded[4].toInt() and 0xff ushr 7)).toShort()) - private val sequenceNumberOfLastProgrammingCommand: Short = (encoded[4] ushr 3 and 0x0f).toShort() - private val bolusPulsesRemaining: Short = ((encoded[4] and 0x07 shl 10 or (encoded[5].toInt() and 0xff) and 2047).toShort()) - private val activeAlerts = (encoded[6].toInt() and 0xff shl 1 or (encoded[7] ushr 7)).toShort() - private val occlusionAlertActive: Boolean = (activeAlerts and 1).toInt() == 1 - private val alert1Active: Boolean = activeAlerts shr 1 and 1 == 1 - private val alert2Active: Boolean = activeAlerts shr 2 and 1 == 1 - private val alert3Active: Boolean = activeAlerts shr 3 and 1 == 1 - private val alert4Active: Boolean = activeAlerts shr 4 and 1 == 1 - private val alert5Active: Boolean = activeAlerts shr 5 and 1 == 1 - private val alert6Active: Boolean = activeAlerts shr 6 and 1 == 1 - private val alert7Active: Boolean = activeAlerts shr 7 and 1 == 1 - private val minutesSinceActivation: Short = (encoded[7] and 0x7f shl 6 or (encoded[8].toInt() and 0xff ushr 2 and 0x3f)).toShort() - private val reservoirPulsesRemaining: Short = (encoded[8] shl 8 or encoded[9].toInt() and 0x3ff).toShort() - fun getMessageType(): Byte { - return messageType - } - - fun getDeliveryStatus(): DeliveryStatus { - return deliveryStatus - } - - fun getPodStatus(): PodStatus { - return podStatus - } - - fun getTotalPulsesDelivered(): Short { - return totalPulsesDelivered - } - - fun getSequenceNumberOfLastProgrammingCommand(): Short { - return sequenceNumberOfLastProgrammingCommand - } - - fun getBolusPulsesRemaining(): Short { - return bolusPulsesRemaining - } - - fun isOcclusionAlertActive(): Boolean { - return occlusionAlertActive - } - - fun isAlert1Active(): Boolean { - return alert1Active - } - - fun isAlert2Active(): Boolean { - return alert2Active - } - - fun isAlert3Active(): Boolean { - return alert3Active - } - - fun isAlert4Active(): Boolean { - return alert4Active - } - - fun isAlert5Active(): Boolean { - return alert5Active - } - - fun isAlert6Active(): Boolean { - return alert6Active - } - - fun isAlert7Active(): Boolean { - return alert7Active - } - - fun getMinutesSinceActivation(): Short { - return minutesSinceActivation - } - - fun getReservoirPulsesRemaining(): Short { - return reservoirPulsesRemaining - } + val messageType: Byte = encoded[0] + val deliveryStatus: DeliveryStatus = byValue((encoded[1].toInt() shr 4 and 0x0f).toByte(), DeliveryStatus.UNKNOWN) + val podStatus: PodStatus = byValue((encoded[1] and 0x0f), PodStatus.UNKNOWN) + val totalPulsesDelivered: Short = ((encoded[2] and 0x0f shl 12 or (encoded[3].toInt() and 0xff shl 1) or (encoded[4].toInt() and 0xff ushr 7)).toShort()) + val sequenceNumberOfLastProgrammingCommand: Short = (encoded[4] ushr 3 and 0x0f).toShort() + val bolusPulsesRemaining: Short = ((encoded[4] and 0x07 shl 10 or (encoded[5].toInt() and 0xff) and 2047).toShort()) + val activeAlerts = (encoded[6].toInt() and 0xff shl 1 or (encoded[7] ushr 7)).toShort() + val occlusionAlertActive: Boolean = (activeAlerts and 1).toInt() == 1 + val alert1Active: Boolean = activeAlerts shr 1 and 1 == 1 + val alert2Active: Boolean = activeAlerts shr 2 and 1 == 1 + val alert3Active: Boolean = activeAlerts shr 3 and 1 == 1 + val alert4Active: Boolean = activeAlerts shr 4 and 1 == 1 + val alert5Active: Boolean = activeAlerts shr 5 and 1 == 1 + val alert6Active: Boolean = activeAlerts shr 6 and 1 == 1 + val alert7Active: Boolean = activeAlerts shr 7 and 1 == 1 + val minutesSinceActivation: Short = (encoded[7] and 0x7f shl 6 or (encoded[8].toInt() and 0xff ushr 2 and 0x3f)).toShort() + val reservoirPulsesRemaining: Short = (encoded[8] shl 8 or encoded[9].toInt() and 0x3ff).toShort() override fun toString(): String { return "DefaultStatusResponse{" + @@ -114,7 +51,6 @@ class DefaultStatusResponse( } } -//TODO autoconvert to Int ok? -private infix fun Byte.ushr(i: Int) = toInt() ushr i -private infix fun Short.shr(i: Int): Int = toInt() shr i -private infix fun Byte.shl(i: Int): Int = toInt() shl i +infix fun Byte.ushr(i: Int) = toInt() ushr i +infix fun Short.shr(i: Int): Int = toInt() shr i +infix fun Byte.shl(i: Int): Int = toInt() shl i diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt index a2090d5e58..0cde181a8d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt @@ -3,39 +3,35 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue class NakResponse( encoded: ByteArray ) : ResponseBase(ResponseType.NAK_RESPONSE, encoded) { - private val messageType: Byte // TODO directly assign here - private val messageLength: Short - private val nakErrorType: NakErrorType - private var alarmType: AlarmType? = null - private var podStatus: PodStatus? = null - private var securityNakSyncCount: Short = 0 - fun getMessageType(): Byte { - return messageType - } + val messageType: Byte = encoded[0] + val messageLength: Short = encoded[1].toShort() + val nakErrorType: NakErrorType = byValue(encoded[2], NakErrorType.UNKNOWN) + var alarmType: AlarmType? = null + private set + var podStatus: PodStatus? = null + private set - fun getMessageLength(): Short { - return messageLength - } + var securityNakSyncCount: Short = 0 + private set - fun getNakErrorType(): NakErrorType { // TODO make public, a val cannot be reassigned, same for other Responses - return nakErrorType - } - - fun getAlarmType(): AlarmType? { - return alarmType - } - - fun getPodStatus(): PodStatus? { - return podStatus - } - - fun getSecurityNakSyncCount(): Short { - return securityNakSyncCount + init { + val byte3 = encoded[3] + val byte4 = encoded[4] + if (nakErrorType == NakErrorType.ILLEGAL_SECURITY_CODE) { + securityNakSyncCount = ((byte3.toInt() shl 8 or byte4.toInt()).toShort()) + alarmType = null + podStatus = null + } else { + securityNakSyncCount = 0 + alarmType = byValue(byte3, AlarmType.UNKNOWN) + podStatus = byValue(byte4, PodStatus.UNKNOWN) + } } override fun toString(): String { @@ -50,21 +46,4 @@ class NakResponse( ", encoded=" + encoded.contentToString() + '}' } - - init { - messageType = encoded[0] - messageLength = encoded[1].toShort() - nakErrorType = NakErrorType.byValue(encoded[2]) - val byte3 = encoded[3] - val byte4 = encoded[4] - if (nakErrorType == NakErrorType.ILLEGAL_SECURITY_CODE) { - securityNakSyncCount = ((byte3.toInt() shl 8 or byte4.toInt()).toShort()) // TODO: toInt() - alarmType = null - podStatus = null - } else { - securityNakSyncCount = 0 - alarmType = AlarmType.byValue(byte3) - podStatus = PodStatus.byValue(byte4) - } - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt index ad08b4b3ec..10d355f380 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response -enum class ResponseType( - val value: Byte -) { +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue + +enum class ResponseType(override val value: Byte) : HasValue { ACTIVATION_RESPONSE(0x01.toByte()), DEFAULT_STATUS_RESPONSE(0x1d.toByte()), @@ -10,9 +10,7 @@ enum class ResponseType( NAK_RESPONSE(0x06.toByte()), UNKNOWN(0xff.toByte()); - enum class StatusResponseType( - val value: Byte - ) { + enum class StatusResponseType(override val value: Byte) : HasValue { DEFAULT_STATUS_RESPONSE(0x00.toByte()), STATUS_RESPONSE_PAGE_1(0x01.toByte()), @@ -24,53 +22,12 @@ enum class ResponseType( STATUS_RESPONSE_PAGE_80(0x50.toByte()), STATUS_RESPONSE_PAGE_81(0x51.toByte()), UNKNOWN(0xff.toByte()); - - companion object { - - @JvmStatic - fun byValue(value: Byte): StatusResponseType { - for (type in values()) { - if (type.value == value) { - return type - } - } - return UNKNOWN - } - } } - enum class ActivationResponseType( - val length: Byte - ) { + enum class ActivationResponseType(override val value: Byte) : HasValue { GET_VERSION_RESPONSE(0x15.toByte()), SET_UNIQUE_ID_RESPONSE(0x1b.toByte()), UNKNOWN(0xff.toByte()); - - companion object { - - @JvmStatic - fun byLength(length: Byte): ActivationResponseType { - for (type in values()) { - if (type.length == length) { - return type - } - } - return UNKNOWN - } - } - } - - companion object { - - @JvmStatic - fun byValue(value: Byte): ResponseType { - for (type in values()) { - if (type.value == value) { - return type - } - } - return UNKNOWN - } } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt index daf867f9fa..0321f8b912 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import java.nio.ByteBuffer class SetUniqueIdResponse( @@ -147,7 +148,7 @@ class SetUniqueIdResponse( bleVersionMinor = (encoded[13].toInt() and 0xff).toShort() bleVersionInterim = (encoded[14].toInt() and 0xff).toShort() productId = (encoded[15].toInt() and 0xff).toShort() - podStatus = PodStatus.byValue(encoded[16]) + podStatus = byValue(encoded[16], PodStatus.UNKNOWN) lotNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20])).long podSequenceNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24])).long uniqueIdReceivedInCommand = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[25], encoded[26], encoded[27], encoded[28])).long diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt index e62250b93f..8b06c96c4b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import java.nio.ByteBuffer import java.util.* import kotlin.experimental.and @@ -19,7 +20,7 @@ class VersionResponse( private val bleVersionMinor: Short = (encoded[6].toInt() and 0xff).toShort() private val bleVersionInterim: Short = (encoded[7].toInt() and 0xff).toShort() private val productId: Short = (encoded[8].toInt() and 0xff).toShort() - private val podStatus: PodStatus = PodStatus.byValue((encoded[9] and 0xf)) + private val podStatus: PodStatus = byValue((encoded[9] and 0xf), PodStatus.UNKNOWN) private val lotNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[10], encoded[11], encoded[12], encoded[13])).long private val podSequenceNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[14], encoded[15], encoded[16], encoded[17])).long private val rssi: Byte = (encoded[18] and 0x3f) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index b9df5b487a..a223b7099a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -34,6 +34,8 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( store() } + // TODO: dynamic get() fun instead of assignment + override val isUniqueIdSet: Boolean = activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) override val isActivationCompleted: Boolean = activationProgress == ActivationProgress.COMPLETED @@ -105,17 +107,17 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( } override fun updateFromDefaultStatusResponse(response: DefaultStatusResponse) { - podState.deliveryStatus = response.getDeliveryStatus() - podState.podStatus = response.getPodStatus() - podState.pulsesDelivered = response.getTotalPulsesDelivered() - podState.pulsesRemaining = response.getReservoirPulsesRemaining() - podState.sequenceNumberOfLastProgrammingCommand = response.getSequenceNumberOfLastProgrammingCommand() - podState.minutesSinceActivation = response.getMinutesSinceActivation() + podState.deliveryStatus = response.deliveryStatus + podState.podStatus = response.podStatus + podState.pulsesDelivered = response.totalPulsesDelivered + podState.pulsesRemaining = response.reservoirPulsesRemaining + podState.sequenceNumberOfLastProgrammingCommand = response.sequenceNumberOfLastProgrammingCommand + podState.minutesSinceActivation = response.minutesSinceActivation // TODO active alerts podState.lastUpdated = System.currentTimeMillis() - store(); + store() } override fun updateFromVersionResponse(response: VersionResponse) { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt new file mode 100644 index 0000000000..3794ddf850 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util + +interface HasValue { + + val value: Byte +} + +inline fun byValue(value: Byte, default: T): T where T : Enum, T : HasValue { + return enumValues().firstOrNull { it.value == value } ?: default +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt index 5aa3dbf73f..b9ff49d4b3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt @@ -14,7 +14,7 @@ object MessageUtil { val b = sArr[s.toInt()].toByte() var s2 = b.toShort() if (b < 0) { - s2 = ((b and Byte.MAX_VALUE) as Byte + 128).toShort() + s2 = ((b and Byte.MAX_VALUE) + 128).toShort() } i += s2.toInt() s = (s + 1).toShort() @@ -28,7 +28,7 @@ object MessageUtil { val b2 = (b xor (s and 255).toByte()) // TODO byte conversion ok? var s2 = b2.toShort() if (b2 < 0) { - s2 = ((b2 and Byte.MAX_VALUE) as Byte + 128).toShort() + s2 = ((b2 and Byte.MAX_VALUE) + 128).toShort() } s = (((s.toInt() shr 8).toShort() and 255) xor crc16table[s2.toInt()]) } diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt index 1621faccb2..2095cbbf8a 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt @@ -17,35 +17,35 @@ class AlarmStatusResponseTest { Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE, response.responseType) - Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.value, response.getMessageType()) + Assert.assertEquals(ResponseType.ADDITIONAL_STATUS_RESPONSE.value, response.messageType) Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS, response.statusResponseType) - Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS.value, response.getAdditionalStatusResponseType()) - Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()) - Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()) - Assert.assertEquals(0.toShort(), response.getBolusPulsesRemaining()) - Assert.assertEquals(5.toShort(), response.getSequenceNumberOfLastProgrammingCommand()) - Assert.assertEquals(445.toShort(), response.getTotalPulsesDelivered()) - Assert.assertEquals(AlarmType.NONE, response.getAlarmType()) - Assert.assertEquals(0.toShort(), response.getAlarmTime()) - Assert.assertEquals(1023.toShort(), response.getReservoirPulsesRemaining()) - Assert.assertEquals(405.toShort(), response.getMinutesSinceActivation()) - Assert.assertFalse(response.isAlert0Active()) - Assert.assertFalse(response.isAlert1Active()) - Assert.assertFalse(response.isAlert2Active()) - Assert.assertFalse(response.isAlert3Active()) - Assert.assertFalse(response.isAlert4Active()) - Assert.assertFalse(response.isAlert5Active()) - Assert.assertFalse(response.isAlert6Active()) - Assert.assertFalse(response.isAlert7Active()) - Assert.assertFalse(response.isOcclusionAlarm()) - Assert.assertFalse(response.isPulseInfoInvalid()) - Assert.assertEquals(PodStatus.UNINITIALIZED, response.getPodStatusWhenAlarmOccurred()) - Assert.assertFalse(response.isImmediateBolusWhenAlarmOccurred()) - Assert.assertEquals(0x00.toByte(), response.getOcclusionType()) - Assert.assertFalse(response.isOccurredWhenFetchingImmediateBolusActiveInformation()) - Assert.assertEquals(0.toShort(), response.getRssi()) - Assert.assertEquals(0.toShort(), response.getReceiverLowerGain()) - Assert.assertEquals(PodStatus.UNINITIALIZED, response.getPodStatusWhenAlarmOccurred2()) - Assert.assertEquals(26378.toShort(), response.getReturnAddressOfPodAlarmHandlerCaller()) + Assert.assertEquals(ResponseType.StatusResponseType.ALARM_STATUS.value, response.additionalStatusResponseType) + Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.podStatus) + Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.deliveryStatus) + Assert.assertEquals(0.toShort(), response.bolusPulsesRemaining) + Assert.assertEquals(5.toShort(), response.sequenceNumberOfLastProgrammingCommand) + Assert.assertEquals(445.toShort(), response.totalPulsesDelivered) + Assert.assertEquals(AlarmType.NONE, response.alarmType) + Assert.assertEquals(0.toShort(), response.alarmTime) + Assert.assertEquals(1023.toShort(), response.reservoirPulsesRemaining) + Assert.assertEquals(405.toShort(), response.minutesSinceActivation) + Assert.assertFalse(response.alert0Active) + Assert.assertFalse(response.alert1Active) + Assert.assertFalse(response.alert2Active) + Assert.assertFalse(response.alert3Active) + Assert.assertFalse(response.alert4Active) + Assert.assertFalse(response.alert5Active) + Assert.assertFalse(response.alert6Active) + Assert.assertFalse(response.alert7Active) + Assert.assertFalse(response.occlusionAlarm) + Assert.assertFalse(response.pulseInfoInvalid) + Assert.assertEquals(PodStatus.UNINITIALIZED, response.podStatusWhenAlarmOccurred) + Assert.assertFalse(response.immediateBolusWhenAlarmOccurred) + Assert.assertEquals(0x00.toByte(), response.occlusionType) + Assert.assertFalse(response.occurredWhenFetchingImmediateBolusActiveInformation) + Assert.assertEquals(0.toShort(), response.rssi) + Assert.assertEquals(0.toShort(), response.receiverLowerGain) + Assert.assertEquals(PodStatus.UNINITIALIZED, response.podStatusWhenAlarmOccurred2) + Assert.assertEquals(26378.toShort(), response.returnAddressOfPodAlarmHandlerCaller) } } \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt index 6ccbdfd13e..da375beab1 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt @@ -16,21 +16,21 @@ class DefaultStatusResponseTest { Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE, response.responseType) - Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE.value, response.getMessageType()) - Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.getDeliveryStatus()) - Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.getPodStatus()) - Assert.assertEquals(320.toShort(), response.getTotalPulsesDelivered()) - Assert.assertEquals(5.toShort(), response.getSequenceNumberOfLastProgrammingCommand()) - Assert.assertEquals(0.toShort(), response.getBolusPulsesRemaining()) - Assert.assertFalse(response.isOcclusionAlertActive()) - Assert.assertFalse(response.isAlert1Active()) - Assert.assertFalse(response.isAlert2Active()) - Assert.assertFalse(response.isAlert3Active()) - Assert.assertFalse(response.isAlert4Active()) - Assert.assertFalse(response.isAlert5Active()) - Assert.assertFalse(response.isAlert6Active()) - Assert.assertFalse(response.isAlert7Active()) - Assert.assertEquals(280.toShort(), response.getMinutesSinceActivation()) - Assert.assertEquals(1023.toShort(), response.getReservoirPulsesRemaining()) + Assert.assertEquals(ResponseType.DEFAULT_STATUS_RESPONSE.value, response.messageType) + Assert.assertEquals(DeliveryStatus.BASAL_ACTIVE, response.deliveryStatus) + Assert.assertEquals(PodStatus.RUNNING_ABOVE_MIN_VOLUME, response.podStatus) + Assert.assertEquals(320.toShort(), response.totalPulsesDelivered) + Assert.assertEquals(5.toShort(), response.sequenceNumberOfLastProgrammingCommand) + Assert.assertEquals(0.toShort(), response.bolusPulsesRemaining) + Assert.assertFalse(response.occlusionAlertActive) + Assert.assertFalse(response.alert1Active) + Assert.assertFalse(response.alert2Active) + Assert.assertFalse(response.alert3Active) + Assert.assertFalse(response.alert4Active) + Assert.assertFalse(response.alert5Active) + Assert.assertFalse(response.alert6Active) + Assert.assertFalse(response.alert7Active) + Assert.assertEquals(280.toShort(), response.minutesSinceActivation) + Assert.assertEquals(1023.toShort(), response.reservoirPulsesRemaining) } } \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt index c4dc703f79..206ac491aa 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt @@ -18,10 +18,10 @@ class NakResponseTest { Assert.assertArrayEquals(encoded, response.encoded) Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.NAK_RESPONSE, response.responseType) - Assert.assertEquals(ResponseType.NAK_RESPONSE.value, response.getMessageType()) - Assert.assertEquals(NakErrorType.ILLEGAL_PARAM, response.getNakErrorType()) - Assert.assertEquals(AlarmType.NONE, response.getAlarmType()) - Assert.assertEquals(PodStatus.RUNNING_BELOW_MIN_VOLUME, response.getPodStatus()) - Assert.assertEquals(0x00.toShort(), response.getSecurityNakSyncCount()) + Assert.assertEquals(ResponseType.NAK_RESPONSE.value, response.messageType) + Assert.assertEquals(NakErrorType.ILLEGAL_PARAM, response.nakErrorType) + Assert.assertEquals(AlarmType.NONE, response.alarmType) + Assert.assertEquals(PodStatus.RUNNING_BELOW_MIN_VOLUME, response.podStatus) + Assert.assertEquals(0x00.toShort(), response.securityNakSyncCount) } } \ No newline at end of file From 0a013b6d2bcb18409c4b4fab83486c5a09eebd67 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Fri, 26 Feb 2021 22:10:25 +0100 Subject: [PATCH 044/649] Serializable instead of Any for data in PodEvent --- .../plugins/pump/omnipod/dash/driver/event/PodEvent.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt index 65d72fa4bb..c1fe5ace52 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt @@ -1,6 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event +import java.io.Serializable + class PodEvent( val type: PodEventType, - val data: Any? + val data: Serializable? ) \ No newline at end of file From dcf7672a24c05d783a9fcc48cdd798f9ff725abe Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sat, 27 Feb 2021 00:39:55 +0100 Subject: [PATCH 045/649] More cleanup after conversion --- .../dash/driver/OmnipodDashManagerImpl.kt | 28 ++-- .../omnipod/dash/driver/event/PodEvent.kt | 18 ++- .../omnipod/dash/driver/event/PodEventType.kt | 12 -- .../pod/command/ProgramAlertsCommand.kt | 5 +- .../driver/pod/command/ProgramBasalCommand.kt | 1 + .../driver/pod/command/ProgramBolusCommand.kt | 2 + .../pod/command/ProgramInsulinCommand.kt | 8 -- .../pod/command/ProgramTempBasalCommand.kt | 3 + .../driver/pod/command/SetUniqueIdCommand.kt | 1 + .../pod/command/SilenceAlertsCommand.kt | 1 + .../driver/pod/command/StopDeliveryCommand.kt | 2 + .../builder/HeaderEnabledCommandBuilder.kt | 1 + .../driver/pod/definition/BasalProgram.kt | 2 +- .../dash/driver/pod/definition/BeepType.kt | 8 +- .../pod/response/SetUniqueIdResponse.kt | 135 +++--------------- .../driver/pod/response/VersionResponse.kt | 90 ++---------- .../state/OmnipodDashPodStateManagerImpl.kt | 117 +++++++++------ .../pod/response/SetUniqueIdResponseTest.kt | 39 +++-- .../pod/response/VersionResponseTest.kt | 31 ++-- 19 files changed, 185 insertions(+), 319 deletions(-) delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEventType.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 335ee0f372..3b3447003b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEventType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand.Companion.DEFAULT_UNIQUE_ID import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress @@ -31,25 +30,26 @@ class OmnipodDashManagerImpl @Inject constructor( return Observable.error(IllegalStateException("Pod is in an incorrect state")) } - private val observeConnectToPod: Observable = Observable.defer { - // TODO - // send CONNECTING event here - bleManager.connect() - Observable.just(PodEvent(PodEventType.CONNECTED, null)) - } + private val observeConnectToPod: Observable + get() { + return Observable.defer { + bleManager.connect() + Observable.just(PodEvent.Connected(0)) // TODO should be returned in BleManager + } + } override fun activatePodPart1(): Observable { - // TODO + val command = GetVersionCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(DEFAULT_UNIQUE_ID) // + .build() + return Observable.concat( observePodReadyForActivationPart1, observeConnectToPod, Observable.defer { - bleManager.sendCommand(GetVersionCommand.Builder() // - .setSequenceNumber(podStateManager.messageSequenceNumber) // - .setUniqueId(DEFAULT_UNIQUE_ID) // - .build() - ) - Observable.just(PodEvent(PodEventType.COMMAND_SENT, null)) + bleManager.sendCommand(command) + Observable.just(PodEvent.CommandSent(command)) // TODO should be returned in BleManager } // ... Send more commands ) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt index c1fe5ace52..e5fe44fb00 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt @@ -1,8 +1,16 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event -import java.io.Serializable +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response + +sealed class PodEvent { + + object Scanning : PodEvent() + object Pairing : PodEvent() + object Connecting : PodEvent() + class Connected(val uniqueId: Int) : PodEvent() + class CommandSending(val command: Command) : PodEvent() + class CommandSent(val command: Command) : PodEvent() + class ResponseReceived(val response: Response) : PodEvent() +} -class PodEvent( - val type: PodEventType, - val data: Serializable? -) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEventType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEventType.kt deleted file mode 100644 index 15397610ee..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEventType.kt +++ /dev/null @@ -1,12 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event - -enum class PodEventType { - SCANNING, - PAIRING, - CONNECTING, - CONNECTED, - COMMAND_SENDING, - COMMAND_SENT, - RESPONSE_RECEIVED, - // ... -} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt index 3ba15675f8..4f0424988b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt @@ -11,7 +11,7 @@ class ProgramAlertsCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, - alertConfigurations: List?, + alertConfigurations: List, nonce: Int ) : NonceEnabledCommand(CommandType.PROGRAM_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { @@ -52,6 +52,7 @@ class ProgramAlertsCommand private constructor( class Builder : NonceEnabledCommandBuilder() { private var alertConfigurations: List? = null + fun setAlertConfigurations(alertConfigurations: List?): Builder { this.alertConfigurations = alertConfigurations return this @@ -59,7 +60,7 @@ class ProgramAlertsCommand private constructor( override fun buildCommand(): ProgramAlertsCommand { requireNotNull(alertConfigurations) { "alertConfigurations can not be null" } // !!? - return ProgramAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, alertConfigurations, nonce!!) // TODO this might crash if not all are set + return ProgramAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, alertConfigurations!!, nonce!!) // TODO this might crash if not all are set } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt index 3495f94566..5758fe9377 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -76,6 +76,7 @@ class ProgramBasalCommand private constructor( private var basalProgram: BasalProgram? = null private var programReminder: ProgramReminder? = null private var currentTime: Date? = null + fun setBasalProgram(basalProgram: BasalProgram?): Builder { this.basalProgram = basalProgram return this diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt index 79d57534a0..c6bbfcfb72 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -57,6 +57,7 @@ class ProgramBolusCommand private constructor( private var numberOfUnits: Double? = null private var delayBetweenPulsesInEighthSeconds: Byte? = null private var programReminder: ProgramReminder? = null + fun setNumberOfUnits(numberOfUnits: Double): Builder { require(numberOfUnits > 0.0) { "Number of units should be greater than zero" } require((numberOfUnits * 1000).toInt() % 50 == 0) { "Number of units must be dividable by 0.05" } @@ -78,6 +79,7 @@ class ProgramBolusCommand private constructor( requireNotNull(numberOfUnits) { "numberOfUnits can not be null" } requireNotNull(delayBetweenPulsesInEighthSeconds) { "delayBetweenPulsesInEighthSeconds can not be null" } requireNotNull(programReminder) { "programReminder can not be null" } + val numberOfPulses = Math.round(numberOfUnits!! * 20).toShort() val byte10And11 = (numberOfPulses * delayBetweenPulsesInEighthSeconds!!).toShort() val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, listOf(BolusShortInsulinProgramElement(numberOfPulses)), calculateChecksum(0x01.toByte(), byte10And11, numberOfPulses), diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt index eb41e68bda..0020407056 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt @@ -34,14 +34,6 @@ class ProgramInsulinCommand internal constructor( } } - fun calculateChecksum(bytes: ByteArray): Short { - var sum: Short = 0 - for (b in bytes) { - sum = ((b.toInt() and 0xff) + sum).toShort() - } - return sum - } - override val encoded: ByteArray get() { val buffer = ByteBuffer.allocate(getLength().toInt()) // diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt index 37c4597ae9..229138dd2d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -31,6 +31,7 @@ class ProgramTempBasalCommand private constructor( private var programReminder: ProgramReminder? = null private var rateInUnitsPerHour: Double? = null private var durationInMinutes: Short? = null + fun setProgramReminder(programReminder: ProgramReminder?): Builder { this.programReminder = programReminder return this @@ -43,6 +44,7 @@ class ProgramTempBasalCommand private constructor( fun setDurationInMinutes(durationInMinutes: Short): Builder { require(durationInMinutes % 30 == 0) { "durationInMinutes must be dividable by 30" } + this.durationInMinutes = durationInMinutes return this } @@ -51,6 +53,7 @@ class ProgramTempBasalCommand private constructor( requireNotNull(programReminder) { "programReminder can not be null" } requireNotNull(rateInUnitsPerHour) { "rateInUnitsPerHour can not be null" } requireNotNull(durationInMinutes) { "durationInMinutes can not be null" } + val durationInSlots = (durationInMinutes!! / 30).toByte() val pulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToPulsesPerSlot(durationInSlots, rateInUnitsPerHour!!) val tenthPulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToTenthPulsesPerSlot(durationInSlots.toInt(), rateInUnitsPerHour!!) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt index 83c0fbc6f4..965f9a3de3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -45,6 +45,7 @@ class SetUniqueIdCommand private constructor( private var lotNumber: Int? = null private var podSequenceNumber: Int? = null private var initializationTime: Date? = null + fun setLotNumber(lotNumber: Int): Builder { this.lotNumber = lotNumber return this diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index d9c32e8f7a..e838c89395 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -63,6 +63,7 @@ class SilenceAlertsCommand private constructor( private var silenceSuspendInProgressAlert = false private var silenceSuspendEndedAlert = false private var silencePodExpirationAlert = false + fun setSilenceAutoOffAlert(silenceAutoOffAlert: Boolean): Builder { this.silenceAutoOffAlert = silenceAutoOffAlert return this diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt index e941909a66..254fd8edf3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -57,6 +57,7 @@ class StopDeliveryCommand private constructor( private var deliveryType: DeliveryType? = null private var beepType: BeepType? = BeepType.LONG_SINGLE_BEEP + fun setDeliveryType(deliveryType: DeliveryType?): Builder { this.deliveryType = deliveryType return this @@ -70,6 +71,7 @@ class StopDeliveryCommand private constructor( override fun buildCommand(): StopDeliveryCommand { requireNotNull(deliveryType) { "deliveryType can not be null" } requireNotNull(beepType) { "beepType can not be null" } + return StopDeliveryCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, deliveryType!!, beepType!!, nonce!!) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt index 27dcf630e4..f6fc7151b8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt @@ -8,6 +8,7 @@ abstract class HeaderEnabledCommandBuilder protected var uniqueId: Int? = null protected var sequenceNumber: Short? = null protected var multiCommandFlag = false + override fun build(): R { requireNotNull(uniqueId) { "uniqueId can not be null" } requireNotNull(sequenceNumber) { "sequenceNumber can not be null" } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt index 45bbc93b3d..ef8f764f91 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt @@ -7,7 +7,7 @@ class BasalProgram( ) { val segments: MutableList = segments.toMutableList() - get() = Collections.unmodifiableList(field) // TODO Adrian: moved method here + get() = Collections.unmodifiableList(field) fun addSegment(segment: Segment) { segments.add(segment) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt index adcf4a9a5b..d997663b6f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt @@ -1,10 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition -enum class BeepType( // Used in stop delivery command - val value: Byte -) { +enum class BeepType(val value: Byte) { SILENT(0x00.toByte()), - FOUR_TIMES_BIP_BEEP(0x02.toByte()), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert - LONG_SINGLE_BEEP(0x06.toByte()); + FOUR_TIMES_BIP_BEEP(0x02.toByte()), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert + LONG_SINGLE_BEEP(0x06.toByte()); // Used in stop delivery command } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt index 0321f8b912..e91b750a6a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt @@ -9,101 +9,25 @@ class SetUniqueIdResponse( encoded: ByteArray ) : ActivationResponseBase(ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded) { - private val messageType: Byte // TODO directly assign here - private val messageLength: Short - private val pulseVolumeInTenThousandthMicroLiter: Short - private val pumpRate: Short - private val primePumpRate: Short - private val numberOfEngagingClutchDrivePulses: Short - private val numberOfPrimePulses: Short - private val podExpirationTimeInHours: Short - private val firmwareVersionMajor: Short - private val firmwareVersionMinor: Short - private val firmwareVersionInterim: Short - private val bleVersionMajor: Short - private val bleVersionMinor: Short - private val bleVersionInterim: Short - private val productId: Short - private val podStatus: PodStatus - private val lotNumber: Long - private val podSequenceNumber: Long - private val uniqueIdReceivedInCommand: Long - - fun getMessageType(): Byte { - return messageType - } - - fun getMessageLength(): Short { // TODO value getters - return messageLength - } - - fun getPulseVolumeInTenThousandthMicroLiter(): Short { - return pulseVolumeInTenThousandthMicroLiter - } - - fun getDeliveryRate(): Short { - return pumpRate - } - - fun getPrimeRate(): Short { - return primePumpRate - } - - fun getNumberOfEngagingClutchDrivePulses(): Short { - return numberOfEngagingClutchDrivePulses - } - - fun getNumberOfPrimePulses(): Short { - return numberOfPrimePulses - } - - fun getPodExpirationTimeInHours(): Short { - return podExpirationTimeInHours - } - - fun getFirmwareVersionMajor(): Short { - return firmwareVersionMajor - } - - fun getFirmwareVersionMinor(): Short { - return firmwareVersionMinor - } - - fun getFirmwareVersionInterim(): Short { - return firmwareVersionInterim - } - - fun getBleVersionMajor(): Short { - return bleVersionMajor - } - - fun getBleVersionMinor(): Short { - return bleVersionMinor - } - - fun getBleVersionInterim(): Short { - return bleVersionInterim - } - - fun getProductId(): Short { - return productId - } - - fun getPodStatus(): PodStatus { - return podStatus - } - - fun getLotNumber(): Long { - return lotNumber - } - - fun getPodSequenceNumber(): Long { - return podSequenceNumber - } - - fun getUniqueIdReceivedInCommand(): Long { - return uniqueIdReceivedInCommand - } + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val pulseVolumeInTenThousandthMicroLiter: Short = ByteBuffer.wrap(byteArrayOf(encoded[2], encoded[3])).short + val pumpRate: Short = (encoded[4].toInt() and 0xff).toShort() + val primePumpRate: Short = (encoded[5].toInt() and 0xff).toShort() + val numberOfEngagingClutchDrivePulses: Short = (encoded[6].toInt() and 0xff).toShort() + val numberOfPrimePulses: Short = (encoded[7].toInt() and 0xff).toShort() + val podExpirationTimeInHours: Short = (encoded[8].toInt() and 0xff).toShort() + val firmwareVersionMajor: Short = (encoded[9].toInt() and 0xff).toShort() + val firmwareVersionMinor: Short = (encoded[10].toInt() and 0xff).toShort() + val firmwareVersionInterim: Short = (encoded[11].toInt() and 0xff).toShort() + val bleVersionMajor: Short = (encoded[12].toInt() and 0xff).toShort() + val bleVersionMinor: Short = (encoded[13].toInt() and 0xff).toShort() + val bleVersionInterim: Short = (encoded[14].toInt() and 0xff).toShort() + val productId: Short = (encoded[15].toInt() and 0xff).toShort() + val podStatus: PodStatus = byValue(encoded[16], PodStatus.UNKNOWN) + val lotNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20])).long + val podSequenceNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24])).long + val uniqueIdReceivedInCommand: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[25], encoded[26], encoded[27], encoded[28])).long override fun toString(): String { return "SetUniqueIdResponse{" + @@ -132,25 +56,4 @@ class SetUniqueIdResponse( '}' } - init { - messageType = encoded[0] - messageLength = (encoded[1].toInt() and 0xff).toShort() - pulseVolumeInTenThousandthMicroLiter = ByteBuffer.wrap(byteArrayOf(encoded[2], encoded[3])).short - pumpRate = (encoded[4].toInt() and 0xff).toShort() - primePumpRate = (encoded[5].toInt() and 0xff).toShort() - numberOfEngagingClutchDrivePulses = (encoded[6].toInt() and 0xff).toShort() - numberOfPrimePulses = (encoded[7].toInt() and 0xff).toShort() - podExpirationTimeInHours = (encoded[8].toInt() and 0xff).toShort() - firmwareVersionMajor = (encoded[9].toInt() and 0xff).toShort() - firmwareVersionMinor = (encoded[10].toInt() and 0xff).toShort() - firmwareVersionInterim = (encoded[11].toInt() and 0xff).toShort() - bleVersionMajor = (encoded[12].toInt() and 0xff).toShort() - bleVersionMinor = (encoded[13].toInt() and 0xff).toShort() - bleVersionInterim = (encoded[14].toInt() and 0xff).toShort() - productId = (encoded[15].toInt() and 0xff).toShort() - podStatus = byValue(encoded[16], PodStatus.UNKNOWN) - lotNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20])).long - podSequenceNumber = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24])).long - uniqueIdReceivedInCommand = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[25], encoded[26], encoded[27], encoded[28])).long - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt index 8b06c96c4b..243c191efb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt @@ -11,81 +11,21 @@ class VersionResponse( encoded: ByteArray ) : ActivationResponseBase(ActivationResponseType.GET_VERSION_RESPONSE, encoded) { - private val messageType: Byte = encoded[0] - private val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() - private val firmwareVersionMajor: Short = (encoded[2].toInt() and 0xff).toShort() - private val firmwareVersionMinor: Short = (encoded[3].toInt() and 0xff).toShort() - private val firmwareVersionInterim: Short = (encoded[4].toInt() and 0xff).toShort() - private val bleVersionMajor: Short = (encoded[5].toInt() and 0xff).toShort() - private val bleVersionMinor: Short = (encoded[6].toInt() and 0xff).toShort() - private val bleVersionInterim: Short = (encoded[7].toInt() and 0xff).toShort() - private val productId: Short = (encoded[8].toInt() and 0xff).toShort() - private val podStatus: PodStatus = byValue((encoded[9] and 0xf), PodStatus.UNKNOWN) - private val lotNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[10], encoded[11], encoded[12], encoded[13])).long - private val podSequenceNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[14], encoded[15], encoded[16], encoded[17])).long - private val rssi: Byte = (encoded[18] and 0x3f) - private val receiverLowerGain: Byte = ((encoded[18].toInt() shr 6 and 0x03).toByte()) - private val uniqueIdReceivedInCommand: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[19], encoded[20], encoded[21], encoded[22])).long - - fun getMessageType(): Byte { - return messageType - } - - fun getMessageLength(): Short { - return messageLength - } - - fun getFirmwareVersionMajor(): Short { - return firmwareVersionMajor - } - - fun getFirmwareVersionMinor(): Short { - return firmwareVersionMinor - } - - fun getFirmwareVersionInterim(): Short { - return firmwareVersionInterim - } - - fun getBleVersionMajor(): Short { - return bleVersionMajor - } - - fun getBleVersionMinor(): Short { - return bleVersionMinor - } - - fun getBleVersionInterim(): Short { - return bleVersionInterim - } - - fun getProductId(): Short { - return productId - } - - fun getPodStatus(): PodStatus { - return podStatus - } - - fun getLotNumber(): Long { - return lotNumber - } - - fun getPodSequenceNumber(): Long { - return podSequenceNumber - } - - fun getRssi(): Byte { - return rssi - } - - fun getReceiverLowerGain(): Byte { - return receiverLowerGain - } - - fun getUniqueIdReceivedInCommand(): Long { - return uniqueIdReceivedInCommand - } + val messageType: Byte = encoded[0] + val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() + val firmwareVersionMajor: Short = (encoded[2].toInt() and 0xff).toShort() + val firmwareVersionMinor: Short = (encoded[3].toInt() and 0xff).toShort() + val firmwareVersionInterim: Short = (encoded[4].toInt() and 0xff).toShort() + val bleVersionMajor: Short = (encoded[5].toInt() and 0xff).toShort() + val bleVersionMinor: Short = (encoded[6].toInt() and 0xff).toShort() + val bleVersionInterim: Short = (encoded[7].toInt() and 0xff).toShort() + val productId: Short = (encoded[8].toInt() and 0xff).toShort() + val podStatus: PodStatus = byValue((encoded[9] and 0xf), PodStatus.UNKNOWN) + val lotNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[10], encoded[11], encoded[12], encoded[13])).long + val podSequenceNumber: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[14], encoded[15], encoded[16], encoded[17])).long + val rssi: Byte = (encoded[18] and 0x3f) + val receiverLowerGain: Byte = ((encoded[18].toInt() shr 6 and 0x03).toByte()) + val uniqueIdReceivedInCommand: Long = ByteBuffer.wrap(byteArrayOf(0, 0, 0, 0, encoded[19], encoded[20], encoded[21], encoded[22])).long override fun toString(): String { return "VersionResponse{" + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index a223b7099a..5fd48d82b4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -36,14 +36,18 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( // TODO: dynamic get() fun instead of assignment - override val isUniqueIdSet: Boolean = activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) + override val isUniqueIdSet: Boolean + get() = activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) - override val isActivationCompleted: Boolean = activationProgress == ActivationProgress.COMPLETED + override val isActivationCompleted: Boolean + get() = activationProgress == ActivationProgress.COMPLETED - override val isSuspended: Boolean = podState.deliveryStatus?.equals(DeliveryStatus.SUSPENDED) - ?: true + override val isSuspended: Boolean + get() = podState.deliveryStatus?.equals(DeliveryStatus.SUSPENDED) + ?: true - override val isPodRunning: Boolean = podState.podStatus?.isRunning() ?: false + override val isPodRunning: Boolean + get() = podState.podStatus?.isRunning() ?: false override var lastConnection: Long get() = podState.lastConnection @@ -52,54 +56,77 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( store() } - override val lastUpdated: Long = podState.lastUpdated + override val lastUpdated: Long + get() = podState.lastUpdated - override val messageSequenceNumber: Short = podState.messageSequenceNumber + override val messageSequenceNumber: Short + get() = podState.messageSequenceNumber - override val sequenceNumberOfLastProgrammingCommand: Short? = podState.sequenceNumberOfLastProgrammingCommand + override val sequenceNumberOfLastProgrammingCommand: Short? + get() = podState.sequenceNumberOfLastProgrammingCommand - override val activationTime: Long? = podState.activationTime + override val activationTime: Long? + get() = podState.activationTime - override val uniqueId: Long? = podState.uniqueId + override val uniqueId: Long? + get() = podState.uniqueId - override val bluetoothAddress: String? = podState.bluetoothAddress + override val bluetoothAddress: String? + get() = podState.bluetoothAddress - override val bluetoothVersion: SoftwareVersion? = podState.bleVersion + override val bluetoothVersion: SoftwareVersion? + get() = podState.bleVersion - override val firmwareVersion: SoftwareVersion? = podState.firmwareVersion + override val firmwareVersion: SoftwareVersion? + get() = podState.firmwareVersion - override val lotNumber: Long? = podState.lotNumber + override val lotNumber: Long? + get() = podState.lotNumber - override val podSequenceNumber: Long? = podState.podSequenceNumber + override val podSequenceNumber: Long? + get() = podState.podSequenceNumber - override val pulseRate: Short? = podState.pulseRate + override val pulseRate: Short? + get() = podState.pulseRate - override val primePulseRate: Short? = podState.primePulseRate + override val primePulseRate: Short? + get() = podState.primePulseRate - override val podLifeInHours: Short? = podState.podLifeInHours + override val podLifeInHours: Short? + get() = podState.podLifeInHours - override val firstPrimeBolusVolume: Short? = podState.firstPrimeBolusVolume + override val firstPrimeBolusVolume: Short? + get() = podState.firstPrimeBolusVolume - override val secondPrimeBolusVolume: Short? = podState.secondPrimeBolusVolume + override val secondPrimeBolusVolume: Short? + get() = podState.secondPrimeBolusVolume - override val pulsesDelivered: Short? = podState.pulsesDelivered + override val pulsesDelivered: Short? + get() = podState.pulsesDelivered - override val pulsesRemaining: Short? = podState.pulsesRemaining + override val pulsesRemaining: Short? + get() = podState.pulsesRemaining - override val podStatus: PodStatus? = podState.podStatus + override val podStatus: PodStatus? + get() = podState.podStatus - override val deliveryStatus: DeliveryStatus? = podState.deliveryStatus + override val deliveryStatus: DeliveryStatus? + get() = podState.deliveryStatus - override val minutesSinceActivation: Short? = podState.minutesSinceActivation + override val minutesSinceActivation: Short? + get() = podState.minutesSinceActivation - override val activeAlerts: EnumSet? = podState.activeAlerts + override val activeAlerts: EnumSet? + get() = podState.activeAlerts - override val tempBasal: OmnipodDashPodStateManager.TempBasal? = podState.tempBasal + override val tempBasal: OmnipodDashPodStateManager.TempBasal? + get() = podState.tempBasal override val tempBasalActive: Boolean - get() = tempBasal != null && tempBasal.startTime + tempBasal.durationInMinutes * 60 * 1000 > System.currentTimeMillis() + get() = tempBasal != null && tempBasal!!.startTime + tempBasal!!.durationInMinutes * 60 * 1000 > System.currentTimeMillis() - override val basalProgram: BasalProgram? = podState.basalProgram + override val basalProgram: BasalProgram? + get() = podState.basalProgram override fun increaseMessageSequenceNumber() { podState.messageSequenceNumber = ((podState.messageSequenceNumber.toInt() + 1) and 0x0f).toShort() @@ -121,28 +148,28 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( } override fun updateFromVersionResponse(response: VersionResponse) { - podState.bleVersion = SoftwareVersion(response.getBleVersionMajor(), response.getBleVersionMinor(), response.getBleVersionInterim()) - podState.firmwareVersion = SoftwareVersion(response.getFirmwareVersionMajor(), response.getFirmwareVersionMinor(), response.getFirmwareVersionInterim()) - podState.podStatus = response.getPodStatus() - podState.lotNumber = response.getLotNumber() - podState.podSequenceNumber = response.getPodSequenceNumber() + podState.bleVersion = SoftwareVersion(response.bleVersionMajor, response.bleVersionMinor, response.bleVersionInterim) + podState.firmwareVersion = SoftwareVersion(response.firmwareVersionMajor, response.firmwareVersionMinor, response.firmwareVersionInterim) + podState.podStatus = response.podStatus + podState.lotNumber = response.lotNumber + podState.podSequenceNumber = response.podSequenceNumber podState.lastUpdated = System.currentTimeMillis() store() } override fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) { - podState.pulseRate = response.getDeliveryRate() - podState.primePulseRate = response.getPrimeRate() - podState.firstPrimeBolusVolume = response.getNumberOfPrimePulses() - podState.secondPrimeBolusVolume = response.getNumberOfEngagingClutchDrivePulses() - podState.podLifeInHours = response.getPodExpirationTimeInHours() - podState.bleVersion = SoftwareVersion(response.getBleVersionMajor(), response.getBleVersionMinor(), response.getBleVersionInterim()) - podState.firmwareVersion = SoftwareVersion(response.getFirmwareVersionMajor(), response.getFirmwareVersionMinor(), response.getFirmwareVersionInterim()) - podState.podStatus = response.getPodStatus() - podState.lotNumber = response.getLotNumber() - podState.podSequenceNumber = response.getPodSequenceNumber() - podState.uniqueId = response.getUniqueIdReceivedInCommand() + podState.pulseRate = response.pumpRate + podState.primePulseRate = response.primePumpRate + podState.firstPrimeBolusVolume = response.numberOfPrimePulses + podState.secondPrimeBolusVolume = response.numberOfEngagingClutchDrivePulses + podState.podLifeInHours = response.podExpirationTimeInHours + podState.bleVersion = SoftwareVersion(response.bleVersionMajor, response.bleVersionMinor, response.bleVersionInterim) + podState.firmwareVersion = SoftwareVersion(response.firmwareVersionMajor, response.firmwareVersionMinor, response.firmwareVersionInterim) + podState.podStatus = response.podStatus + podState.lotNumber = response.lotNumber + podState.podSequenceNumber = response.podSequenceNumber + podState.uniqueId = response.uniqueIdReceivedInCommand podState.lastUpdated = System.currentTimeMillis() store() diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt index fa0d1dac73..6f627c5d80 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert @@ -17,24 +16,24 @@ class SetUniqueIdResponseTest { Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE, response.responseType) Assert.assertEquals(ResponseType.ActivationResponseType.SET_UNIQUE_ID_RESPONSE, response.activationResponseType) - Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.value, response.getMessageType()) - Assert.assertEquals(27.toShort(), response.getMessageLength()) - Assert.assertEquals(5000.toShort(), response.getPulseVolumeInTenThousandthMicroLiter()) - Assert.assertEquals(16.toShort(), response.getDeliveryRate()) - Assert.assertEquals(8.toShort(), response.getPrimeRate()) - Assert.assertEquals(52.toShort(), response.getNumberOfEngagingClutchDrivePulses()) - Assert.assertEquals(10.toShort(), response.getNumberOfPrimePulses()) - Assert.assertEquals(80.toShort(), response.getPodExpirationTimeInHours()) - Assert.assertEquals(4.toShort(), response.getFirmwareVersionMajor()) - Assert.assertEquals(10.toShort(), response.getFirmwareVersionMinor()) - Assert.assertEquals(0.toShort(), response.getFirmwareVersionInterim()) - Assert.assertEquals(1.toShort(), response.getBleVersionMajor()) - Assert.assertEquals(3.toShort(), response.getBleVersionMinor()) - Assert.assertEquals(0.toShort(), response.getBleVersionInterim()) - Assert.assertEquals(4.toShort(), response.getProductId()) - Assert.assertEquals(PodStatus.UID_SET, response.getPodStatus()) - Assert.assertEquals(135556289L, response.getLotNumber()) - Assert.assertEquals(611540L, response.getPodSequenceNumber()) - Assert.assertEquals(37879809L, response.getUniqueIdReceivedInCommand()) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.value, response.messageType) + Assert.assertEquals(27.toShort(), response.messageLength) + Assert.assertEquals(5000.toShort(), response.pulseVolumeInTenThousandthMicroLiter) + Assert.assertEquals(16.toShort(), response.pumpRate) + Assert.assertEquals(8.toShort(), response.primePumpRate) + Assert.assertEquals(52.toShort(), response.numberOfEngagingClutchDrivePulses) + Assert.assertEquals(10.toShort(), response.numberOfPrimePulses) + Assert.assertEquals(80.toShort(), response.podExpirationTimeInHours) + Assert.assertEquals(4.toShort(), response.firmwareVersionMajor) + Assert.assertEquals(10.toShort(), response.firmwareVersionMinor) + Assert.assertEquals(0.toShort(), response.firmwareVersionInterim) + Assert.assertEquals(1.toShort(), response.bleVersionMajor) + Assert.assertEquals(3.toShort(), response.bleVersionMinor) + Assert.assertEquals(0.toShort(), response.bleVersionInterim) + Assert.assertEquals(4.toShort(), response.productId) + Assert.assertEquals(PodStatus.UID_SET, response.podStatus) + Assert.assertEquals(135556289L, response.lotNumber) + Assert.assertEquals(611540L, response.podSequenceNumber) + Assert.assertEquals(37879809L, response.uniqueIdReceivedInCommand) } } \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt index 32612070fd..2ae37834d1 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert @@ -17,20 +16,20 @@ class VersionResponseTest { Assert.assertNotSame(encoded, response.encoded) Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE, response.responseType) Assert.assertEquals(ResponseType.ActivationResponseType.GET_VERSION_RESPONSE, response.activationResponseType) - Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.value, response.getMessageType()) - Assert.assertEquals(21.toShort(), response.getMessageLength()) - Assert.assertEquals(4.toShort(), response.getFirmwareVersionMajor()) - Assert.assertEquals(10.toShort(), response.getFirmwareVersionMinor()) - Assert.assertEquals(0.toShort(), response.getFirmwareVersionInterim()) - Assert.assertEquals(1.toShort(), response.getBleVersionMajor()) - Assert.assertEquals(3.toShort(), response.getBleVersionMinor()) - Assert.assertEquals(0.toShort(), response.getBleVersionInterim()) - Assert.assertEquals(4.toShort(), response.getProductId()) - Assert.assertEquals(PodStatus.FILLED, response.getPodStatus()) - Assert.assertEquals(135556289L, response.getLotNumber()) - Assert.assertEquals(611540L, response.getPodSequenceNumber()) - Assert.assertEquals(0.toByte(), response.getRssi()) - Assert.assertEquals(0.toByte(), response.getReceiverLowerGain()) - Assert.assertEquals(4294967295L, response.getUniqueIdReceivedInCommand()) + Assert.assertEquals(ResponseType.ACTIVATION_RESPONSE.value, response.messageType) + Assert.assertEquals(21.toShort(), response.messageLength) + Assert.assertEquals(4.toShort(), response.firmwareVersionMajor) + Assert.assertEquals(10.toShort(), response.firmwareVersionMinor) + Assert.assertEquals(0.toShort(), response.firmwareVersionInterim) + Assert.assertEquals(1.toShort(), response.bleVersionMajor) + Assert.assertEquals(3.toShort(), response.bleVersionMinor) + Assert.assertEquals(0.toShort(), response.bleVersionInterim) + Assert.assertEquals(4.toShort(), response.productId) + Assert.assertEquals(PodStatus.FILLED, response.podStatus) + Assert.assertEquals(135556289L, response.lotNumber) + Assert.assertEquals(611540L, response.podSequenceNumber) + Assert.assertEquals(0.toByte(), response.rssi) + Assert.assertEquals(0.toByte(), response.receiverLowerGain) + Assert.assertEquals(4294967295L, response.uniqueIdReceivedInCommand) } } \ No newline at end of file From e0e1be01a35cc87889b240a09e84c039f0cadd91 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 27 Feb 2021 01:21:03 +0100 Subject: [PATCH 046/649] Retry for Observables --- .../androidaps/utils/rx/RxExtensions.kt | 21 ++- .../androidaps/utils/rx/RxExtensionsTest.kt | 132 ++++++++++++++++++ .../androidaps/utils/rx/TestSchedulerRule.kt | 31 ++++ 3 files changed, 183 insertions(+), 1 deletion(-) create mode 100644 core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt create mode 100644 core/src/test/java/info/nightscout/androidaps/utils/rx/TestSchedulerRule.kt diff --git a/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt b/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt index 78e2db0e7a..aef2b17e18 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/rx/RxExtensions.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.utils.rx import io.reactivex.Completable import io.reactivex.Flowable +import io.reactivex.Observable import io.reactivex.Single import java.util.concurrent.TimeUnit import kotlin.math.pow @@ -40,4 +41,22 @@ fun Completable.retryExponentialBackoff(retries: Int, time: Long, timeUnit: Time ).flatMap { retryCount: Int -> Flowable.timer(time * 2.toDouble().pow(retryCount.toDouble()).toLong(), timeUnit) } - } \ No newline at end of file + } + +inline fun Observable.retryWithBackoff( + retries: Int, + delay: Long, + timeUnit: TimeUnit, + delayFactor: Double = 1.0 +): Observable = this.retryWhen { + it.zipWith(Observable.range(0, retries + 1), { throwable: Throwable, count: Int -> + if (count >= retries) { + throw throwable + } else { + count + } + }).flatMap { retryCount: Int -> + val actualDelay = (timeUnit.toMillis(delay) * delayFactor.pow(retryCount.toDouble())).toLong() + Observable.timer(actualDelay, TimeUnit.MILLISECONDS) + } +} \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt new file mode 100644 index 0000000000..6e1ec2c7dc --- /dev/null +++ b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt @@ -0,0 +1,132 @@ +package info.nightscout.androidaps.utils.rx + +import io.reactivex.Observable +import io.reactivex.observers.TestObserver +import io.reactivex.schedulers.TestScheduler +import org.junit.Assert.assertEquals +import org.junit.Rule +import org.junit.Test +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +class RxExtensionsTest { + + private val testScheduler = TestScheduler() + + @get:Rule + val schedulerRule = TestSchedulerRule(testScheduler) + + @Test + fun `fail after 4 retries`() { + val atomicInteger = AtomicInteger() + val testObservable: TestObserver = succeedOnObservable(atomicInteger, 5) + .retryWithBackoff(4, 1, TimeUnit.SECONDS) + .test() + assertEquals(1, atomicInteger.get()) // 1st failure + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(3, TimeUnit.SECONDS) // 2nd, 3rd, 4th failure + assertEquals(4, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1, TimeUnit.SECONDS) // 5th failure on 4th retry + assertEquals(5, atomicInteger.get()) + testObservable.assertError(RuntimeException::class.java) + testObservable.assertNever(1) + } + + @Test + fun `succeed after 4 retries`() { + val atomicInteger = AtomicInteger() + val testObservable: TestObserver = succeedOnObservable(atomicInteger, 4) + .retryWithBackoff(4, 1, TimeUnit.SECONDS) + .test() + assertEquals(1, atomicInteger.get()) // 1st failure + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(3, TimeUnit.SECONDS) // 2nd, 3rd, 4th failure + assertEquals(4, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1, TimeUnit.SECONDS) // 5th is a charm + assertEquals(5, atomicInteger.get()) + testObservable.assertValue(1) + } + + @Test + fun `succeed after 4 retries with delay factor`() { + val atomicInteger = AtomicInteger() + val testObservable: TestObserver = succeedOnObservable(atomicInteger, 4) + .retryWithBackoff(4, 1, TimeUnit.SECONDS, delayFactor = 1.2) + .test() + assertEquals(1, atomicInteger.get()) // 1st failure + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS) + assertEquals(1, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS) //1st retry after 1 second + assertEquals(2, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1199, TimeUnit.MILLISECONDS) + assertEquals(2, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS) //2nd retry after 1.2 seconds more + assertEquals(3, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1439, TimeUnit.MILLISECONDS) + assertEquals(3, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS) //3rd retry after 1.44 seconds more + assertEquals(4, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + testScheduler.advanceTimeBy(1726, TimeUnit.MILLISECONDS) + assertEquals(4, atomicInteger.get()) + testObservable.assertNotComplete() + testObservable.assertNotTerminated() + testObservable.assertNever(1) + + //4th retry = 5th try is a charm after 1.728 seconds more - rounding error by 1 millisecond!! + testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS) + assertEquals(5, atomicInteger.get()) + testObservable.assertValue(1) + } + + private fun succeedOnObservable(atomicInteger: AtomicInteger, initialFailures: Int): Observable = + Observable.defer { + if (atomicInteger.incrementAndGet() == initialFailures + 1) { + Observable.just(1) + } else { + Observable.error(RuntimeException()) + } + } + +} \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/utils/rx/TestSchedulerRule.kt b/core/src/test/java/info/nightscout/androidaps/utils/rx/TestSchedulerRule.kt new file mode 100644 index 0000000000..258c89fc91 --- /dev/null +++ b/core/src/test/java/info/nightscout/androidaps/utils/rx/TestSchedulerRule.kt @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.utils.rx + +import io.reactivex.Scheduler +import io.reactivex.android.plugins.RxAndroidPlugins +import io.reactivex.plugins.RxJavaPlugins +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement + +class TestSchedulerRule(val scheduler: Scheduler) : TestRule { + + override fun apply(base: Statement, description: Description) = + object : Statement() { + override fun evaluate() { + RxAndroidPlugins.reset() + RxAndroidPlugins.setInitMainThreadSchedulerHandler { scheduler } + RxJavaPlugins.reset() + RxJavaPlugins.setIoSchedulerHandler { scheduler } + RxJavaPlugins.setNewThreadSchedulerHandler { scheduler } + RxJavaPlugins.setComputationSchedulerHandler { scheduler } + + try { + base.evaluate() + } finally { + RxJavaPlugins.reset() + RxAndroidPlugins.reset() + } + + } + } +} \ No newline at end of file From 937cdaf6beee5d255aefa0f76be74495409bb23c Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 27 Feb 2021 01:26:58 +0100 Subject: [PATCH 047/649] rename scheduler rule --- .../utils/rx/{TestSchedulerRule.kt => RxSchedulerRule.kt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core/src/test/java/info/nightscout/androidaps/utils/rx/{TestSchedulerRule.kt => RxSchedulerRule.kt} (100%) diff --git a/core/src/test/java/info/nightscout/androidaps/utils/rx/TestSchedulerRule.kt b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt similarity index 100% rename from core/src/test/java/info/nightscout/androidaps/utils/rx/TestSchedulerRule.kt rename to core/src/test/java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt From 47bc12d6af9a5c00accde96151255f4dbe155d79 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 27 Feb 2021 01:28:22 +0100 Subject: [PATCH 048/649] rename scheduler rule --- .../info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt | 2 +- .../java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt index 6e1ec2c7dc..2e84af6618 100644 --- a/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxExtensionsTest.kt @@ -14,7 +14,7 @@ class RxExtensionsTest { private val testScheduler = TestScheduler() @get:Rule - val schedulerRule = TestSchedulerRule(testScheduler) + val schedulerRule = RxSchedulerRule(testScheduler) @Test fun `fail after 4 retries`() { diff --git a/core/src/test/java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt index 258c89fc91..3ccdc9dcf4 100644 --- a/core/src/test/java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt +++ b/core/src/test/java/info/nightscout/androidaps/utils/rx/RxSchedulerRule.kt @@ -7,7 +7,7 @@ import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement -class TestSchedulerRule(val scheduler: Scheduler) : TestRule { +class RxSchedulerRule(val scheduler: Scheduler) : TestRule { override fun apply(base: Statement, description: Description) = object : Statement() { From d08a979da3ef20349e824eec915f261837311a03 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sat, 27 Feb 2021 23:21:09 +0100 Subject: [PATCH 049/649] Make OmnipodDashManager.connect() return an Observable of PodEvents --- .../common/viewmodel/ActionViewModelBase.kt | 27 +++++---- .../dash/driver/OmnipodDashManagerImpl.kt | 28 +++------- .../dash/driver/comm/OmnipodDashBleManager.kt | 9 ++- .../driver/comm/OmnipodDashBleManagerImpl.kt | 55 ++++++++++++------- .../comm/exceptions/ScanFailException.kt | 2 +- .../ScanFailFoundTooManyException.kt | 2 +- .../exceptions/ScanFailNotFoundException.kt | 2 +- .../dash/driver/comm/ltk/LTKExchanger.kt | 2 +- .../dash/driver/comm/scan/ScanCollector.kt | 2 +- .../omnipod/dash/driver/event/PodEvent.kt | 11 +++- .../action/DashInitializePodViewModel.kt | 31 ++++++----- .../action/DashInsertCannulaViewModel.kt | 6 +- .../action/DashDeactivatePodViewModel.kt | 6 +- .../action/ErosInitializePodViewModel.kt | 8 ++- .../action/ErosInsertCannulaViewModel.kt | 9 ++- .../action/ErosDeactivatePodViewModel.kt | 24 ++++---- 16 files changed, 126 insertions(+), 98 deletions(-) diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt index 3bc13ff952..290277f77d 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt @@ -2,12 +2,18 @@ package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common. import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult -import io.reactivex.schedulers.Schedulers -import io.reactivex.subjects.SingleSubject +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag +import io.reactivex.Single +import javax.inject.Inject abstract class ActionViewModelBase : ViewModelBase() { + @Inject lateinit var injector: HasAndroidInjector + @Inject lateinit var logger: AAPSLogger + private val _isActionExecutingLiveData = MutableLiveData(false) val isActionExecutingLiveData: LiveData = _isActionExecutingLiveData @@ -16,14 +22,15 @@ abstract class ActionViewModelBase : ViewModelBase() { fun executeAction() { _isActionExecutingLiveData.postValue(true) - SingleSubject.fromCallable(this::doExecuteAction) - .subscribeOn(Schedulers.io()) - .doOnSuccess { result -> - _isActionExecutingLiveData.postValue(false) - _actionResultLiveData.postValue(result) - } - .subscribe() + val disposable = doExecuteAction().subscribe({ result -> + _isActionExecutingLiveData.postValue(false) + _actionResultLiveData.postValue(result) + }, { throwable -> + logger.error(LTag.PUMP, "Caught exception in while executing action in ActionViewModelBase", throwable) + _isActionExecutingLiveData.postValue(false) + _actionResultLiveData.postValue(PumpEnactResult(injector).success(false).comment(throwable.message)) + }) } - protected abstract fun doExecuteAction(): PumpEnactResult + protected abstract fun doExecuteAction(): Single } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 3b3447003b..06966acb19 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -11,6 +11,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import io.reactivex.Observable +import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -30,29 +32,17 @@ class OmnipodDashManagerImpl @Inject constructor( return Observable.error(IllegalStateException("Pod is in an incorrect state")) } - private val observeConnectToPod: Observable - get() { - return Observable.defer { - bleManager.connect() - Observable.just(PodEvent.Connected(0)) // TODO should be returned in BleManager - } - } - override fun activatePodPart1(): Observable { - val command = GetVersionCommand.Builder() // - .setSequenceNumber(podStateManager.messageSequenceNumber) // - .setUniqueId(DEFAULT_UNIQUE_ID) // - .build() - return Observable.concat( observePodReadyForActivationPart1, - observeConnectToPod, - Observable.defer { - bleManager.sendCommand(command) - Observable.just(PodEvent.CommandSent(command)) // TODO should be returned in BleManager - } + bleManager.connect(), + bleManager.sendCommand(GetVersionCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(DEFAULT_UNIQUE_ID) // + .build()) // // ... Send more commands - ) + ).subscribeOn(Schedulers.io()) // + .observeOn(AndroidSchedulers.mainThread()) } override fun activatePodPart2(): Observable { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index ef445e8563..aa0b64e641 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -1,18 +1,17 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response +import io.reactivex.Observable interface OmnipodDashBleManager { - fun sendCommand(cmd: Command): Response + fun sendCommand(cmd: Command): Observable fun getStatus(): ConnectionStatus - fun connect() + fun connect(): Observable fun disconnect() - - fun getPodId(): Id } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 1f88eb69cb..bc795b6fc0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -17,8 +17,10 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk.LTKE import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response +import io.reactivex.Observable +import org.apache.commons.lang3.NotImplementedException import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException @@ -62,8 +64,9 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context return bleIO } - override fun sendCommand(cmd: Command): Response { - TODO("not implemented") + override fun sendCommand(cmd: Command): Observable { + // TODO + return Observable.error(NotImplementedException("sendCommand is not yet implemented")) } override fun getStatus(): ConnectionStatus { @@ -71,30 +74,42 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context } @Throws(InterruptedException::class, ScanFailException::class, FailedToConnectException::class, CouldNotSendBleException::class, BleIOBusyException::class, TimeoutException::class, CouldNotConfirmWriteException::class, CouldNotEnableNotifications::class, DescriptorNotFoundException::class, CouldNotConfirmDescriptorWriteException::class) - override fun connect() { - // TODO: this is wrong and I know it - aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") - val podScanner = PodScanner(aapsLogger, bluetoothAdapter) - val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address - // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; - val bleIO = connect(podAddress) - val msgIO = MessageIO(aapsLogger, bleIO) - val ltkExchanger = LTKExchanger(aapsLogger, msgIO) - val ltk = ltkExchanger.negociateLTKAndNonce() + override fun connect(): Observable = Observable.create { emitter -> + // TODO: when we are already connected, + // emit PodEvent.AlreadyConnected, complete the observable and return from this method - aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") + try { + // TODO: this is wrong and I know it + aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation") + + val podScanner = PodScanner(aapsLogger, bluetoothAdapter) + emitter.onNext(PodEvent.Scanning) + + val podAddress = podScanner.scanForPod(PodScanner.SCAN_FOR_SERVICE_UUID, PodScanner.POD_ID_NOT_ACTIVATED).scanResult.device.address + // For tests: this.podAddress = "B8:27:EB:1D:7E:BB"; + emitter.onNext(PodEvent.BluetoothConnecting) + + val bleIO = connect(podAddress) + emitter.onNext(PodEvent.BluetoothConnected(podAddress)) + + val msgIO = MessageIO(aapsLogger, bleIO) + val ltkExchanger = LTKExchanger(aapsLogger, msgIO) + emitter.onNext(PodEvent.NegotiatingLtkAndNoncePrefix) + + val ltk = ltkExchanger.negotiateLTKAndNonce() + aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") + emitter.onNext(PodEvent.Connected(PodScanner.POD_ID_NOT_ACTIVATED)) // TODO supply actual pod id + + emitter.onComplete() + } catch (ex: Exception) { + emitter.onError(ex) // TODO is this necessary? + } } override fun disconnect() { TODO("not implemented") } - - override fun getPodId(): Id { - // TODO: return something meaningful here - return Id.fromInt(4243); - } - companion object { private const val CONNECT_TIMEOUT_MS = 5000 diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt index ccaaf5a758..396cdffcf4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions open class ScanFailException : Exception { - constructor() + constructor(message: String) : super(message) constructor(errorCode: Int) : super("errorCode$errorCode") } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt index 6f30e90c90..002ecabf3d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.BleDiscoveredDevice import java.util.* -class ScanFailFoundTooManyException(devices: List) : ScanFailException() { +class ScanFailFoundTooManyException(devices: List) : ScanFailException("Found more than one Pod") { private val devices: List = ArrayList(devices) val discoveredDevices: List diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt index 9466ea9b52..55b189baff 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class ScanFailNotFoundException : ScanFailException() \ No newline at end of file +class ScanFailNotFoundException : ScanFailException("No Pod found") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index cd4cdb1540..666c7c0538 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.utils.extensions.hexStringToByteArray internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { - fun negociateLTKAndNonce(): LTK? { + fun negotiateLTKAndNonce(): LTK? { // send SP1, SP2 // TODO: get this from somewhere(preferences?) var seq: Byte = 1 diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt index 95286d9423..658f3b69ff 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt @@ -34,7 +34,7 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S for (result in found.values) { try { result.scanRecord?.let { - val device = BleDiscoveredDevice(result, result.scanRecord, podID) + val device = BleDiscoveredDevice(result, it, podID) ret.add(device) logger.debug(LTag.PUMPBTCOMM, "ScanCollector found: " + result.toString() + "Pod ID: " + podID) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt index e5fe44fb00..2f68033ea5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt @@ -5,10 +5,15 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response. sealed class PodEvent { + /* BT connection events */ + class AlreadyConnected(val uniqueId: Long) : PodEvent() object Scanning : PodEvent() - object Pairing : PodEvent() - object Connecting : PodEvent() - class Connected(val uniqueId: Int) : PodEvent() + object BluetoothConnecting : PodEvent() + class BluetoothConnected(val address: String) : PodEvent() + object NegotiatingLtkAndNoncePrefix : PodEvent() + class Connected(val uniqueId: Long) : PodEvent() + + /* Message exchange events */ class CommandSending(val command: Command) : PodEvent() class CommandSent(val command: Command) : PodEvent() class ResponseReceived(val response: Response) : PodEvent() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index 8715ff9b12..f4781f6a5e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -1,18 +1,15 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager +import io.reactivex.Single import javax.inject.Inject -class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAPSLogger, - private val injector: HasAndroidInjector, - private val omnipodManager: OmnipodDashManager) : InitializePodViewModel() { +class DashInitializePodViewModel @Inject constructor(private val omnipodManager: OmnipodDashManager) : InitializePodViewModel() { override fun isPodInAlarm(): Boolean = false // TODO @@ -20,16 +17,20 @@ class DashInitializePodViewModel @Inject constructor(private val aapsLogger: AAP override fun isPodDeactivatable(): Boolean = true // TODO - override fun doExecuteAction(): PumpEnactResult { - // TODO FIRST STEP OF ACTIVATION - val disposable = omnipodManager.activatePodPart1().subscribe( - { podEvent -> aapsLogger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") }, - { throwable -> aapsLogger.error(LTag.PUMP, "Error in Pod activation part 1: $throwable") }, - { aapsLogger.debug("Pod activation part 1 completed") } - ) - - return PumpEnactResult(injector).success(false).comment("not implemented") - } + override fun doExecuteAction(): Single = + Single.create { source -> + val disposable = omnipodManager.activatePodPart1().subscribe( + { podEvent -> logger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") }, + { throwable -> + logger.error(LTag.PUMP, "Error in Pod activation part 1", throwable) + source.onSuccess(PumpEnactResult(injector).success(false).comment(throwable.message)) + }, + { + logger.debug("Pod activation part 1 completed") + source.onSuccess(PumpEnactResult(injector).success(true)) + } + ) + } @StringRes override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_initialize_pod_title diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt index 0f353b17e8..f3086ffa92 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -1,14 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import io.reactivex.Single import javax.inject.Inject -class DashInsertCannulaViewModel @Inject constructor(private val injector: HasAndroidInjector, private val profileFunction: ProfileFunction) : InsertCannulaViewModel() { +class DashInsertCannulaViewModel @Inject constructor(private val profileFunction: ProfileFunction) : InsertCannulaViewModel() { override fun isPodInAlarm(): Boolean = false // TODO @@ -16,7 +16,7 @@ class DashInsertCannulaViewModel @Inject constructor(private val injector: HasAn override fun isPodDeactivatable(): Boolean = true // TODO - override fun doExecuteAction(): PumpEnactResult = PumpEnactResult(injector) // TODO + override fun doExecuteAction(): Single = Single.just(PumpEnactResult(injector).success(false).comment("TODO")) // TODO @StringRes override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_insert_cannula_title diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt index 093b93fe51..28e773252b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt @@ -1,15 +1,15 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.action import androidx.annotation.StringRes -import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.plugins.pump.omnipod.common.R import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel +import io.reactivex.Single import javax.inject.Inject -class DashDeactivatePodViewModel @Inject constructor(private val injector: HasAndroidInjector) : DeactivatePodViewModel() { +class DashDeactivatePodViewModel @Inject constructor() : DeactivatePodViewModel() { - override fun doExecuteAction(): PumpEnactResult = PumpEnactResult(injector) // TODO + override fun doExecuteAction(): Single = Single.just(PumpEnactResult(injector).success(false).comment("TODO")) // TODO override fun discardPod() { // TODO diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt index e721cdbd6b..a08d79a2b3 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt @@ -7,9 +7,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.R import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager +import io.reactivex.Single import javax.inject.Inject -class ErosInitializePodViewModel @Inject constructor(private val aapsOmnipodManager: AapsOmnipodErosManager, private val podStateManager: AapsErosPodStateManager) : InitializePodViewModel() { +class ErosInitializePodViewModel @Inject constructor( + private val aapsOmnipodManager: AapsOmnipodErosManager, + private val podStateManager: AapsErosPodStateManager +) : InitializePodViewModel() { override fun isPodInAlarm(): Boolean = podStateManager.isPodFaulted @@ -17,7 +21,7 @@ class ErosInitializePodViewModel @Inject constructor(private val aapsOmnipodMana override fun isPodDeactivatable(): Boolean = podStateManager.activationProgress.isAtLeast(ActivationProgress.PAIRING_COMPLETED) - override fun doExecuteAction(): PumpEnactResult = aapsOmnipodManager.initializePod() + override fun doExecuteAction(): Single = Single.just(aapsOmnipodManager.initializePod()) @StringRes override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_initialize_pod_title diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt index bc503baedd..cb7c7c98fb 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt @@ -8,9 +8,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.R import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsErosPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager +import io.reactivex.Single import javax.inject.Inject -class ErosInsertCannulaViewModel @Inject constructor(private val aapsOmnipodManager: AapsOmnipodErosManager, private val podStateManager: AapsErosPodStateManager, private val profileFunction: ProfileFunction) : InsertCannulaViewModel() { +class ErosInsertCannulaViewModel @Inject constructor( + private val aapsOmnipodManager: AapsOmnipodErosManager, + private val podStateManager: AapsErosPodStateManager, + private val profileFunction: ProfileFunction +) : InsertCannulaViewModel() { override fun isPodInAlarm(): Boolean = podStateManager.isPodFaulted @@ -18,7 +23,7 @@ class ErosInsertCannulaViewModel @Inject constructor(private val aapsOmnipodMana override fun isPodDeactivatable(): Boolean = podStateManager.activationProgress.isAtLeast(ActivationProgress.PAIRING_COMPLETED) - override fun doExecuteAction(): PumpEnactResult = aapsOmnipodManager.insertCannula(profileFunction.getProfile()) + override fun doExecuteAction(): Single = Single.just(aapsOmnipodManager.insertCannula(profileFunction.getProfile())) @StringRes override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_insert_cannula_title diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt index fad491a5f5..099aa87bf0 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt @@ -8,20 +8,22 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.Comm import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager import info.nightscout.androidaps.queue.Callback -import io.reactivex.subjects.SingleSubject +import io.reactivex.Single import javax.inject.Inject -class ErosDeactivatePodViewModel @Inject constructor(private val aapsOmnipodManager: AapsOmnipodErosManager, private val commandQueueProvider: CommandQueueProvider) : DeactivatePodViewModel() { +class ErosDeactivatePodViewModel @Inject constructor( + private val aapsOmnipodManager: AapsOmnipodErosManager, + private val commandQueueProvider: CommandQueueProvider +) : DeactivatePodViewModel() { - override fun doExecuteAction(): PumpEnactResult { - val singleSubject = SingleSubject.create() - commandQueueProvider.customCommand(CommandDeactivatePod(), object : Callback() { - override fun run() { - singleSubject.onSuccess(result) - } - }) - return singleSubject.blockingGet() - } + override fun doExecuteAction(): Single = + Single.create { source -> + commandQueueProvider.customCommand(CommandDeactivatePod(), object : Callback() { + override fun run() { + source.onSuccess(result) + } + }) + } override fun discardPod() { aapsOmnipodManager.discardPodState() From 7e5667705d9d8c5d5b364494d9915e5028e17a10 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sat, 27 Feb 2021 23:46:57 +0100 Subject: [PATCH 050/649] Minor improvement --- .../pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 06966acb19..1721dfd8a7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -25,11 +25,12 @@ class OmnipodDashManagerImpl @Inject constructor( ) : OmnipodDashManager { private val observePodReadyForActivationPart1: Observable - get() { + get() = Observable.defer { if (podStateManager.activationProgress.isBefore(ActivationProgress.PHASE_1_COMPLETED)) { - return Observable.empty() + Observable.empty() + } else { + Observable.error(IllegalStateException("Pod is in an incorrect state")) } - return Observable.error(IllegalStateException("Pod is in an incorrect state")) } override fun activatePodPart1(): Observable { From 86d965a7f135e1bd8458605dc2538f52cc8e0574 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sat, 27 Feb 2021 23:50:51 +0100 Subject: [PATCH 051/649] initial history database --- omnipod-dash/build.gradle | 7 +++ .../dash/dagger/OmnipodDashHistoryModule.kt | 33 +++++++++++ .../omnipod/dash/dagger/OmnipodDashModule.kt | 2 +- .../pump/omnipod/dash/history/DashHistory.kt | 55 +++++++++++++++++++ .../dash/history/data/HistoryRecord.kt | 13 +++++ .../pump/omnipod/dash/history/data/Record.kt | 11 ++++ .../omnipod/dash/history/data/ResultStates.kt | 9 +++ .../dash/history/database/Converters.kt | 34 ++++++++++++ .../history/database/DashHistoryDatabase.kt | 31 +++++++++++ .../dash/history/database/HistoryRecordDao.kt | 36 ++++++++++++ .../history/database/HistoryRecordEntity.kt | 22 ++++++++ .../dash/history/mapper/HistoryMapper.kt | 32 +++++++++++ 12 files changed, 284 insertions(+), 1 deletion(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt diff --git a/omnipod-dash/build.gradle b/omnipod-dash/build.gradle index ea8c60af66..45c11a93bf 100644 --- a/omnipod-dash/build.gradle +++ b/omnipod-dash/build.gradle @@ -17,4 +17,11 @@ android { dependencies { implementation project(':core') implementation project(':omnipod-common') + + implementation "androidx.room:room-runtime:$room_version" + implementation "androidx.room:room-rxjava2:$room_version" + kapt "androidx.room:room-compiler:$room_version" + + implementation 'com.github.guepardoapps:kulid:1.1.2.0' + } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt new file mode 100644 index 0000000000..172dd497b0 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt @@ -0,0 +1,33 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.dagger + +import android.content.Context +import dagger.Module +import dagger.Provides +import dagger.Reusable +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.DashHistory +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.DashHistoryDatabase +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordDao +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper.HistoryMapper +import javax.inject.Singleton + +@Module +class OmnipodDashHistoryModule { + + @Provides + @Singleton + internal fun provideDatabase(context: Context): DashHistoryDatabase = DashHistoryDatabase.build(context) + + @Provides + @Singleton + internal fun provideHistoryRecordDao(dashHistoryDatabase: DashHistoryDatabase): HistoryRecordDao = dashHistoryDatabase.historyRecordDao() + + @Provides + @Reusable // no state, let system decide when to reuse or create new. + internal fun provideHistoryMapper() = HistoryMapper() + + @Provides + @Singleton + internal fun provideDashHistory(dao: HistoryRecordDao, historyMapper: HistoryMapper) = + DashHistory(dao, historyMapper) + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index a67a8dd570..98780b10d9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.OmnipodDashOvervi import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.DashPodActivationWizardActivity import info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.DashPodDeactivationWizardActivity -@Module +@Module(includes = [OmnipodDashHistoryModule::class]) @Suppress("unused") abstract class OmnipodDashModule { // ACTIVITIES diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt new file mode 100644 index 0000000000..98319550ed --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt @@ -0,0 +1,55 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history + +import com.github.guepardoapps.kulid.ULID +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.BolusRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.HistoryRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.InitialResult +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.ResolvedResult +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.TempBasalRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordDao +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordEntity +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper.HistoryMapper +import io.reactivex.Completable +import io.reactivex.Single +import java.lang.System.currentTimeMillis +import javax.inject.Inject + +class DashHistory @Inject constructor( + private val dao: HistoryRecordDao, + private val historyMapper: HistoryMapper +) { + + fun markSuccess(id: String): Completable = dao.markResolved(id, ResolvedResult.SUCCESS, currentTimeMillis()) + + fun markFailure(id: String): Completable = dao.markResolved(id, ResolvedResult.FAILURE, currentTimeMillis()) + + fun createRecord( + commandType: OmnipodCommandType, + initialResult: InitialResult = InitialResult.UNCONFIRMED, + tempBasalRecord: TempBasalRecord? = null, + bolusRecord: BolusRecord? = null, + resolveResult: ResolvedResult? = null, + resolvedAt: Long? = null + ): Single { + val id = ULID.random() + return dao.save( + HistoryRecordEntity( + id = id, + createdAt = currentTimeMillis(), + commandType = commandType, + tempBasalRecord = tempBasalRecord, + bolusRecord = bolusRecord, + initialResult = initialResult, + resolvedResult = resolveResult, + resolvedAt = resolvedAt, + ) + ).toSingle { id } + } + + fun getRecords(): Single> = + dao.all().map { list -> list.map(historyMapper::entityToDomain) } + + fun getRecordsAfter(time: Long): Single> = dao.allSince(time) + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt new file mode 100644 index 0000000000..5229248a7e --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data + +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType + +data class HistoryRecord( + val id: String, // ULID + val createdAt: Long, + val commandType: OmnipodCommandType, + val initialResult: InitialResult, + val record: Record?, + val resolvedResult: ResolvedResult?, + val resolvedAt: Long? +) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt new file mode 100644 index 0000000000..6344c9fcd7 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data + +sealed class Record + +data class BolusRecord(val amout: Double, val bolusType: BolusType): Record() + +data class TempBasalRecord(val duration: Long, val rate: Double): Record() + +enum class BolusType { + DEFAULT, SMB +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt new file mode 100644 index 0000000000..53dc608e60 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data + +enum class InitialResult { + SUCCESS, FAILURE, UNCONFIRMED +} + +enum class ResolvedResult { + SUCCESS, FAILURE +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt new file mode 100644 index 0000000000..b37d71bf3f --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt @@ -0,0 +1,34 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database + +import androidx.room.TypeConverter +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.BolusType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.InitialResult +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.ResolvedResult + +class Converters { + + @TypeConverter + fun toBolusType(s: String) = enumValueOf(s) + + @TypeConverter + fun fromBolusType(bolusType: BolusType) = bolusType.name + + @TypeConverter + fun toInitialResult(s: String) = enumValueOf(s) + + @TypeConverter + fun fromInitialResult(initialResult: InitialResult) = initialResult.name + + @TypeConverter + fun toResolvedResult(s: String) = enumValueOf(s) + + @TypeConverter + fun fromResolvedResult(resolvedResult: ResolvedResult) = resolvedResult.name + + @TypeConverter + fun toOmnipodCommandType(s: String) = enumValueOf(s) + + @TypeConverter + fun fromOmnipodCommandType(omnipodCommandType: OmnipodCommandType) = omnipodCommandType.name +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt new file mode 100644 index 0000000000..259447afb0 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt @@ -0,0 +1,31 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database + +import android.content.Context +import androidx.room.Database +import androidx.room.Room +import androidx.room.RoomDatabase +import androidx.room.TypeConverters + +@Database( + entities = [HistoryRecordEntity::class], + exportSchema = false, + version = DashHistoryDatabase.VERSION +) +@TypeConverters(Converters::class) +abstract class DashHistoryDatabase : RoomDatabase() { + + abstract fun historyRecordDao() : HistoryRecordDao + + companion object { + + const val VERSION = 1 + + @Synchronized + fun build(context: Context) = + Room.databaseBuilder(context.applicationContext, DashHistoryDatabase::class.java, "omnipod_dash_history_database.db") + .fallbackToDestructiveMigration() + .build() + + } + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt new file mode 100644 index 0000000000..e5c425dd24 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt @@ -0,0 +1,36 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database + +import androidx.room.Dao +import androidx.room.Delete +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.ResolvedResult +import io.reactivex.Completable +import io.reactivex.Single + +@Dao +abstract class HistoryRecordDao { + + @Query("SELECT * from historyrecords") + abstract fun all(): Single> + + @Query("SELECT * from historyrecords") + abstract fun allBlocking(): List + + @Query("SELECT * from historyrecords WHERE createdAt <= :since") + abstract fun allSince(since: Long): Single> + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun saveBlocking(historyRecordEntity: HistoryRecordEntity) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + abstract fun save(historyRecordEntity: HistoryRecordEntity): Completable + + @Delete + abstract fun delete(historyRecordEntity: HistoryRecordEntity): Completable + + @Query("UPDATE historyrecords SET resolvedResult = :resolvedResult, resolvedAt = :resolvedAt WHERE id = :id ") + abstract fun markResolved(id: String, resolvedResult: ResolvedResult, resolvedAt: Long): Completable + +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt new file mode 100644 index 0000000000..6539009117 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database + +import androidx.room.Embedded +import androidx.room.Entity +import androidx.room.PrimaryKey +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.BolusRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.InitialResult +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.ResolvedResult +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.TempBasalRecord + +@Entity(tableName = "historyrecords") +data class HistoryRecordEntity( + @PrimaryKey val id: String, // ULID + val createdAt: Long, + val commandType: OmnipodCommandType, + val initialResult: InitialResult, + @Embedded(prefix = "tempBasalRecord_") val tempBasalRecord: TempBasalRecord?, + @Embedded(prefix = "bolusRecord_") val bolusRecord: BolusRecord?, + val resolvedResult: ResolvedResult?, + val resolvedAt: Long?) + diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt new file mode 100644 index 0000000000..6ceeb6920c --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.BolusRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.HistoryRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.TempBasalRecord +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordEntity + +class HistoryMapper { + + fun domainToEntity(historyRecord: HistoryRecord): HistoryRecordEntity = + HistoryRecordEntity( + id = historyRecord.id, + createdAt = historyRecord.createdAt, + commandType = historyRecord.commandType, + initialResult = historyRecord.initialResult, + tempBasalRecord = historyRecord.record as? TempBasalRecord, + bolusRecord = historyRecord.record as? BolusRecord, + resolvedResult = historyRecord.resolvedResult, + resolvedAt = historyRecord.resolvedAt + ) + + fun entityToDomain(entity: HistoryRecordEntity): HistoryRecord = + HistoryRecord(id = entity.id, + createdAt = entity.createdAt, + initialResult = entity.initialResult, + commandType = entity.commandType, + record = entity.bolusRecord ?: entity.tempBasalRecord, + resolvedResult = entity.resolvedResult, + resolvedAt = entity.resolvedAt + ) + +} \ No newline at end of file From 8d629977ec6ea7a9d8928786ae39782423db2cfc Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sat, 27 Feb 2021 23:52:06 +0100 Subject: [PATCH 052/649] Improvement --- .../pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 1721dfd8a7..8497b92a87 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -37,10 +37,12 @@ class OmnipodDashManagerImpl @Inject constructor( return Observable.concat( observePodReadyForActivationPart1, bleManager.connect(), - bleManager.sendCommand(GetVersionCommand.Builder() // - .setSequenceNumber(podStateManager.messageSequenceNumber) // - .setUniqueId(DEFAULT_UNIQUE_ID) // - .build()) // + Observable.defer { + bleManager.sendCommand(GetVersionCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(DEFAULT_UNIQUE_ID) // + .build()) // + } // ... Send more commands ).subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) From 634b9c20e76b267efc8948a562cf52fc08dde277 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 00:42:32 +0100 Subject: [PATCH 053/649] Add interceptors for PodEvents and errors --- .../dash/driver/OmnipodDashManagerImpl.kt | 75 ++++++++++++++++++- .../omnipod/dash/driver/event/PodEvent.kt | 2 +- .../pod/state/OmnipodDashPodStateManager.kt | 4 +- .../state/OmnipodDashPodStateManagerImpl.kt | 20 ++++- 4 files changed, 93 insertions(+), 8 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 8497b92a87..e4c18b1d13 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand @@ -9,9 +10,14 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers +import io.reactivex.functions.Consumer import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject @@ -19,7 +25,7 @@ import javax.inject.Singleton @Singleton class OmnipodDashManagerImpl @Inject constructor( - private val aapsLogger: AAPSLogger, + private val logger: AAPSLogger, private val podStateManager: OmnipodDashPodStateManager, private val bleManager: OmnipodDashBleManager ) : OmnipodDashManager { @@ -33,10 +39,13 @@ class OmnipodDashManagerImpl @Inject constructor( } } + private val connectToPod: Observable + get() = Observable.defer { bleManager.connect() } + override fun activatePodPart1(): Observable { return Observable.concat( observePodReadyForActivationPart1, - bleManager.connect(), + connectToPod, Observable.defer { bleManager.sendCommand(GetVersionCommand.Builder() // .setSequenceNumber(podStateManager.messageSequenceNumber) // @@ -44,7 +53,11 @@ class OmnipodDashManagerImpl @Inject constructor( .build()) // } // ... Send more commands - ).subscribeOn(Schedulers.io()) // + ) // + // TODO these would be common for any observable returned in a public function in this class + .doOnNext(PodEventInterceptor()) // + .doOnError(ErrorInterceptor()) + .subscribeOn(Schedulers.io()) // .observeOn(AndroidSchedulers.mainThread()) } @@ -112,4 +125,60 @@ class OmnipodDashManagerImpl @Inject constructor( // TODO return Observable.empty() } + + inner class PodEventInterceptor : Consumer { + + // TODO split into separate methods + override fun accept(event: PodEvent) { + logger.debug(LTag.PUMP, "Intercepted PodEvent in OmnipodDashManagerImpl: ${event.javaClass.simpleName}") + when (event) { + is PodEvent.AlreadyConnected -> { + podStateManager.bluetoothAddress = event.bluetoothAddress + podStateManager.uniqueId = event.uniqueId + } + + is PodEvent.BluetoothConnected -> { + podStateManager.bluetoothAddress = event.address + } + + is PodEvent.Connected -> { + podStateManager.uniqueId = event.uniqueId + } + + is PodEvent.ResponseReceived -> { + podStateManager.increaseMessageSequenceNumber() + when (event.response) { + is VersionResponse -> { + podStateManager.updateFromVersionResponse(event.response) + } + + is SetUniqueIdResponse -> { + podStateManager.updateFromSetUniqueIdResponse(event.response) + } + + is DefaultStatusResponse -> { + podStateManager.updateFromDefaultStatusResponse(event.response) + } + + is AlarmStatusResponse -> { + podStateManager.updateFromAlarmStatusResponse(event.response) + } + } + } + + else -> { + // Do nothing + } + } + } + + } + + inner class ErrorInterceptor : Consumer { + + override fun accept(throwable: Throwable) { + logger.debug(LTag.PUMP, "Intercepted error in OmnipodDashManagerImpl: ${throwable.javaClass.simpleName}") + } + + } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt index 2f68033ea5..25386ca32a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response. sealed class PodEvent { /* BT connection events */ - class AlreadyConnected(val uniqueId: Long) : PodEvent() + class AlreadyConnected(val bluetoothAddress: String, val uniqueId: Long) : PodEvent() object Scanning : PodEvent() object BluetoothConnecting : PodEvent() class BluetoothConnected(val address: String) : PodEvent() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index 85e959d5ec..bcfe894f5e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -21,8 +21,8 @@ interface OmnipodDashPodStateManager { val messageSequenceNumber: Short val sequenceNumberOfLastProgrammingCommand: Short? val activationTime: Long? - val uniqueId: Long? - val bluetoothAddress: String? + var uniqueId: Long? + var bluetoothAddress: String? val bluetoothVersion: SoftwareVersion? val firmwareVersion: SoftwareVersion? diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index 5fd48d82b4..bfc345801f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -68,11 +68,27 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( override val activationTime: Long? get() = podState.activationTime - override val uniqueId: Long? + override var uniqueId: Long? get() = podState.uniqueId + set(uniqueId) { + if (podState.uniqueId == null) { + podState.uniqueId = uniqueId + store() + } else if (uniqueId != podState.uniqueId) { + throw IllegalStateException("Trying to set Unique ID to $uniqueId, but it is already set to ${podState.uniqueId}") + } + } - override val bluetoothAddress: String? + override var bluetoothAddress: String? get() = podState.bluetoothAddress + set(bluetoothAddress) { + if (podState.bluetoothAddress == null) { + podState.bluetoothAddress = bluetoothAddress + store() + } else if (bluetoothAddress != podState.bluetoothAddress) { + throw IllegalStateException("Trying to set Bluetooth Address to $bluetoothAddress, but it is already set to ${podState.bluetoothAddress}") + } + } override val bluetoothVersion: SoftwareVersion? get() = podState.bleVersion From 2d0d38f70f20aa85ade4d914820d6ccd109a69d2 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sun, 28 Feb 2021 03:30:13 +0100 Subject: [PATCH 054/649] database integration test working --- gradle/test_dependencies.gradle | 13 ++++- .../omnipod/dash/history/DashHistoryTest.kt | 58 +++++++++++++++++++ .../omnipod/dash/history/RxSchedulerRule.kt | 32 ++++++++++ .../pump/omnipod/dash/history/DashHistory.kt | 10 +++- .../dash/history/data/HistoryRecord.kt | 1 + .../dash/history/database/Converters.kt | 4 +- .../history/database/DashHistoryDatabase.kt | 3 +- 7 files changed, 111 insertions(+), 10 deletions(-) create mode 100644 omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt create mode 100644 omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt diff --git a/gradle/test_dependencies.gradle b/gradle/test_dependencies.gradle index 3a484c419c..881e535d9d 100644 --- a/gradle/test_dependencies.gradle +++ b/gradle/test_dependencies.gradle @@ -13,9 +13,16 @@ dependencies { testImplementation "org.skyscreamer:jsonassert:1.5.0" testImplementation "org.hamcrest:hamcrest-all:1.3" - androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0-alpha04' - androidTestImplementation "androidx.test.ext:junit:$androidx_junit" - androidTestImplementation "androidx.test:rules:$androidx_rules" + + // newer integration test libraries might not work + // https://stackoverflow.com/questions/64700104/attribute-androidforcequeryable-not-found-in-android-studio-when-running-espres + androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' + androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.3.0' + + androidTestImplementation 'androidx.test.ext:junit:1.1.2' + androidTestImplementation 'androidx.test:rules:1.3.0' + androidTestImplementation 'androidx.test:runner:1.3.0' + androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' } diff --git a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt new file mode 100644 index 0000000000..28467f7a59 --- /dev/null +++ b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt @@ -0,0 +1,58 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history + +import android.content.Context +import androidx.room.Room +import androidx.test.core.app.ApplicationProvider +import androidx.test.ext.junit.runners.AndroidJUnit4 +import com.github.guepardoapps.kulid.ULID +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.DashHistoryDatabase +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordDao +import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper.HistoryMapper +import io.reactivex.schedulers.Schedulers +import org.junit.After +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class DashHistoryTest { + + private lateinit var dao: HistoryRecordDao + private lateinit var database: DashHistoryDatabase + private lateinit var dashHistory: DashHistory + + @get:Rule + val schedulerRule = RxSchedulerRule(Schedulers.trampoline()) + + @Before + fun setUp() { + val context = ApplicationProvider.getApplicationContext() + database = Room.inMemoryDatabaseBuilder( + context, DashHistoryDatabase::class.java).build() + dao = database.historyRecordDao() + dashHistory = DashHistory(dao, HistoryMapper()) + } + + @Test + fun testInsertSomething() { // needs to be camel case as runs on Android + dashHistory.getRecords().test().apply { + assertValue { it.isEmpty() } + } + + dashHistory.createRecord(commandType = OmnipodCommandType.SET_BOLUS).test().apply { + assertValue { ULID.isValid(it) } + } + + dashHistory.getRecords().test().apply { + assertValue { it.size == 1 } + } + + } + + @After + fun tearDown() { + database.close() + } +} \ No newline at end of file diff --git a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt new file mode 100644 index 0000000000..6073957e5f --- /dev/null +++ b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.history + +import io.reactivex.Scheduler +import io.reactivex.android.plugins.RxAndroidPlugins +import io.reactivex.plugins.RxJavaPlugins +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement + +// TODO: move to core before the big merge +class RxSchedulerRule(val scheduler: Scheduler) : TestRule { + + override fun apply(base: Statement, description: Description) = + object : Statement() { + override fun evaluate() { + RxAndroidPlugins.reset() + RxAndroidPlugins.setInitMainThreadSchedulerHandler { scheduler } + RxJavaPlugins.reset() + RxJavaPlugins.setIoSchedulerHandler { scheduler } + RxJavaPlugins.setNewThreadSchedulerHandler { scheduler } + RxJavaPlugins.setComputationSchedulerHandler { scheduler } + + try { + base.evaluate() + } finally { + RxJavaPlugins.reset() + RxAndroidPlugins.reset() + } + + } + } +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt index 98319550ed..e2ebf8f94d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt @@ -20,9 +20,9 @@ class DashHistory @Inject constructor( private val historyMapper: HistoryMapper ) { - fun markSuccess(id: String): Completable = dao.markResolved(id, ResolvedResult.SUCCESS, currentTimeMillis()) + fun markSuccess(id: String): Completable = dao.markResolved(id, ResolvedResult.SUCCESS, currentTimeMillis()) // TODO pass time - fun markFailure(id: String): Completable = dao.markResolved(id, ResolvedResult.FAILURE, currentTimeMillis()) + fun markFailure(id: String): Completable = dao.markResolved(id, ResolvedResult.FAILURE, currentTimeMillis()) // TODO pass time fun createRecord( commandType: OmnipodCommandType, @@ -33,10 +33,14 @@ class DashHistory @Inject constructor( resolvedAt: Long? = null ): Single { val id = ULID.random() + + // TODO: verify that on OmnipodCommandType.SET_BOLUS bolusRecord is not null? + // TODO: verify that on SET_TEMPORARY_BASAL tempBasalRecord is not null + return dao.save( HistoryRecordEntity( id = id, - createdAt = currentTimeMillis(), + createdAt = currentTimeMillis(), // TODO pass time (as date, keep createdAt) commandType = commandType, tempBasalRecord = tempBasalRecord, bolusRecord = bolusRecord, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt index 5229248a7e..3993d8de73 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt @@ -4,6 +4,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.Omnipod data class HistoryRecord( val id: String, // ULID + // TODO add date val createdAt: Long, val commandType: OmnipodCommandType, val initialResult: InitialResult, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt index b37d71bf3f..2395695f1e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt @@ -21,10 +21,10 @@ class Converters { fun fromInitialResult(initialResult: InitialResult) = initialResult.name @TypeConverter - fun toResolvedResult(s: String) = enumValueOf(s) + fun toResolvedResult(s: String?) = s?.let { enumValueOf(it) } @TypeConverter - fun fromResolvedResult(resolvedResult: ResolvedResult) = resolvedResult.name + fun fromResolvedResult(resolvedResult: ResolvedResult?) = resolvedResult?.name @TypeConverter fun toOmnipodCommandType(s: String) = enumValueOf(s) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt index 259447afb0..75b21716ba 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt @@ -5,6 +5,7 @@ import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters +import androidx.room.migration.Migration @Database( entities = [HistoryRecordEntity::class], @@ -20,12 +21,10 @@ abstract class DashHistoryDatabase : RoomDatabase() { const val VERSION = 1 - @Synchronized fun build(context: Context) = Room.databaseBuilder(context.applicationContext, DashHistoryDatabase::class.java, "omnipod_dash_history_database.db") .fallbackToDestructiveMigration() .build() - } } \ No newline at end of file From 6dce871ed459329545e86662eb0a0507fbc56568 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sun, 28 Feb 2021 03:55:01 +0100 Subject: [PATCH 055/649] fix database --- .../omnipod/dash/history/DashHistoryTest.kt | 18 +++++++++++++++-- .../pump/omnipod/dash/history/DashHistory.kt | 20 ++++++++++++++----- .../dash/history/data/HistoryRecord.kt | 4 ++-- .../history/database/HistoryRecordEntity.kt | 3 ++- .../dash/history/mapper/HistoryMapper.kt | 4 +++- 5 files changed, 38 insertions(+), 11 deletions(-) diff --git a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt index 28467f7a59..9edd38f85e 100644 --- a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt +++ b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt @@ -36,19 +36,33 @@ class DashHistoryTest { } @Test - fun testInsertSomething() { // needs to be camel case as runs on Android + fun testInsertionAndConverters() { dashHistory.getRecords().test().apply { assertValue { it.isEmpty() } } - dashHistory.createRecord(commandType = OmnipodCommandType.SET_BOLUS).test().apply { + dashHistory.createRecord(commandType = OmnipodCommandType.CANCEL_BOLUS, 0L).test().apply { assertValue { ULID.isValid(it) } } dashHistory.getRecords().test().apply { assertValue { it.size == 1 } } + } + @Test + fun testExceptionOnBolusWithoutRecord() { + dashHistory.getRecords().test().apply { + assertValue { it.isEmpty() } + } + + dashHistory.createRecord(commandType = OmnipodCommandType.SET_BOLUS, 0L).test().apply { + assertError(IllegalArgumentException::class.java) + } + + dashHistory.getRecords().test().apply { + assertValue { it.isEmpty() } + } } @After diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt index e2ebf8f94d..d02d1141f9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt @@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.history import com.github.guepardoapps.kulid.ULID import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType.SET_BOLUS +import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType.SET_TEMPORARY_BASAL import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.BolusRecord import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.HistoryRecord import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.InitialResult @@ -20,12 +22,13 @@ class DashHistory @Inject constructor( private val historyMapper: HistoryMapper ) { - fun markSuccess(id: String): Completable = dao.markResolved(id, ResolvedResult.SUCCESS, currentTimeMillis()) // TODO pass time + fun markSuccess(id: String, date: Long): Completable = dao.markResolved(id, ResolvedResult.SUCCESS, currentTimeMillis()) - fun markFailure(id: String): Completable = dao.markResolved(id, ResolvedResult.FAILURE, currentTimeMillis()) // TODO pass time + fun markFailure(id: String, date: Long): Completable = dao.markResolved(id, ResolvedResult.FAILURE, currentTimeMillis()) fun createRecord( commandType: OmnipodCommandType, + date: Long, initialResult: InitialResult = InitialResult.UNCONFIRMED, tempBasalRecord: TempBasalRecord? = null, bolusRecord: BolusRecord? = null, @@ -34,13 +37,20 @@ class DashHistory @Inject constructor( ): Single { val id = ULID.random() - // TODO: verify that on OmnipodCommandType.SET_BOLUS bolusRecord is not null? - // TODO: verify that on SET_TEMPORARY_BASAL tempBasalRecord is not null + when { + commandType == SET_BOLUS && bolusRecord == null -> + Single.error(IllegalArgumentException("bolusRecord missing on SET_BOLUS")) + commandType == SET_TEMPORARY_BASAL && tempBasalRecord == null -> + Single.error(IllegalArgumentException("tempBasalRecord missing on SET_TEMPORARY_BASAL")) + else -> null + }?.let { return it } + return dao.save( HistoryRecordEntity( id = id, - createdAt = currentTimeMillis(), // TODO pass time (as date, keep createdAt) + date = date, + createdAt = currentTimeMillis(), commandType = commandType, tempBasalRecord = tempBasalRecord, bolusRecord = bolusRecord, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt index 3993d8de73..56aa2dc6b2 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/HistoryRecord.kt @@ -4,8 +4,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.Omnipod data class HistoryRecord( val id: String, // ULID - // TODO add date - val createdAt: Long, + val createdAt: Long, // creation date of the record + val date: Long, // when event actually happened val commandType: OmnipodCommandType, val initialResult: InitialResult, val record: Record?, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt index 6539009117..4eea309c5a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt @@ -12,7 +12,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.TempBas @Entity(tableName = "historyrecords") data class HistoryRecordEntity( @PrimaryKey val id: String, // ULID - val createdAt: Long, + val createdAt: Long, // creation date of the record + val date: Long, // when event actually happened val commandType: OmnipodCommandType, val initialResult: InitialResult, @Embedded(prefix = "tempBasalRecord_") val tempBasalRecord: TempBasalRecord?, diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt index 6ceeb6920c..e3eeb39320 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt @@ -11,17 +11,19 @@ class HistoryMapper { HistoryRecordEntity( id = historyRecord.id, createdAt = historyRecord.createdAt, + date = historyRecord.date, commandType = historyRecord.commandType, initialResult = historyRecord.initialResult, tempBasalRecord = historyRecord.record as? TempBasalRecord, bolusRecord = historyRecord.record as? BolusRecord, resolvedResult = historyRecord.resolvedResult, - resolvedAt = historyRecord.resolvedAt + resolvedAt = historyRecord.resolvedAt, ) fun entityToDomain(entity: HistoryRecordEntity): HistoryRecord = HistoryRecord(id = entity.id, createdAt = entity.createdAt, + date = entity.date, initialResult = entity.initialResult, commandType = entity.commandType, record = entity.bolusRecord ?: entity.tempBasalRecord, From 76756fabaa4ada64a0ae687562e0418eb53f452e Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Sun, 28 Feb 2021 14:18:17 +0100 Subject: [PATCH 056/649] a bit more readable --- .../pump/omnipod/dash/history/DashHistory.kt | 30 ++++++++----------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt index d02d1141f9..b5c1c5367d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt @@ -39,25 +39,21 @@ class DashHistory @Inject constructor( when { commandType == SET_BOLUS && bolusRecord == null -> - Single.error(IllegalArgumentException("bolusRecord missing on SET_BOLUS")) + return Single.error(IllegalArgumentException("bolusRecord missing on SET_BOLUS")) commandType == SET_TEMPORARY_BASAL && tempBasalRecord == null -> - Single.error(IllegalArgumentException("tempBasalRecord missing on SET_TEMPORARY_BASAL")) - else -> null - }?.let { return it } + return Single.error(IllegalArgumentException("tempBasalRecord missing on SET_TEMPORARY_BASAL")) + } - - return dao.save( - HistoryRecordEntity( - id = id, - date = date, - createdAt = currentTimeMillis(), - commandType = commandType, - tempBasalRecord = tempBasalRecord, - bolusRecord = bolusRecord, - initialResult = initialResult, - resolvedResult = resolveResult, - resolvedAt = resolvedAt, - ) + return dao.save(HistoryRecordEntity( + id = id, + date = date, + createdAt = currentTimeMillis(), + commandType = commandType, + tempBasalRecord = tempBasalRecord, + bolusRecord = bolusRecord, + initialResult = initialResult, + resolvedResult = resolveResult, + resolvedAt = resolvedAt) ).toSingle { id } } From aa14843d33f9edb63f97f6d5e0547fef38506515 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 15:18:10 +0100 Subject: [PATCH 057/649] Address review findings --- .../action/InitializePodViewModel.kt | 8 ++- .../action/InsertCannulaViewModel.kt | 8 ++- .../PodActivationActionViewModelBase.kt | 7 +- .../common/viewmodel/ActionViewModelBase.kt | 9 ++- .../action/DeactivatePodViewModel.kt | 7 +- .../dash/driver/OmnipodDashManagerImpl.kt | 68 ++++++++++--------- .../driver/comm/OmnipodDashBleManagerImpl.kt | 4 +- .../dash/driver/comm/scan/PodScanner.kt | 2 +- .../omnipod/dash/driver/event/PodEvent.kt | 4 +- .../state/OmnipodDashPodStateManagerImpl.kt | 2 - .../action/DashInitializePodViewModel.kt | 17 +++-- .../action/DashInsertCannulaViewModel.kt | 8 ++- .../action/DashDeactivatePodViewModel.kt | 7 +- .../action/ErosInitializePodViewModel.kt | 8 ++- .../action/ErosInsertCannulaViewModel.kt | 8 ++- .../action/ErosDeactivatePodViewModel.kt | 8 ++- 16 files changed, 116 insertions(+), 59 deletions(-) diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InitializePodViewModel.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InitializePodViewModel.kt index fcaf143c99..1b394cf7d8 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InitializePodViewModel.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InitializePodViewModel.kt @@ -1,3 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action -abstract class InitializePodViewModel : PodActivationActionViewModelBase() \ No newline at end of file +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.logging.AAPSLogger + +abstract class InitializePodViewModel( + injector: HasAndroidInjector, + logger: AAPSLogger +) : PodActivationActionViewModelBase(injector, logger) \ No newline at end of file diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InsertCannulaViewModel.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InsertCannulaViewModel.kt index 73ebaa7bee..a07ce28eab 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InsertCannulaViewModel.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/InsertCannulaViewModel.kt @@ -1,3 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action -abstract class InsertCannulaViewModel : PodActivationActionViewModelBase() \ No newline at end of file +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.logging.AAPSLogger + +abstract class InsertCannulaViewModel( + injector: HasAndroidInjector, + logger: AAPSLogger +) : PodActivationActionViewModelBase(injector, logger) \ No newline at end of file diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/PodActivationActionViewModelBase.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/PodActivationActionViewModelBase.kt index 2f5d8b2f51..b71ede17bf 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/PodActivationActionViewModelBase.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/activation/viewmodel/action/PodActivationActionViewModelBase.kt @@ -1,8 +1,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.viewmodel.ActionViewModelBase -abstract class PodActivationActionViewModelBase : ActionViewModelBase() { +abstract class PodActivationActionViewModelBase( + injector: HasAndroidInjector, + logger: AAPSLogger +) : ActionViewModelBase(injector, logger) { abstract fun isPodInAlarm(): Boolean diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt index 290277f77d..23f175ae1d 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt @@ -7,12 +7,11 @@ import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import io.reactivex.Single -import javax.inject.Inject -abstract class ActionViewModelBase : ViewModelBase() { - - @Inject lateinit var injector: HasAndroidInjector - @Inject lateinit var logger: AAPSLogger +abstract class ActionViewModelBase( + protected val injector: HasAndroidInjector, + protected val logger: AAPSLogger +) : ViewModelBase() { private val _isActionExecutingLiveData = MutableLiveData(false) val isActionExecutingLiveData: LiveData = _isActionExecutingLiveData diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/deactivation/viewmodel/action/DeactivatePodViewModel.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/deactivation/viewmodel/action/DeactivatePodViewModel.kt index 15abe11e69..541013e82f 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/deactivation/viewmodel/action/DeactivatePodViewModel.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/deactivation/viewmodel/action/DeactivatePodViewModel.kt @@ -1,8 +1,13 @@ package info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.viewmodel.ActionViewModelBase -abstract class DeactivatePodViewModel : ActionViewModelBase() { +abstract class DeactivatePodViewModel( + injector: HasAndroidInjector, + logger: AAPSLogger +) : ActionViewModelBase(injector, logger) { abstract fun discardPod() } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index e4c18b1d13..f40dace292 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -12,13 +12,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definitio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager +import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.Observable -import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer -import io.reactivex.schedulers.Schedulers import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -27,7 +27,8 @@ import javax.inject.Singleton class OmnipodDashManagerImpl @Inject constructor( private val logger: AAPSLogger, private val podStateManager: OmnipodDashPodStateManager, - private val bleManager: OmnipodDashBleManager + private val bleManager: OmnipodDashBleManager, + private val aapsSchedulers: AapsSchedulers ) : OmnipodDashManager { private val observePodReadyForActivationPart1: Observable @@ -39,26 +40,28 @@ class OmnipodDashManagerImpl @Inject constructor( } } - private val connectToPod: Observable + private val observeConnectToPod: Observable get() = Observable.defer { bleManager.connect() } + private val observeSendGetVersionCommand: Observable + get() = Observable.defer { + bleManager.sendCommand(GetVersionCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(DEFAULT_UNIQUE_ID) // + .build()) // + } + override fun activatePodPart1(): Observable { return Observable.concat( observePodReadyForActivationPart1, - connectToPod, - Observable.defer { - bleManager.sendCommand(GetVersionCommand.Builder() // - .setSequenceNumber(podStateManager.messageSequenceNumber) // - .setUniqueId(DEFAULT_UNIQUE_ID) // - .build()) // - } + observeConnectToPod, + observeSendGetVersionCommand // ... Send more commands ) // // TODO these would be common for any observable returned in a public function in this class .doOnNext(PodEventInterceptor()) // .doOnError(ErrorInterceptor()) - .subscribeOn(Schedulers.io()) // - .observeOn(AndroidSchedulers.mainThread()) + .subscribeOn(aapsSchedulers.io) } override fun activatePodPart2(): Observable { @@ -128,7 +131,6 @@ class OmnipodDashManagerImpl @Inject constructor( inner class PodEventInterceptor : Consumer { - // TODO split into separate methods override fun accept(event: PodEvent) { logger.debug(LTag.PUMP, "Intercepted PodEvent in OmnipodDashManagerImpl: ${event.javaClass.simpleName}") when (event) { @@ -147,23 +149,7 @@ class OmnipodDashManagerImpl @Inject constructor( is PodEvent.ResponseReceived -> { podStateManager.increaseMessageSequenceNumber() - when (event.response) { - is VersionResponse -> { - podStateManager.updateFromVersionResponse(event.response) - } - - is SetUniqueIdResponse -> { - podStateManager.updateFromSetUniqueIdResponse(event.response) - } - - is DefaultStatusResponse -> { - podStateManager.updateFromDefaultStatusResponse(event.response) - } - - is AlarmStatusResponse -> { - podStateManager.updateFromAlarmStatusResponse(event.response) - } - } + handleResponse(event.response) } else -> { @@ -172,6 +158,26 @@ class OmnipodDashManagerImpl @Inject constructor( } } + private fun handleResponse(response: Response) { + when (response) { + is VersionResponse -> { + podStateManager.updateFromVersionResponse(response) + } + + is SetUniqueIdResponse -> { + podStateManager.updateFromSetUniqueIdResponse(response) + } + + is DefaultStatusResponse -> { + podStateManager.updateFromDefaultStatusResponse(response) + } + + is AlarmStatusResponse -> { + podStateManager.updateFromAlarmStatusResponse(response) + } + } + } + } inner class ErrorInterceptor : Consumer { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index bc795b6fc0..a9de3a3a11 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -94,7 +94,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context val msgIO = MessageIO(aapsLogger, bleIO) val ltkExchanger = LTKExchanger(aapsLogger, msgIO) - emitter.onNext(PodEvent.NegotiatingLtkAndNoncePrefix) + emitter.onNext(PodEvent.Pairing) val ltk = ltkExchanger.negotiateLTKAndNonce() aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") @@ -102,7 +102,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context emitter.onComplete() } catch (ex: Exception) { - emitter.onError(ex) // TODO is this necessary? + emitter.tryOnError(ex) // TODO is this necessary? } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt index e41c428a39..e898b755fe 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt @@ -42,7 +42,7 @@ class PodScanner(private val logger: AAPSLogger, private val bluetoothAdapter: B companion object { const val SCAN_FOR_SERVICE_UUID = "00004024-0000-1000-8000-00805F9B34FB" - const val POD_ID_NOT_ACTIVATED = 4294967294L + const val POD_ID_NOT_ACTIVATED = 0xFFFFFFFFL private const val SCAN_DURATION_MS = 5000 } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt index 25386ca32a..0bc6bf5125 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt @@ -10,7 +10,9 @@ sealed class PodEvent { object Scanning : PodEvent() object BluetoothConnecting : PodEvent() class BluetoothConnected(val address: String) : PodEvent() - object NegotiatingLtkAndNoncePrefix : PodEvent() + object Pairing : PodEvent() + object Paired : PodEvent() + object EstablishingSession : PodEvent() class Connected(val uniqueId: Long) : PodEvent() /* Message exchange events */ diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index bfc345801f..04370dad68 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -34,8 +34,6 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( store() } - // TODO: dynamic get() fun instead of assignment - override val isUniqueIdSet: Boolean get() = activationProgress.isAtLeast(ActivationProgress.SET_UNIQUE_ID) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index f4781f6a5e..dd2daa8e3b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -1,15 +1,22 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager import io.reactivex.Single +import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject -class DashInitializePodViewModel @Inject constructor(private val omnipodManager: OmnipodDashManager) : InitializePodViewModel() { +class DashInitializePodViewModel @Inject constructor( + private val omnipodManager: OmnipodDashManager, + injector: HasAndroidInjector, + logger: AAPSLogger +) : InitializePodViewModel(injector, logger) { override fun isPodInAlarm(): Boolean = false // TODO @@ -19,13 +26,13 @@ class DashInitializePodViewModel @Inject constructor(private val omnipodManager: override fun doExecuteAction(): Single = Single.create { source -> - val disposable = omnipodManager.activatePodPart1().subscribe( - { podEvent -> logger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") }, - { throwable -> + val disposable = omnipodManager.activatePodPart1().subscribeBy( + onNext = { podEvent -> logger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") }, + onError = { throwable -> logger.error(LTag.PUMP, "Error in Pod activation part 1", throwable) source.onSuccess(PumpEnactResult(injector).success(false).comment(throwable.message)) }, - { + onComplete = { logger.debug("Pod activation part 1 completed") source.onSuccess(PumpEnactResult(injector).success(true)) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt index f3086ffa92..0b5ef6bc66 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -1,14 +1,20 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import io.reactivex.Single import javax.inject.Inject -class DashInsertCannulaViewModel @Inject constructor(private val profileFunction: ProfileFunction) : InsertCannulaViewModel() { +class DashInsertCannulaViewModel @Inject constructor( + private val profileFunction: ProfileFunction, + injector: HasAndroidInjector, + logger: AAPSLogger +) : InsertCannulaViewModel(injector, logger) { override fun isPodInAlarm(): Boolean = false // TODO diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt index 28e773252b..8d7c393cf4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt @@ -1,13 +1,18 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivation.viewmodel.action import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.R import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel import io.reactivex.Single import javax.inject.Inject -class DashDeactivatePodViewModel @Inject constructor() : DeactivatePodViewModel() { +class DashDeactivatePodViewModel @Inject constructor( + injector: HasAndroidInjector, + logger: AAPSLogger +) : DeactivatePodViewModel(injector, logger) { override fun doExecuteAction(): Single = Single.just(PumpEnactResult(injector).success(false).comment("TODO")) // TODO diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt index a08d79a2b3..e7cfd81ed5 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInitializePodViewModel.kt @@ -1,7 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.eros.R import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress @@ -12,8 +14,10 @@ import javax.inject.Inject class ErosInitializePodViewModel @Inject constructor( private val aapsOmnipodManager: AapsOmnipodErosManager, - private val podStateManager: AapsErosPodStateManager -) : InitializePodViewModel() { + private val podStateManager: AapsErosPodStateManager, + injector: HasAndroidInjector, + logger: AAPSLogger +) : InitializePodViewModel(injector, logger) { override fun isPodInAlarm(): Boolean = podStateManager.isPodFaulted diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt index cb7c7c98fb..f28b6d1e9b 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/activation/viewmodel/action/ErosInsertCannulaViewModel.kt @@ -1,8 +1,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.wizard.activation.viewmodel.action import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel import info.nightscout.androidaps.plugins.pump.omnipod.eros.R import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.ActivationProgress @@ -14,8 +16,10 @@ import javax.inject.Inject class ErosInsertCannulaViewModel @Inject constructor( private val aapsOmnipodManager: AapsOmnipodErosManager, private val podStateManager: AapsErosPodStateManager, - private val profileFunction: ProfileFunction -) : InsertCannulaViewModel() { + private val profileFunction: ProfileFunction, + injector: HasAndroidInjector, + logger: AAPSLogger +) : InsertCannulaViewModel(injector, logger) { override fun isPodInAlarm(): Boolean = podStateManager.isPodFaulted diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt index 099aa87bf0..2546e6426c 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/wizard/deactivation/viewmodel/action/ErosDeactivatePodViewModel.kt @@ -1,8 +1,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.eros.ui.wizard.deactivation.viewmodel.action import androidx.annotation.StringRes +import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.pump.omnipod.common.R import info.nightscout.androidaps.plugins.pump.omnipod.common.queue.command.CommandDeactivatePod import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.viewmodel.action.DeactivatePodViewModel @@ -13,8 +15,10 @@ import javax.inject.Inject class ErosDeactivatePodViewModel @Inject constructor( private val aapsOmnipodManager: AapsOmnipodErosManager, - private val commandQueueProvider: CommandQueueProvider -) : DeactivatePodViewModel() { + private val commandQueueProvider: CommandQueueProvider, + injector: HasAndroidInjector, + logger: AAPSLogger +) : DeactivatePodViewModel(injector, logger) { override fun doExecuteAction(): Single = Single.create { source -> From 5c8ba986823ccce4804c80bbd6b95cab0c8db73e Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 15:30:12 +0100 Subject: [PATCH 058/649] Remove TODO --- .../pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index a9de3a3a11..3dda0461dc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -102,7 +102,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context emitter.onComplete() } catch (ex: Exception) { - emitter.tryOnError(ex) // TODO is this necessary? + emitter.tryOnError(ex) } } From 513ac9b0f4776d75db9f20983ffad72b744af179 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 15:45:50 +0100 Subject: [PATCH 059/649] Replace subscribe with subscribeBy --- .../common/viewmodel/ActionViewModelBase.kt | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt index 23f175ae1d..807cfc1aec 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/viewmodel/ActionViewModelBase.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import io.reactivex.Single +import io.reactivex.rxkotlin.subscribeBy abstract class ActionViewModelBase( protected val injector: HasAndroidInjector, @@ -21,14 +22,16 @@ abstract class ActionViewModelBase( fun executeAction() { _isActionExecutingLiveData.postValue(true) - val disposable = doExecuteAction().subscribe({ result -> - _isActionExecutingLiveData.postValue(false) - _actionResultLiveData.postValue(result) - }, { throwable -> - logger.error(LTag.PUMP, "Caught exception in while executing action in ActionViewModelBase", throwable) - _isActionExecutingLiveData.postValue(false) - _actionResultLiveData.postValue(PumpEnactResult(injector).success(false).comment(throwable.message)) - }) + val disposable = doExecuteAction().subscribeBy( + onSuccess = { result -> + _isActionExecutingLiveData.postValue(false) + _actionResultLiveData.postValue(result) + }, + onError = { throwable -> + logger.error(LTag.PUMP, "Caught exception in while executing action in ActionViewModelBase", throwable) + _isActionExecutingLiveData.postValue(false) + _actionResultLiveData.postValue(PumpEnactResult(injector).success(false).comment(throwable.message)) + }) } protected abstract fun doExecuteAction(): Single From 256cfe077d7e0f2f65e841c626fa5b8f574738e3 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 18:20:17 +0100 Subject: [PATCH 060/649] Replace single booleans for alerts with EnumSet of AlertType and introduce sealed class AlertTrigger --- .../omnipod/dash/driver/OmnipodDashManager.kt | 4 +- .../dash/driver/OmnipodDashManagerImpl.kt | 4 +- .../pod/command/ProgramAlertsCommand.kt | 6 +- .../driver/pod/command/ProgramBasalCommand.kt | 6 +- .../driver/pod/command/ProgramBolusCommand.kt | 2 +- .../pod/command/ProgramTempBasalCommand.kt | 2 +- .../driver/pod/command/SetUniqueIdCommand.kt | 2 +- .../pod/command/SilenceAlertsCommand.kt | 77 +++-------------- .../driver/pod/command/StopDeliveryCommand.kt | 4 +- .../pod/definition/AlertConfiguration.kt | 24 ++++-- .../driver/pod/definition/AlertTrigger.kt | 6 ++ .../driver/pod/definition/AlertTriggerType.kt | 6 -- .../definition/{AlertSlot.kt => AlertType.kt} | 9 +- .../pod/response/AlarmStatusResponse.kt | 84 +++++++------------ .../pod/response/DefaultStatusResponse.kt | 45 ++++------ .../pod/state/OmnipodDashPodStateManager.kt | 2 +- .../state/OmnipodDashPodStateManagerImpl.kt | 4 +- .../omnipod/dash/driver/pod/util/AlertUtil.kt | 29 +++++++ .../pod/command/ProgramAlertsCommandTest.kt | 14 ++-- .../pod/command/SilenceAlertsCommandTest.kt | 4 +- .../pod/response/AlarmStatusResponseTest.kt | 9 +- .../pod/response/DefaultStatusResponseTest.kt | 10 +-- 22 files changed, 143 insertions(+), 210 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt delete mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/{AlertSlot.kt => AlertType.kt} (69%) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index 3063c6de12..c567702331 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import io.reactivex.Observable import java.util.* @@ -33,7 +33,7 @@ interface OmnipodDashManager { fun programAlerts(alertConfigurations: List): Observable - fun silenceAlerts(alerts: EnumSet): Observable + fun silenceAlerts(alerts: EnumSet): Observable fun deactivatePod(): Observable } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index f40dace292..19660bf9d7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.G import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand.Companion.DEFAULT_UNIQUE_ID import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse @@ -119,7 +119,7 @@ class OmnipodDashManagerImpl @Inject constructor( return Observable.empty() } - override fun silenceAlerts(alerts: EnumSet): Observable { + override fun silenceAlerts(alerts: EnumSet): Observable { // TODO return Observable.empty() } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt index 4f0424988b..44c8505a49 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt @@ -53,14 +53,14 @@ class ProgramAlertsCommand private constructor( private var alertConfigurations: List? = null - fun setAlertConfigurations(alertConfigurations: List?): Builder { + fun setAlertConfigurations(alertConfigurations: List): Builder { this.alertConfigurations = alertConfigurations return this } override fun buildCommand(): ProgramAlertsCommand { - requireNotNull(alertConfigurations) { "alertConfigurations can not be null" } // !!? - return ProgramAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, alertConfigurations!!, nonce!!) // TODO this might crash if not all are set + requireNotNull(alertConfigurations) { "alertConfigurations can not be null" } + return ProgramAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, alertConfigurations!!, nonce!!) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt index 5758fe9377..9e9afdd3d3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -77,17 +77,17 @@ class ProgramBasalCommand private constructor( private var programReminder: ProgramReminder? = null private var currentTime: Date? = null - fun setBasalProgram(basalProgram: BasalProgram?): Builder { + fun setBasalProgram(basalProgram: BasalProgram): Builder { this.basalProgram = basalProgram return this } - fun setProgramReminder(programReminder: ProgramReminder?): Builder { + fun setProgramReminder(programReminder: ProgramReminder): Builder { this.programReminder = programReminder return this } - fun setCurrentTime(currentTime: Date?): Builder { + fun setCurrentTime(currentTime: Date): Builder { this.currentTime = currentTime return this } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt index c6bbfcfb72..c02f1d3ef0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -70,7 +70,7 @@ class ProgramBolusCommand private constructor( return this } - fun setProgramReminder(programReminder: ProgramReminder?): Builder { + fun setProgramReminder(programReminder: ProgramReminder): Builder { this.programReminder = programReminder return this } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt index 229138dd2d..c0179ed62e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -32,7 +32,7 @@ class ProgramTempBasalCommand private constructor( private var rateInUnitsPerHour: Double? = null private var durationInMinutes: Short? = null - fun setProgramReminder(programReminder: ProgramReminder?): Builder { + fun setProgramReminder(programReminder: ProgramReminder): Builder { this.programReminder = programReminder return this } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt index 965f9a3de3..04d62e99ac 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -56,7 +56,7 @@ class SetUniqueIdCommand private constructor( return this } - fun setInitializationTime(initializationTime: Date?): Builder { + fun setInitializationTime(initializationTime: Date): Builder { this.initializationTime = initializationTime return this } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index e838c89395..afdfa1c25b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -3,7 +3,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.NonceEnabledCommand import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.builder.NonceEnabledCommandBuilder -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.AlertUtil import java.nio.ByteBuffer import java.util.* @@ -11,7 +12,7 @@ class SilenceAlertsCommand private constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, - private val parameters: SilenceAlertCommandParameters, + private val alertTypes: EnumSet, nonce: Int ) : NonceEnabledCommand(CommandType.SILENCE_ALERTS, uniqueId, sequenceNumber, multiCommandFlag, nonce) { @@ -22,12 +23,12 @@ class SilenceAlertsCommand private constructor( .put(commandType.value) // .put(BODY_LENGTH) // .putInt(nonce) // - .put(parameters.encoded) // + .put(AlertUtil.encodeAlertSet(alertTypes)) // .array()) override fun toString(): String { return "SilenceAlertsCommand{" + - "parameters=" + parameters + + "alterTypes=" + alertTypes + ", nonce=" + nonce + ", commandType=" + commandType + ", uniqueId=" + uniqueId + @@ -36,76 +37,18 @@ class SilenceAlertsCommand private constructor( '}' } - class SilenceAlertCommandParameters(private val silenceAutoOffAlert: Boolean, private val silenceMultiCommandAlert: Boolean, private val silenceExpirationImminentAlert: Boolean, private val silenceUserSetExpirationAlert: Boolean, private val silenceLowReservoirAlert: Boolean, private val silenceSuspendInProgressAlert: Boolean, private val silenceSuspendEndedAlert: Boolean, private val silencePodExpirationAlert: Boolean) : Encodable { - - override val encoded: ByteArray - get() { - val bitSet = BitSet(8) - bitSet[0] = silenceAutoOffAlert - bitSet[1] = silenceMultiCommandAlert - bitSet[2] = silenceExpirationImminentAlert - bitSet[3] = silenceUserSetExpirationAlert - bitSet[4] = silenceLowReservoirAlert - bitSet[5] = silenceSuspendInProgressAlert - bitSet[6] = silenceSuspendEndedAlert - bitSet[7] = silencePodExpirationAlert - return bitSet.toByteArray() - } - } - class Builder : NonceEnabledCommandBuilder() { - private var silenceAutoOffAlert = false - private var silenceMultiCommandAlert = false - private var silenceExpirationImminentAlert = false - private var silenceUserSetExpirationAlert = false - private var silenceLowReservoirAlert = false - private var silenceSuspendInProgressAlert = false - private var silenceSuspendEndedAlert = false - private var silencePodExpirationAlert = false + private var alertTypes: EnumSet? = null - fun setSilenceAutoOffAlert(silenceAutoOffAlert: Boolean): Builder { - this.silenceAutoOffAlert = silenceAutoOffAlert - return this - } - - fun setSilenceMultiCommandAlert(silenceMultiCommandAlert: Boolean): Builder { - this.silenceMultiCommandAlert = silenceMultiCommandAlert - return this - } - - fun setSilenceExpirationImminentAlert(silenceExpirationImminentAlert: Boolean): Builder { - this.silenceExpirationImminentAlert = silenceExpirationImminentAlert - return this - } - - fun setSilenceUserSetExpirationAlert(silenceUserSetExpirationAlert: Boolean): Builder { - this.silenceUserSetExpirationAlert = silenceUserSetExpirationAlert - return this - } - - fun setSilenceLowReservoirAlert(silenceLowReservoirAlert: Boolean): Builder { - this.silenceLowReservoirAlert = silenceLowReservoirAlert - return this - } - - fun setSilenceSuspendInProgressAlert(silenceSuspendInProgressAlert: Boolean): Builder { - this.silenceSuspendInProgressAlert = silenceSuspendInProgressAlert - return this - } - - fun setSilenceSuspendEndedAlert(silenceSuspendEndedAlert: Boolean): Builder { - this.silenceSuspendEndedAlert = silenceSuspendEndedAlert - return this - } - - fun setSilencePodExpirationAlert(silencePodExpirationAlert: Boolean): Builder { - this.silencePodExpirationAlert = silencePodExpirationAlert + fun setAlertTypes(alertTypes: EnumSet): Builder { + this.alertTypes = alertTypes return this } override fun buildCommand(): SilenceAlertsCommand { - return SilenceAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, SilenceAlertCommandParameters(silenceAutoOffAlert, silenceMultiCommandAlert, silenceExpirationImminentAlert, silenceUserSetExpirationAlert, silenceLowReservoirAlert, silenceSuspendInProgressAlert, silenceSuspendEndedAlert, silencePodExpirationAlert), nonce!!) + requireNotNull(alertTypes) { "alertTypes can not be null" } + return SilenceAlertsCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, alertTypes!!, nonce!!) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt index 254fd8edf3..603a7ff09d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -58,12 +58,12 @@ class StopDeliveryCommand private constructor( private var deliveryType: DeliveryType? = null private var beepType: BeepType? = BeepType.LONG_SINGLE_BEEP - fun setDeliveryType(deliveryType: DeliveryType?): Builder { + fun setDeliveryType(deliveryType: DeliveryType): Builder { this.deliveryType = deliveryType return this } - fun setBeepType(beepType: BeepType?): Builder { + fun setBeepType(beepType: BeepType): Builder { this.beepType = beepType return this } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt index 9b1b3a8d4c..4040ac5831 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt @@ -4,23 +4,22 @@ import java.nio.ByteBuffer import kotlin.experimental.or class AlertConfiguration( - private val slot: AlertSlot, + private val type: AlertType, private val enabled: Boolean, private val durationInMinutes: Short, private val autoOff: Boolean, - private val triggerType: AlertTriggerType, - private val offsetInMinutesOrThresholdInMicroLiters: Short, + private val trigger: AlertTrigger, private val beepType: BeepType, private val beepRepetition: BeepRepetitionType ) : Encodable { override val encoded: ByteArray get() { - var firstByte = (slot.value.toInt() shl 4).toByte() + var firstByte = (type.index.toInt() shl 4).toByte() if (enabled) { firstByte = firstByte or (1 shl 3) } - if (triggerType == AlertTriggerType.RESERVOIR_VOLUME_TRIGGER) { + if (trigger is AlertTrigger.ReservoirVolumeTrigger) { firstByte = firstByte or (1 shl 2) } if (autoOff) { @@ -30,7 +29,15 @@ class AlertConfiguration( return ByteBuffer.allocate(6) // .put(firstByte) .put(durationInMinutes.toByte()) // - .putShort(offsetInMinutesOrThresholdInMicroLiters) // + .putShort(when (trigger) { + is AlertTrigger.ReservoirVolumeTrigger -> { + trigger.thresholdInMicroLiters + } + + is AlertTrigger.TimerTrigger -> { + trigger.offsetInMinutes + } + }) // .put(beepRepetition.value) // .put(beepType.value) // .array() @@ -38,12 +45,11 @@ class AlertConfiguration( override fun toString(): String { return "AlertConfiguration{" + - "slot=" + slot + + "type=" + type + ", enabled=" + enabled + ", durationInMinutes=" + durationInMinutes + ", autoOff=" + autoOff + - ", triggerType=" + triggerType + - ", offsetInMinutesOrThresholdInMicroLiters=" + offsetInMinutesOrThresholdInMicroLiters + + ", trigger=" + trigger + ", beepType=" + beepType + ", beepRepetition=" + beepRepetition + '}' diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt new file mode 100644 index 0000000000..48df9b25bf --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition + +sealed class AlertTrigger { + class TimerTrigger(val offsetInMinutes: Short) : AlertTrigger() + class ReservoirVolumeTrigger(val thresholdInMicroLiters: Short) : AlertTrigger() +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt deleted file mode 100644 index 7dc7a16f1a..0000000000 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTriggerType.kt +++ /dev/null @@ -1,6 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition - -enum class AlertTriggerType { - TIME_TRIGGER, - RESERVOIR_VOLUME_TRIGGER -} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt similarity index 69% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt index 3735e550cd..ec6d472066 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertSlot.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.HasValue -enum class AlertSlot(override val value: Byte) : HasValue { +enum class AlertType(val index: Byte) : HasValue { AUTO_OFF(0x00.toByte()), MULTI_COMMAND(0x01.toByte()), @@ -13,4 +13,11 @@ enum class AlertSlot(override val value: Byte) : HasValue { SUSPEND_ENDED(0x06.toByte()), EXPIRATION(0x07.toByte()), UNKNOWN(0xff.toByte()); + + override val value: Byte + get() = if (this == UNKNOWN) { + 0xff.toByte() + } else { + (1 shl index.toInt()).toByte() + } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index df22e3a23a..847eaa903c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -1,11 +1,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.StatusResponseType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.AlertUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import java.nio.ByteBuffer +import java.util.* import kotlin.experimental.and class AlarmStatusResponse( @@ -24,14 +27,7 @@ class AlarmStatusResponse( val alarmTime: Short = ByteBuffer.wrap(byteArrayOf(encoded[11], encoded[12])).short val reservoirPulsesRemaining: Short = ByteBuffer.wrap(byteArrayOf(encoded[13], encoded[14])).short val minutesSinceActivation: Short = ByteBuffer.wrap(byteArrayOf(encoded[15], encoded[16])).short - val alert0Active: Boolean - val alert1Active: Boolean - val alert2Active: Boolean - val alert3Active: Boolean - val alert4Active: Boolean - val alert5Active: Boolean - val alert6Active: Boolean - val alert7Active: Boolean + val activeAlerts: EnumSet = AlertUtil.decodeAlertSet(encoded[17]) val occlusionAlarm: Boolean val pulseInfoInvalid: Boolean val podStatusWhenAlarmOccurred: PodStatus @@ -44,15 +40,6 @@ class AlarmStatusResponse( val returnAddressOfPodAlarmHandlerCaller: Short init { - val activeAlerts = encoded[17].toInt() - alert0Active = activeAlerts and 1 == 1 - alert1Active = activeAlerts ushr 1 and 1 == 1 - alert2Active = activeAlerts ushr 2 and 1 == 1 - alert3Active = activeAlerts ushr 3 and 1 == 1 - alert4Active = activeAlerts ushr 4 and 1 == 1 - alert5Active = activeAlerts ushr 5 and 1 == 1 - alert6Active = activeAlerts ushr 6 and 1 == 1 - alert7Active = activeAlerts ushr 7 and 1 == 1 val alarmFlags = encoded[18] occlusionAlarm = (alarmFlags.toInt() and 1) == 1 pulseInfoInvalid = alarmFlags shr 1 and 1 == 1 @@ -69,44 +56,33 @@ class AlarmStatusResponse( } override fun toString(): String { - return "AlarmStatusResponse{" + - "messageType=" + messageType + - ", messageLength=" + messageLength + - ", additionalStatusResponseType=" + additionalStatusResponseType + - ", podStatus=" + podStatus + - ", deliveryStatus=" + deliveryStatus + - ", bolusPulsesRemaining=" + bolusPulsesRemaining + - ", sequenceNumberOfLastProgrammingCommand=" + sequenceNumberOfLastProgrammingCommand + - ", totalPulsesDelivered=" + totalPulsesDelivered + - ", alarmType=" + alarmType + - ", alarmTime=" + alarmTime + - ", reservoirPulsesRemaining=" + reservoirPulsesRemaining + - ", minutesSinceActivation=" + minutesSinceActivation + - ", alert0Active=" + alert0Active + - ", alert1Active=" + alert1Active + - ", alert2Active=" + alert2Active + - ", alert3Active=" + alert3Active + - ", alert4Active=" + alert4Active + - ", alert5Active=" + alert5Active + - ", alert6Active=" + alert6Active + - ", alert7Active=" + alert7Active + - ", occlusionAlarm=" + occlusionAlarm + - ", pulseInfoInvalid=" + pulseInfoInvalid + - ", podStatusWhenAlarmOccurred=" + podStatusWhenAlarmOccurred + - ", immediateBolusWhenAlarmOccurred=" + immediateBolusWhenAlarmOccurred + - ", occlusionType=" + occlusionType + - ", occurredWhenFetchingImmediateBolusActiveInformation=" + occurredWhenFetchingImmediateBolusActiveInformation + - ", rssi=" + rssi + - ", receiverLowerGain=" + receiverLowerGain + - ", podStatusWhenAlarmOccurred2=" + podStatusWhenAlarmOccurred2 + - ", returnAddressOfPodAlarmHandlerCaller=" + returnAddressOfPodAlarmHandlerCaller + - ", statusResponseType=" + statusResponseType + - ", responseType=" + responseType + - ", encoded=" + encoded.contentToString() + - '}' + return "AlarmStatusResponse(" + + "messageType=$messageType, " + + "messageLength=$messageLength, " + + "additionalStatusResponseType=$additionalStatusResponseType, " + + "podStatus=$podStatus, " + + "deliveryStatus=$deliveryStatus, " + + "bolusPulsesRemaining=$bolusPulsesRemaining, " + + "sequenceNumberOfLastProgrammingCommand=$sequenceNumberOfLastProgrammingCommand, " + + "totalPulsesDelivered=$totalPulsesDelivered, " + + "alarmType=$alarmType, " + + "alarmTime=$alarmTime, " + + "reservoirPulsesRemaining=$reservoirPulsesRemaining, " + + "minutesSinceActivation=$minutesSinceActivation, " + + "activeAlerts=$activeAlerts, " + + "occlusionAlarm=$occlusionAlarm, " + + "pulseInfoInvalid=$pulseInfoInvalid, " + + "podStatusWhenAlarmOccurred=$podStatusWhenAlarmOccurred, " + + "immediateBolusWhenAlarmOccurred=$immediateBolusWhenAlarmOccurred, " + + "occlusionType=$occlusionType, " + + "occurredWhenFetchingImmediateBolusActiveInformation=$occurredWhenFetchingImmediateBolusActiveInformation, " + + "rssi=$rssi, " + + "receiverLowerGain=$receiverLowerGain, " + + "podStatusWhenAlarmOccurred2=$podStatusWhenAlarmOccurred2, " + + "returnAddressOfPodAlarmHandlerCaller=$returnAddressOfPodAlarmHandlerCaller" + + ")" } infix fun Byte.shr(i: Int): Int = toInt() shr i -} - +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt index cfe5a0af70..fde2951b31 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt @@ -1,8 +1,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.AlertUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue +import java.util.* import kotlin.experimental.and class DefaultStatusResponse( @@ -15,42 +18,24 @@ class DefaultStatusResponse( val totalPulsesDelivered: Short = ((encoded[2] and 0x0f shl 12 or (encoded[3].toInt() and 0xff shl 1) or (encoded[4].toInt() and 0xff ushr 7)).toShort()) val sequenceNumberOfLastProgrammingCommand: Short = (encoded[4] ushr 3 and 0x0f).toShort() val bolusPulsesRemaining: Short = ((encoded[4] and 0x07 shl 10 or (encoded[5].toInt() and 0xff) and 2047).toShort()) - val activeAlerts = (encoded[6].toInt() and 0xff shl 1 or (encoded[7] ushr 7)).toShort() - val occlusionAlertActive: Boolean = (activeAlerts and 1).toInt() == 1 - val alert1Active: Boolean = activeAlerts shr 1 and 1 == 1 - val alert2Active: Boolean = activeAlerts shr 2 and 1 == 1 - val alert3Active: Boolean = activeAlerts shr 3 and 1 == 1 - val alert4Active: Boolean = activeAlerts shr 4 and 1 == 1 - val alert5Active: Boolean = activeAlerts shr 5 and 1 == 1 - val alert6Active: Boolean = activeAlerts shr 6 and 1 == 1 - val alert7Active: Boolean = activeAlerts shr 7 and 1 == 1 + val activeAlerts: EnumSet = AlertUtil.decodeAlertSet((encoded[6].toInt() and 0xff shl 1 or (encoded[7] ushr 7)).toByte()) val minutesSinceActivation: Short = (encoded[7] and 0x7f shl 6 or (encoded[8].toInt() and 0xff ushr 2 and 0x3f)).toShort() val reservoirPulsesRemaining: Short = (encoded[8] shl 8 or encoded[9].toInt() and 0x3ff).toShort() override fun toString(): String { - return "DefaultStatusResponse{" + - "messageType=" + messageType + - ", deliveryStatus=" + deliveryStatus + - ", podStatus=" + podStatus + - ", totalPulsesDelivered=" + totalPulsesDelivered + - ", sequenceNumberOfLastProgrammingCommand=" + sequenceNumberOfLastProgrammingCommand + - ", bolusPulsesRemaining=" + bolusPulsesRemaining + - ", occlusionAlertActive=" + occlusionAlertActive + - ", alert1Active=" + alert1Active + - ", alert2Active=" + alert2Active + - ", alert3Active=" + alert3Active + - ", alert4Active=" + alert4Active + - ", alert5Active=" + alert5Active + - ", alert6Active=" + alert6Active + - ", alert7Active=" + alert7Active + - ", minutesSinceActivation=" + minutesSinceActivation + - ", reservoirPulsesRemaining=" + reservoirPulsesRemaining + - ", responseType=" + responseType + - ", encoded=" + encoded.contentToString() + - '}' + return "DefaultStatusResponse(" + + "messageType=$messageType" + + ", deliveryStatus=$deliveryStatus" + + ", podStatus=$podStatus" + + ", totalPulsesDelivered=$totalPulsesDelivered" + + ", sequenceNumberOfLastProgrammingCommand=$sequenceNumberOfLastProgrammingCommand" + + ", bolusPulsesRemaining=$bolusPulsesRemaining" + + ", activeAlerts=$activeAlerts" + + ", minutesSinceActivation=$minutesSinceActivation" + + ", reservoirPulsesRemaining=$reservoirPulsesRemaining)" } + } infix fun Byte.ushr(i: Int) = toInt() ushr i -infix fun Short.shr(i: Int): Int = toInt() shr i infix fun Byte.shl(i: Int): Int = toInt() shl i diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index bcfe894f5e..b0a069b5bc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -39,7 +39,7 @@ interface OmnipodDashPodStateManager { val podStatus: PodStatus? val deliveryStatus: DeliveryStatus? val minutesSinceActivation: Short? - val activeAlerts: EnumSet? + val activeAlerts: EnumSet? val tempBasal: TempBasal? val tempBasalActive: Boolean diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index 04370dad68..229109a6d2 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -130,7 +130,7 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( override val minutesSinceActivation: Short? get() = podState.minutesSinceActivation - override val activeAlerts: EnumSet? + override val activeAlerts: EnumSet? get() = podState.activeAlerts override val tempBasal: OmnipodDashPodStateManager.TempBasal? @@ -247,7 +247,7 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( var podStatus: PodStatus? = null var deliveryStatus: DeliveryStatus? = null var minutesSinceActivation: Short? = null - var activeAlerts: EnumSet? = null + var activeAlerts: EnumSet? = null var basalProgram: BasalProgram? = null var tempBasal: OmnipodDashPodStateManager.TempBasal? = null diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt new file mode 100644 index 0000000000..04cc4e3ce0 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util + +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType +import java.util.* + +object AlertUtil { + + fun decodeAlertSet(encoded: Byte): EnumSet { + val encodedInt = encoded.toInt() and 0xff + + val alertList = AlertType.values().filter { + (it.value.toInt() and 0xff) and encodedInt != 0 + }.toList() + + return if (alertList.isEmpty()) { + EnumSet.noneOf(AlertType::class.java) + } else { + EnumSet.copyOf(alertList) + } + } + + fun encodeAlertSet(alertSet: EnumSet): Byte { + var out = 0 + alertSet.forEach { slot -> + out = out or (slot.value.toInt() and 0xff) + } + return out.toByte() + } +} \ No newline at end of file diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt index 7fca25cfd7..63c5063c0e 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertSlot -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTriggerType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTrigger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepRepetitionType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType import org.apache.commons.codec.DecoderException @@ -15,8 +15,8 @@ class ProgramAlertsCommandTest { @Test @Throws(DecoderException::class) fun testExpirationAlerts() { val configurations: MutableList = ArrayList() - configurations.add(AlertConfiguration(AlertSlot.EXPIRATION, true, 420.toShort(), false, AlertTriggerType.TIME_TRIGGER, 4305.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX3)) - configurations.add(AlertConfiguration(AlertSlot.EXPIRATION_IMMINENT, true, 0.toShort(), false, AlertTriggerType.TIME_TRIGGER, 4725.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX4)) + configurations.add(AlertConfiguration(AlertType.EXPIRATION, true, 420.toShort(), false, AlertTrigger.TimerTrigger(4305.toShort()), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX3)) + configurations.add(AlertConfiguration(AlertType.EXPIRATION_IMMINENT, true, 0.toShort(), false, AlertTrigger.TimerTrigger(4725.toShort()), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX4)) val encoded = ProgramAlertsCommand.Builder() // .setUniqueId(37879811) // @@ -32,7 +32,7 @@ class ProgramAlertsCommandTest { @Test @Throws(DecoderException::class) fun testLowReservoirAlert() { val configurations: MutableList = ArrayList() - configurations.add(AlertConfiguration(AlertSlot.LOW_RESERVOIR, true, 0.toShort(), false, AlertTriggerType.RESERVOIR_VOLUME_TRIGGER, 200.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX)) + configurations.add(AlertConfiguration(AlertType.LOW_RESERVOIR, true, 0.toShort(), false, AlertTrigger.ReservoirVolumeTrigger(200.toShort()), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX)) val encoded = ProgramAlertsCommand.Builder() // .setUniqueId(37879811) // @@ -47,7 +47,7 @@ class ProgramAlertsCommandTest { @Test @Throws(DecoderException::class) fun testUserExpirationAlert() { val configurations: MutableList = ArrayList() - configurations.add(AlertConfiguration(AlertSlot.USER_SET_EXPIRATION, true, 0.toShort(), false, AlertTriggerType.TIME_TRIGGER, 4079.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX2)) + configurations.add(AlertConfiguration(AlertType.USER_SET_EXPIRATION, true, 0.toShort(), false, AlertTrigger.TimerTrigger(4079.toShort()), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX2)) val encoded = ProgramAlertsCommand.Builder() // .setUniqueId(37879811) // @@ -62,7 +62,7 @@ class ProgramAlertsCommandTest { @Test @Throws(DecoderException::class) fun testLumpOfCoalAlert() { val configurations: MutableList = ArrayList() - configurations.add(AlertConfiguration(AlertSlot.EXPIRATION, true, 55.toShort(), false, AlertTriggerType.TIME_TRIGGER, 5.toShort(), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX5)) + configurations.add(AlertConfiguration(AlertType.EXPIRATION, true, 55.toShort(), false, AlertTrigger.TimerTrigger(5.toShort()), BeepType.FOUR_TIMES_BIP_BEEP, BeepRepetitionType.XXX5)) val encoded = ProgramAlertsCommand.Builder() // .setUniqueId(37879811) // diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt index f901594225..0f9c267578 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt @@ -1,9 +1,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert import org.junit.Test +import java.util.* class SilenceAlertsCommandTest { @@ -12,7 +14,7 @@ class SilenceAlertsCommandTest { .setUniqueId(37879811) // .setSequenceNumber(1.toShort()) // .setNonce(1229869870) // - .setSilenceLowReservoirAlert(true) // + .setAlertTypes(EnumSet.of(AlertType.LOW_RESERVOIR)) // .build() // .encoded diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt index 2095cbbf8a..06e6337afd 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt @@ -29,14 +29,7 @@ class AlarmStatusResponseTest { Assert.assertEquals(0.toShort(), response.alarmTime) Assert.assertEquals(1023.toShort(), response.reservoirPulsesRemaining) Assert.assertEquals(405.toShort(), response.minutesSinceActivation) - Assert.assertFalse(response.alert0Active) - Assert.assertFalse(response.alert1Active) - Assert.assertFalse(response.alert2Active) - Assert.assertFalse(response.alert3Active) - Assert.assertFalse(response.alert4Active) - Assert.assertFalse(response.alert5Active) - Assert.assertFalse(response.alert6Active) - Assert.assertFalse(response.alert7Active) + Assert.assertEquals(0, response.activeAlerts.size) Assert.assertFalse(response.occlusionAlarm) Assert.assertFalse(response.pulseInfoInvalid) Assert.assertEquals(PodStatus.UNINITIALIZED, response.podStatusWhenAlarmOccurred) diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt index da375beab1..f925642d38 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.DeliveryStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert @@ -22,14 +21,7 @@ class DefaultStatusResponseTest { Assert.assertEquals(320.toShort(), response.totalPulsesDelivered) Assert.assertEquals(5.toShort(), response.sequenceNumberOfLastProgrammingCommand) Assert.assertEquals(0.toShort(), response.bolusPulsesRemaining) - Assert.assertFalse(response.occlusionAlertActive) - Assert.assertFalse(response.alert1Active) - Assert.assertFalse(response.alert2Active) - Assert.assertFalse(response.alert3Active) - Assert.assertFalse(response.alert4Active) - Assert.assertFalse(response.alert5Active) - Assert.assertFalse(response.alert6Active) - Assert.assertFalse(response.alert7Active) + Assert.assertEquals(0, response.activeAlerts.size) Assert.assertEquals(280.toShort(), response.minutesSinceActivation) Assert.assertEquals(1023.toShort(), response.reservoirPulsesRemaining) } From c93705e88fa9f7ec1ab3558872ea29f3c1137742 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 18:22:56 +0100 Subject: [PATCH 061/649] Add retry for connecting to Pod --- .../pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 19660bf9d7..8426a62e07 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -17,9 +17,11 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.rx.retryWithBackoff import io.reactivex.Observable import io.reactivex.functions.Consumer import java.util.* +import java.util.concurrent.TimeUnit import javax.inject.Inject import javax.inject.Singleton @@ -41,7 +43,7 @@ class OmnipodDashManagerImpl @Inject constructor( } private val observeConnectToPod: Observable - get() = Observable.defer { bleManager.connect() } + get() = Observable.defer { bleManager.connect().retryWithBackoff(retries = 2, delay = 3, timeUnit = TimeUnit.SECONDS) } // TODO are these reasonable values? private val observeSendGetVersionCommand: Observable get() = Observable.defer { From 81ad52ebce8d037c08d17af925c7bc2da4d452be Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Fri, 26 Feb 2021 23:56:39 +0100 Subject: [PATCH 062/649] implement SPS1 command I had to add a new dependency: `tink-android:1.5.0` for X25519 --- core/core_dependencies.gradle | 1 + omnipod-dash/build.gradle | 5 +-- .../driver/comm/OmnipodDashBleManagerImpl.kt | 2 + .../dash/driver/comm/command/BleCommand.kt | 6 +++ .../dash/driver/comm/ltk/LTKExchanger.kt | 44 ++++++++++++++----- .../dash/driver/comm/message/MessageIO.kt | 4 +- .../driver/comm/message/PayloadSplitter.kt | 4 +- .../dash/driver/comm/packet/BlePacket.kt | 8 +++- .../driver/comm/scan/BleDiscoveredDevice.kt | 1 - 9 files changed, 56 insertions(+), 19 deletions(-) diff --git a/core/core_dependencies.gradle b/core/core_dependencies.gradle index 552aa32c15..25ecf5b36c 100644 --- a/core/core_dependencies.gradle +++ b/core/core_dependencies.gradle @@ -47,6 +47,7 @@ dependencies { //CryptoUtil api 'com.madgag.spongycastle:core:1.58.0.0' + // Graphview cannot be upgraded api "com.jjoe64:graphview:4.0.1" diff --git a/omnipod-dash/build.gradle b/omnipod-dash/build.gradle index 45c11a93bf..34ca4406c5 100644 --- a/omnipod-dash/build.gradle +++ b/omnipod-dash/build.gradle @@ -21,7 +21,6 @@ dependencies { implementation "androidx.room:room-runtime:$room_version" implementation "androidx.room:room-rxjava2:$room_version" kapt "androidx.room:room-compiler:$room_version" - implementation 'com.github.guepardoapps:kulid:1.1.2.0' - -} \ No newline at end of file + implementation 'com.google.crypto.tink:tink-android:1.5.0' +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 3dda0461dc..d08d9c50c9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -5,6 +5,7 @@ import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.content.Context +import com.google.crypto.tink.subtle.X25519 import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig @@ -24,6 +25,7 @@ import org.apache.commons.lang3.NotImplementedException import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException +import javax.crypto.KeyAgreement import javax.inject.Inject import javax.inject.Singleton diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt index a51e738df4..186585676c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command +import info.nightscout.androidaps.utils.extensions.toHex + open class BleCommand(val data: ByteArray) { constructor(type: BleCommandType) : this(byteArrayOf(type.value)) @@ -17,6 +19,10 @@ open class BleCommand(val data: ByteArray) { return true } + override fun toString(): String { + return "Raw command: [${data.toHex()}]"; + } + override fun hashCode(): Int { return data.contentHashCode() } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 666c7c0538..235b6f2261 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -1,31 +1,41 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk +import com.google.crypto.tink.subtle.X25519 import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding import info.nightscout.androidaps.utils.extensions.hexStringToByteArray +import java.security.SecureRandom internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { + private val privateKey = X25519.generatePrivateKey() + private val nonce = ByteArray(16) + private val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) + val nodeId = controllerId.increment() + private var seq: Byte = 1 + + init{ + val random = SecureRandom() + random.nextBytes(nonce) + } fun negotiateLTKAndNonce(): LTK? { // send SP1, SP2 - // TODO: get this from somewhere(preferences?) - var seq: Byte = 1 - val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) - val nodeId = controllerId.increment() - - var sp1sp2 = sp1sp2(nodeId.address, sp2(), seq, controllerId, nodeId) + var sp1sp2 = sp1sp2(nodeId.address, sp2()) msgIO.sendMesssage(sp1sp2.messagePacket) -/* - var sps1 = + seq++ + var sps1 = sps1() msgIO.sendMesssage(sps1.messagePacket) // send SPS1 + // read SPS1 val podSps1 = msgIO.receiveMessage() - + aapsLogger.info(LTag.PUMPBTCOMM, "Received message: %s", podSps1) +/* // send SPS2 var sps2 = PairMessage() msgIO.sendMesssage(sps2.messagePacket) @@ -46,7 +56,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI return GET_POD_STATUS_HEX_COMMAND.hexStringToByteArray() } - fun sp1sp2(sp1: ByteArray, sp2: ByteArray, seq: Byte, controllerId: Id, nodeId: Id): PairMessage { + fun sp1sp2(sp1: ByteArray, sp2: ByteArray): PairMessage { val payload = StringLengthPrefixEncoding.formatKeys( arrayOf("SP1=", ",SP2="), arrayOf(sp1, sp2), @@ -59,6 +69,20 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI ) } + fun sps1(): PairMessage { + val publicKey = X25519.publicFromPrivate(privateKey) + val payload = StringLengthPrefixEncoding.formatKeys( + arrayOf("SPS1="), + arrayOf(publicKey+nonce), + ) + return PairMessage( + sequenceNumber = seq, + source = controllerId, + destination = nodeId, + payload = payload, + ) + } + companion object { private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt index 7f742a4aca..0f04d55c0c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -38,7 +38,7 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { fun receiveMessage(): MessagePacket { val expectRTS = bleIO.receivePacket(CharacteristicType.CMD) - if (BleCommand(expectRTS) != BleCommandCTS()) { + if (BleCommand(expectRTS) != BleCommandRTS()) { throw UnexpectedCommandException(BleCommand(expectRTS)) } bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandCTS().data) @@ -53,7 +53,7 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { } } if (joiner.oneExtra) { - var data = bleIO.receivePacket(CharacteristicType.DATA) + data = bleIO.receivePacket(CharacteristicType.DATA) val accumulateAction = joiner.accumulate(data) if (accumulateAction is PayloadJoinerActionReject) { bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandNack(accumulateAction.idx).data) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt index d74032e6fe..6a0c60139b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt @@ -25,6 +25,7 @@ internal class PayloadSplitter(private val payload: ByteArray) { ret.add(LastOptionalPlusOneBlePacket( index = 1, payload = payload.copyOfRange(end, payload.size), + size = (payload.size-end).toByte(), )) } return ret @@ -53,9 +54,10 @@ internal class PayloadSplitter(private val payload: ByteArray) { payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + end), crc32 = crc32, )) - if (rest > 14) { + if (rest > LastBlePacket.CAPACITY) { ret.add(LastOptionalPlusOneBlePacket( index = (middleFragments + 2).toByte(), + size = (rest-LastBlePacket.CAPACITY).toByte(), payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + LastBlePacket.CAPACITY, payload.size), )) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index b9bd30a252..acdd237431 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -7,6 +7,7 @@ sealed class BlePacket { abstract fun asByteArray(): ByteArray companion object { + const val MAX_BLE_PACKET_LEN = 20 const val MAX_BLE_BUFFER_LEN = MAX_BLE_PACKET_LEN + 1 // we use this as the size allocated for the ByteBuffer } @@ -33,6 +34,7 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val } companion object { + internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = 13 // we are using all fields internal const val CAPACITY_WITH_MIDDLE_PACKETS = 18 // we are not using crc32 or size internal const val CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET = 18 @@ -46,6 +48,7 @@ data class MiddleBlePacket(val index: Byte, val payload: ByteArray) : BlePacket( } companion object { + internal const val CAPACITY = 19 } } @@ -66,14 +69,15 @@ data class LastBlePacket(val index: Byte, val size: Byte, val payload: ByteArray } companion object { + internal const val CAPACITY = 14 } } -data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray) : BlePacket() { +data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray, val size: Byte) : BlePacket() { override fun asByteArray(): ByteArray { - return byteArrayOf(index) + payload + return byteArrayOf(index, size) + payload } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt index 1b4a2cee2a..bf3d3dd74c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -31,7 +31,6 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: Sc @Throws(DiscoveredInvalidPodException::class) private fun validatePodId() { - val scanRecord = scanResult.scanRecord val serviceUUIDs = scanRecord.serviceUuids val hexPodId = extractUUID16(serviceUUIDs[3]) + extractUUID16(serviceUUIDs[4]) val podId = hexPodId.toLong(16) From 1aa6d02893baf076e38064a16205f0bb11dc0b11 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sat, 27 Feb 2021 13:28:19 +0100 Subject: [PATCH 063/649] ble: implement message reading&joining Now are able to read the first message: ``` INFO[0005] Received SPS1 6b943ec06b594f8a0383f384a3c916da75e1c7846c3e1b73f72f86ee2dc48774b2b4e5ad62d798b76cfd06be1cd4c937 DEBU[0005] Donna LTK: b874cb3cbe487040442138452faeb02d284ac55f489f19593265ff52f7310f1f DEBU[0005] First key 58cb3b742dc48774000000001cd4c937 :: 16 DEBU[0005] CMACY: 16 DEBU[0005] Intermediar key 4c13eebc4cf09795a07c50bf13786c18 :: 16 DEBU[0005] Pod public 2fe57da347cd62431528daac5fbb290730fff684afc4cfc2ed90995f58cb3b74 :: 32 DEBU[0005] Pod nonce 00000000000000000000000000000000 :: 16 DEBU[0005] Generated SPS1: 535053313d00302fe57da347cd62431528daac5fbb290730fff684afc4cfc2ed90995f58cb3b7400000000000000000000000000000000 TRAC[0005] CMD notification return: 4/00 TRAC[0005] received CMD: 01 TRAC[0005] Sending message: 54570003000006e00000109100001092535053313d00302fe57da347cd62431528daac5fbb290730fff684afc4cfc2ed90995f58cb3b7400000000000000000000000000000000 TRAC[0005] DATA notification return: 23/000354570003000006e000001091000010925350 TRAC[0005] DATA notification return: 23/0153313d00302fe57da347cd62431528daac5fbb TRAC[0005] DATA notification return: 23/02290730fff684afc4cfc2ed90995f58cb3b7400 TRAC[0005] DATA notification return: 23/030f7d02931d0000000000000000000000000000 TRAC[0005] DATA notification return: 23/0401000000000000000000000000000000000000 TRAC[0005] received CMD: 04 ``` --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 7 +- .../dash/driver/comm/command/BleCommand.kt | 2 +- .../comm/exceptions/MessageIOException.kt | 3 + .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 1 - .../dash/driver/comm/ltk/LTKExchanger.kt | 7 +- .../comm/message/CrcMismatchException.kt | 6 + .../comm/message/IncorrectPacketException.kt | 5 + .../dash/driver/comm/message/MessageIO.kt | 45 ++++--- .../dash/driver/comm/message/PayloadJoiner.kt | 111 +++++++++++++++--- .../driver/comm/message/PayloadSplitter.kt | 6 +- .../dash/driver/comm/packet/BlePacket.kt | 20 +++- 11 files changed, 157 insertions(+), 56 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/CrcMismatchException.kt create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/IncorrectPacketException.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index d08d9c50c9..1f8c9ed5b4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -5,7 +5,6 @@ import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.content.Context -import com.google.crypto.tink.subtle.X25519 import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig @@ -25,7 +24,6 @@ import org.apache.commons.lang3.NotImplementedException import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException -import javax.crypto.KeyAgreement import javax.inject.Inject import javax.inject.Singleton @@ -112,6 +110,11 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context TODO("not implemented") } + override fun getPodId(): Id { + // TODO: return something meaningful here + return Id.fromInt(4243) + } + companion object { private const val CONNECT_TIMEOUT_MS = 5000 diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt index 186585676c..e437bd23a9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommand.kt @@ -20,7 +20,7 @@ open class BleCommand(val data: ByteArray) { } override fun toString(): String { - return "Raw command: [${data.toHex()}]"; + return "Raw command: [${data.toHex()}]" } override fun hashCode(): Int { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt new file mode 100644 index 0000000000..c5d3d0ead1 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt @@ -0,0 +1,3 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +class MessageIOException(override val cause: Throwable) : Exception(cause) \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index a763193b77..3340d1daf1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -50,7 +50,6 @@ class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map BleCommandSuccess() - is PayloadJoinerActionReject -> BleCommandFail() - } - bleIO.sendAndConfirmPacket(CharacteristicType.CMD, finalCmd.data) - val fullPayload = joiner.bytes() - return MessagePacket.parse(fullPayload) } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt index d2f754e396..51af76eef1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt @@ -1,31 +1,108 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io -import java.io.ByteArrayOutputStream +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.CrcMismatchException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.IncorrectPacketException +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.crc32 +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.BlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.FirstBlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.LastBlePacket +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.packet.LastOptionalPlusOneBlePacket +import java.lang.Integer.min +import java.nio.ByteBuffer +import java.util.* -sealed class PayloadJoinerAction - -class PayloadJoinerActionAccept : PayloadJoinerAction() -class PayloadJoinerActionReject(val idx: Byte) : PayloadJoinerAction() - -class PayloadJoiner { +@ExperimentalUnsignedTypes +class PayloadJoiner(private val firstPacket: ByteArray) { var oneExtra: Boolean = false + val fullFragments: Int + var crc: Long = 0 + private var expectedIndex = 0 + private val fragments: LinkedList = LinkedList() - private val payload = ByteArrayOutputStream() + init { + if (firstPacket.size < 2) { + throw IncorrectPacketException(0, firstPacket) + } + fullFragments = firstPacket[1].toInt() + when { + // Without middle packets + firstPacket.size < FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS -> + throw IncorrectPacketException(0, firstPacket) - fun start(payload: ByteArray): Int { - TODO("not implemented") + fullFragments == 0 -> { + crc = ByteBuffer.wrap(firstPacket.copyOfRange(2, 6)).int.toUInt().toLong() + val rest = firstPacket[6] + val end = min(rest + 7, BlePacket.MAX_LEN) + oneExtra = rest + 7 > end + fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, end)) + if (end > firstPacket.size) { + throw IncorrectPacketException(0, firstPacket) + } + } + + // With middle packets + firstPacket.size < BlePacket.MAX_LEN -> + throw IncorrectPacketException(0, firstPacket) + + else -> { + fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITH_MIDDLE_PACKETS, BlePacket.MAX_LEN)) + } + } } - fun accumulate(payload: ByteArray): PayloadJoinerAction { - TODO("not implemented") + fun accumulate(packet: ByteArray) { + if (packet.size < 3) { // idx, size, at least 1 byte of payload + throw IncorrectPacketException((expectedIndex + 1).toByte(), packet) + } + val idx = packet[0].toInt() + if (idx != expectedIndex + 1) { + throw IncorrectPacketException((expectedIndex + 1).toByte(), packet) + } + expectedIndex++ + when { + idx < fullFragments -> { // this is a middle fragment + if (packet.size < BlePacket.MAX_LEN) { + throw IncorrectPacketException(idx.toByte(), packet) + } + fragments.add(packet.copyOfRange(1, BlePacket.MAX_LEN)) + } + + idx == fullFragments -> { // this is the last fragment + if (packet.size < LastBlePacket.HEADER_SIZE) { + throw IncorrectPacketException(idx.toByte(), packet) + } + crc = ByteBuffer.wrap(packet.copyOfRange(2, 6)).int.toUInt().toLong() + val rest = packet[1].toInt() + val end = min(rest, BlePacket.MAX_LEN) + if (packet.size < end) { + throw IncorrectPacketException(idx.toByte(), packet) + } + oneExtra = rest + LastBlePacket.HEADER_SIZE > end + fragments.add(packet.copyOfRange(LastBlePacket.HEADER_SIZE, BlePacket.MAX_LEN)) + } + + idx > fullFragments -> { // this is the extra fragment + val size = packet[1].toInt() + if (packet.size < LastOptionalPlusOneBlePacket.HEADER_SIZE + size) { + throw IncorrectPacketException(idx.toByte(), packet) + } + + fragments.add(packet.copyOfRange(LastOptionalPlusOneBlePacket.HEADER_SIZE, LastOptionalPlusOneBlePacket.HEADER_SIZE + size)) + } + } } - fun finalize(): PayloadJoinerAction { - TODO("not implemented") + fun finalize(): ByteArray { + val totalLen = fragments.fold(0, { acc, elem -> acc + elem.size }) + val bb = ByteBuffer.allocate(totalLen) + fragments.map { fragment -> bb.put(fragment) } + bb.flip() + val bytes = bb.array() + if (bytes.crc32() != crc) { + throw CrcMismatchException(bytes.crc32(), crc, bytes) + } + return bytes.copyOfRange(0, bytes.size) } - fun bytes(): ByteArray { - TODO("not implemented") - } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt index 6a0c60139b..bd5e5811db 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt @@ -25,7 +25,7 @@ internal class PayloadSplitter(private val payload: ByteArray) { ret.add(LastOptionalPlusOneBlePacket( index = 1, payload = payload.copyOfRange(end, payload.size), - size = (payload.size-end).toByte(), + size = (payload.size - end).toByte(), )) } return ret @@ -57,7 +57,7 @@ internal class PayloadSplitter(private val payload: ByteArray) { if (rest > LastBlePacket.CAPACITY) { ret.add(LastOptionalPlusOneBlePacket( index = (middleFragments + 2).toByte(), - size = (rest-LastBlePacket.CAPACITY).toByte(), + size = (rest - LastBlePacket.CAPACITY).toByte(), payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + LastBlePacket.CAPACITY, payload.size), )) } @@ -65,7 +65,7 @@ internal class PayloadSplitter(private val payload: ByteArray) { } } -private fun ByteArray.crc32(): Long { +internal fun ByteArray.crc32(): Long { val crc = CRC32() crc.update(this) return crc.value diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index acdd237431..bd67c5a4d3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -8,8 +8,8 @@ sealed class BlePacket { companion object { - const val MAX_BLE_PACKET_LEN = 20 - const val MAX_BLE_BUFFER_LEN = MAX_BLE_PACKET_LEN + 1 // we use this as the size allocated for the ByteBuffer + const val MAX_LEN = 20 + const val MAX_BLE_BUFFER_LEN = MAX_LEN + 1 // we use this as the size allocated for the ByteBuffer } } @@ -35,8 +35,11 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val companion object { - internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = 13 // we are using all fields - internal const val CAPACITY_WITH_MIDDLE_PACKETS = 18 // we are not using crc32 or size + internal const val HEADER_SIZE_WITHOUT_MIDDLE_PACKETS = 7 // we are using all fields + internal const val HEADER_SIZE_WITH_MIDDLE_PACKETS = 2 + + internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = MAX_LEN - HEADER_SIZE_WITHOUT_MIDDLE_PACKETS // we are using all fields + internal const val CAPACITY_WITH_MIDDLE_PACKETS = MAX_LEN - HEADER_SIZE_WITH_MIDDLE_PACKETS // we are not using crc32 or size internal const val CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET = 18 } } @@ -70,7 +73,8 @@ data class LastBlePacket(val index: Byte, val size: Byte, val payload: ByteArray companion object { - internal const val CAPACITY = 14 + internal const val HEADER_SIZE = 6 + internal const val CAPACITY = MAX_LEN - HEADER_SIZE } } @@ -79,5 +83,11 @@ data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray, override fun asByteArray(): ByteArray { return byteArrayOf(index, size) + payload } + + companion object { + + internal const val HEADER_SIZE = 2 + internal const val CAPACITY = MAX_LEN - HEADER_SIZE + } } From 39408ac53583bfe673a5e62a67f50b90d700c969 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sat, 27 Feb 2021 13:39:47 +0100 Subject: [PATCH 064/649] BLE LTK: define all the steps --- .../dash/driver/comm/ltk/LTKExchanger.kt | 66 +++++++++++++++---- 1 file changed, 53 insertions(+), 13 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 3641435a69..7b7fa8dcb1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -6,8 +6,10 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding import info.nightscout.androidaps.utils.extensions.hexStringToByteArray +import info.nightscout.androidaps.utils.extensions.toHex import java.security.SecureRandom internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { @@ -17,6 +19,8 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) val nodeId = controllerId.increment() private var seq: Byte = 1 + private var ltk = ByteArray(0) + private var noncePrefix = ByteArray(0) init { val random = SecureRandom() @@ -36,28 +40,36 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI // read SPS1 val podSps1 = msgIO.receiveMessage() aapsLogger.info(LTag.PUMPBTCOMM, "Received message: %s", podSps1) -/* + processSps1FromPod(podSps1) + + seq++ + // send SPS2 - var sps2 = PairMessage() + val sps2 = sps2() msgIO.sendMesssage(sps2.messagePacket) // read SPS2 + val podSps2 = msgIO.receiveMessage() + validatePodSps2(podSps2) // send SP0GP0 - msgIO.sendMesssage(sps2.messagePacket) + msgIO.sendMesssage(sp0gp0().messagePacket) // read P0 + + //TODO: if we fail to read or validate p0 will lead to undefined state + // it could be that: + // - the pod answered with p0 and we did not receive/could not process the answer + // - the pod answered with some sort of error val p0 = msgIO.receiveMessage() -*/ - return null + validateP0(p0) + + return LTK( + ltk = ltk, + noncePrefix = noncePrefix, + ) } - private fun sp2(): ByteArray { - // This is GetPodStatus command, with page 0 parameter. - // We could replace that in the future with the serialized GetPodStatus() - return GET_POD_STATUS_HEX_COMMAND.hexStringToByteArray() - } - - fun sp1sp2(sp1: ByteArray, sp2: ByteArray): PairMessage { + private fun sp1sp2(sp1: ByteArray, sp2: ByteArray): PairMessage { val payload = StringLengthPrefixEncoding.formatKeys( arrayOf("SP1=", ",SP2="), arrayOf(sp1, sp2), @@ -70,7 +82,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI ) } - fun sps1(): PairMessage { + private fun sps1(): PairMessage { val publicKey = X25519.publicFromPrivate(privateKey) val payload = StringLengthPrefixEncoding.formatKeys( arrayOf("SPS1="), @@ -84,6 +96,34 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI ) } + private fun processSps1FromPod(msg: MessagePacket) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS1 from pod: ${msg.payload.toHex()}") + + } + + private fun sps2(): PairMessage { + TODO("implement") + } + + private fun validatePodSps2(podSps2: MessagePacket) { + TODO("implement") + + } + + private fun sp2(): ByteArray { + // This is GetPodStatus command, with page 0 parameter. + // We could replace that in the future with the serialized GetPodStatus() + return GET_POD_STATUS_HEX_COMMAND.hexStringToByteArray() + } + + private fun sp0gp0(): PairMessage { + TODO("implement") + } + + private fun validateP0(p0: MessagePacket) { + TODO("implement") + + } companion object { private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. From ddfbd2e7bdff41c9d01c7eee63b7f3b20fc94c36 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sat, 27 Feb 2021 18:33:04 +0100 Subject: [PATCH 065/649] dash ble tlk: start generating keys --- .../dash/driver/comm/ltk/LTKExchanger.kt | 47 +++++++++++++++---- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 7b7fa8dcb1..455f0f1575 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -1,21 +1,32 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk +import com.google.crypto.tink.mac.AesCmacKeyManager +import com.google.crypto.tink.proto.AesCmac import com.google.crypto.tink.subtle.X25519 + import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.MessageIOException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding import info.nightscout.androidaps.utils.extensions.hexStringToByteArray import info.nightscout.androidaps.utils.extensions.toHex +import org.spongycastle.crypto.engines.AESEngine import java.security.SecureRandom internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { - private val privateKey = X25519.generatePrivateKey() - private val nonce = ByteArray(16) + private val pdmPrivate = X25519.generatePrivateKey() + private val pdmPublic = X25519.publicFromPrivate(pdmPrivate) + private var podPublic = ByteArray(PUBLIC_KEY_SIZE) + private var podNonce = ByteArray(NONCE_SIZE) + private val pdmNonce = ByteArray(NONCE_SIZE) + private val confPdm = ByteArray(CONF_SIZE) + private val confPod = ByteArray(CONF_SIZE) + private val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) val nodeId = controllerId.increment() private var seq: Byte = 1 @@ -24,7 +35,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI init { val random = SecureRandom() - random.nextBytes(nonce) + random.nextBytes(pdmNonce) } fun negotiateLTKAndNonce(): LTK? { @@ -41,9 +52,9 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI val podSps1 = msgIO.receiveMessage() aapsLogger.info(LTag.PUMPBTCOMM, "Received message: %s", podSps1) processSps1FromPod(podSps1) - + // now we have all the data to generate: confPod, confPdm, ltk and noncePrefix + generateKeys() seq++ - // send SPS2 val sps2 = sps2() msgIO.sendMesssage(sps2.messagePacket) @@ -52,6 +63,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI val podSps2 = msgIO.receiveMessage() validatePodSps2(podSps2) + seq++ // send SP0GP0 msgIO.sendMesssage(sp0gp0().messagePacket) // read P0 @@ -83,7 +95,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI } private fun sps1(): PairMessage { - val publicKey = X25519.publicFromPrivate(privateKey) + val publicKey = X25519.publicFromPrivate(pdmPrivate) val payload = StringLengthPrefixEncoding.formatKeys( arrayOf("SPS1="), arrayOf(publicKey + nonce), @@ -98,7 +110,11 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private fun processSps1FromPod(msg: MessagePacket) { aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS1 from pod: ${msg.payload.toHex()}") - + if (msg.payload.size != 48) { + throw MessageIOException() + } + podPublic = msg.payload.copyOfRange(0, PUBLIC_KEY_SIZE) + podNonce = msg.payload.copyOfRange(PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE+ NONCE_SIZE) } private fun sps2(): PairMessage { @@ -124,8 +140,23 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI TODO("implement") } - companion object { + fun generateKeys() { + val curveLTK = X25519.computeSharedSecret(pdmPrivate, podPublic) + aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, donna key: ${curveLTK.toHex()}") + //first_key = data.pod_public[-4:] + data.pdm_public[-4:] + data.pod_nonce[-4:] + data.pdm_nonce[-4:] + + val firstKey = podPublic.copyOfRange(podPublic.size-4, podPublic.size) + + pdmPublic.copyOfRange(pdmPublic.size-4, pdmPublic.size) + + podNonce.copyOfRange(podNonce.size-4, podNonce.size) + + pdmNonce.copyOfRange(pdmNonce.size-4, pdmNonce.size) + aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, first key: ${firstKey.toHex()}") + } + + companion object { + private val PUBLIC_KEY_SIZE = 32 + private val NONCE_SIZE = 16 + private val CONF_SIZE = 16 private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. } } \ No newline at end of file From ddb1c1834935fd1353dea1e41bfa20bd318d0093 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sat, 27 Feb 2021 20:45:01 +0100 Subject: [PATCH 066/649] ble ltk: implement encryption and message parsing --- .../CouldNotParseMessageException.kt | 5 ++ .../comm/exceptions/MessageIOException.kt | 5 +- .../dash/driver/comm/ltk/LTKExchanger.kt | 40 +++++++++---- .../dash/driver/comm/message/MessageIO.kt | 1 - .../dash/driver/comm/message/MessagePacket.kt | 58 ++++++++++++++++++- .../dash/driver/comm/message/PayloadJoiner.kt | 15 ++--- 6 files changed, 100 insertions(+), 24 deletions(-) create mode 100644 omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt new file mode 100644 index 0000000000..65df8175e6 --- /dev/null +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions + +import info.nightscout.androidaps.utils.extensions.toHex + +class CouldNotParseMessageException(val payload: ByteArray): Exception("Could not parse message payload: ${payload.toHex()}") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt index c5d3d0ead1..ea4201bc02 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt @@ -1,3 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class MessageIOException(override val cause: Throwable) : Exception(cause) \ No newline at end of file +class MessageIOException : Exception { + constructor(msg: String): super(msg) + constructor(cause: Throwable): super(cause) +} \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index 455f0f1575..cd9dde9b41 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -1,9 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk -import com.google.crypto.tink.mac.AesCmacKeyManager -import com.google.crypto.tink.proto.AesCmac import com.google.crypto.tink.subtle.X25519 - import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id @@ -15,6 +12,8 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message. import info.nightscout.androidaps.utils.extensions.hexStringToByteArray import info.nightscout.androidaps.utils.extensions.toHex import org.spongycastle.crypto.engines.AESEngine +import org.spongycastle.crypto.macs.CMac +import org.spongycastle.crypto.params.KeyParameter import java.security.SecureRandom internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgIO: MessageIO) { @@ -30,7 +29,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) val nodeId = controllerId.increment() private var seq: Byte = 1 - private var ltk = ByteArray(0) + private var ltk = ByteArray(CMAC_SIZE) private var noncePrefix = ByteArray(0) init { @@ -98,7 +97,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI val publicKey = X25519.publicFromPrivate(pdmPrivate) val payload = StringLengthPrefixEncoding.formatKeys( arrayOf("SPS1="), - arrayOf(publicKey + nonce), + arrayOf(publicKey + pdmNonce), ) return PairMessage( sequenceNumber = seq, @@ -111,10 +110,10 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private fun processSps1FromPod(msg: MessagePacket) { aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS1 from pod: ${msg.payload.toHex()}") if (msg.payload.size != 48) { - throw MessageIOException() + throw MessageIOException("Invalid payload size") } podPublic = msg.payload.copyOfRange(0, PUBLIC_KEY_SIZE) - podNonce = msg.payload.copyOfRange(PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE+ NONCE_SIZE) + podNonce = msg.payload.copyOfRange(PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE + NONCE_SIZE) } private fun sps2(): PairMessage { @@ -144,19 +143,36 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI fun generateKeys() { val curveLTK = X25519.computeSharedSecret(pdmPrivate, podPublic) aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, donna key: ${curveLTK.toHex()}") - //first_key = data.pod_public[-4:] + data.pdm_public[-4:] + data.pod_nonce[-4:] + data.pdm_nonce[-4:] - val firstKey = podPublic.copyOfRange(podPublic.size-4, podPublic.size) - + pdmPublic.copyOfRange(pdmPublic.size-4, pdmPublic.size) - + podNonce.copyOfRange(podNonce.size-4, podNonce.size) - + pdmNonce.copyOfRange(pdmNonce.size-4, pdmNonce.size) + //first_key = data.pod_public[-4:] + data.pdm_public[-4:] + data.pod_nonce[-4:] + data.pdm_nonce[-4:] + val firstKey = podPublic.copyOfRange(podPublic.size - 4, podPublic.size) + + pdmPublic.copyOfRange(pdmPublic.size - 4, pdmPublic.size)+ + podNonce.copyOfRange(podNonce.size - 4, podNonce.size)+ + pdmNonce.copyOfRange(pdmNonce.size - 4, pdmNonce.size) aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, first key: ${firstKey.toHex()}") + + val aesEngine = AESEngine() + val intermediateMac = CMac(aesEngine) + intermediateMac.init(KeyParameter(firstKey)) + intermediateMac.update(curveLTK, 0, curveLTK.size) + val intermediateKey = ByteArray(CMAC_SIZE) + intermediateMac.doFinal(intermediateKey, 0) + aapsLogger.debug(LTag.PUMPBTCOMM, "Intermediate key: ${intermediateKey.toHex()}") + + val ltkMac = CMac(aesEngine) + ltkMac.init(KeyParameter(firstKey)) + ltkMac.update(curveLTK, 0, curveLTK.size) + intermediateMac.doFinal(ltk, 0) + aapsLogger.debug(LTag.PUMPBTCOMM, "LTK: ${ltk.toHex()}") + } companion object { + private val PUBLIC_KEY_SIZE = 32 private val NONCE_SIZE = 16 private val CONF_SIZE = 16 + private val CMAC_SIZE = 16 private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt index 88e6a5dde4..4b67f33167 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -36,7 +36,6 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { bleIO.flushIncomingQueues() } - @kotlin.ExperimentalUnsignedTypes fun receiveMessage(): MessagePacket { val expectRTS = bleIO.receivePacket(CharacteristicType.CMD) if (BleCommand(expectRTS) != BleCommandRTS()) { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index d9cd686b4c..3563745ffe 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotParseMessageException import java.nio.ByteBuffer /*** @@ -69,9 +70,56 @@ data class MessagePacket( companion object { private val MAGIC_PATTERN = "TW" // all messages start with this string + private val HEADER_SIZE = 16 fun parse(payload: ByteArray): MessagePacket { - TODO("implement message header parsing") + if (payload.size < HEADER_SIZE) { + throw CouldNotParseMessageException(payload) + } + if (payload.copyOfRange(0, 2).toString() != "TW") { + throw info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotParseMessageException(payload) + } + val f1 = Flag(payload[2].toInt()) + val sas = f1.get(3) != 0 + val tfs = f1.get(4) != 0 + val version = ((f1.get(0) shl 2) or (f1.get(1) shl 1) or (f1.get(2) shl 0)).toShort() + val eqos = (f1.get(7) or (f1.get(6) shl 1) or (f1.get(5) shl 2)).toShort() + + val f2 = Flag(payload[3].toInt()) + val ack = f2.get(0) != 0 + val priority = f2.get(1) != 0 + val lastMessage = f2.get(2) != 0 + val gateway = f2.get(3) != 0 + val type = MessageType.byValue((f1.get(7) or (f1.get(6) shl 1) or (f1.get(5) shl 2) or (f1.get(4) shl 3)).toByte()) + if (version.toInt() != 0) { + throw CouldNotParseMessageException(payload) + } + val sequenceNumber = payload[4] + val ackNumber = payload[5] + val size = (payload[6].toInt() shl 3) or (payload[7].toInt() ushr 5) + if (size + HEADER_SIZE > payload.size) { + throw CouldNotParseMessageException(payload) + } + val payloadEnd = 16 + size + + if (type == MessageType.ENCRYPTED) 8 + else 0 + + return MessagePacket( + type = type, + ack = ack, + eqos = eqos, + priority = priority, + lastMessage = lastMessage, + gateway = gateway, + sas = sas, + tfs = tfs, + version = version, + sequenceNumber = payload[4], + ackNumber = payload[5], + source = Id(payload.copyOfRange(8, 12)), + destination = Id(payload.copyOfRange(12, 16)), + payload = payload.copyOfRange(16, payloadEnd), + ) } } } @@ -85,8 +133,12 @@ private class Flag(var value: Int = 0) { value = value or mask } - fun get(idx: Byte): Boolean { + fun get(idx: Byte): Int { val mask = 1 shl (7 - idx) - return value and mask != 0 + if (value and mask == 0) { + return 0 + } + return 1 + } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt index 51af76eef1..9b383b5f22 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt @@ -11,7 +11,6 @@ import java.lang.Integer.min import java.nio.ByteBuffer import java.util.* -@ExperimentalUnsignedTypes class PayloadJoiner(private val firstPacket: ByteArray) { var oneExtra: Boolean = false @@ -30,8 +29,8 @@ class PayloadJoiner(private val firstPacket: ByteArray) { firstPacket.size < FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS -> throw IncorrectPacketException(0, firstPacket) - fullFragments == 0 -> { - crc = ByteBuffer.wrap(firstPacket.copyOfRange(2, 6)).int.toUInt().toLong() + fullFragments == 0 -> { + crc = ByteBuffer.wrap(firstPacket.copyOfRange(2, 6)).int.toUnsignedLong() val rest = firstPacket[6] val end = min(rest + 7, BlePacket.MAX_LEN) oneExtra = rest + 7 > end @@ -42,10 +41,10 @@ class PayloadJoiner(private val firstPacket: ByteArray) { } // With middle packets - firstPacket.size < BlePacket.MAX_LEN -> + firstPacket.size < BlePacket.MAX_LEN -> throw IncorrectPacketException(0, firstPacket) - else -> { + else -> { fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITH_MIDDLE_PACKETS, BlePacket.MAX_LEN)) } } @@ -72,7 +71,7 @@ class PayloadJoiner(private val firstPacket: ByteArray) { if (packet.size < LastBlePacket.HEADER_SIZE) { throw IncorrectPacketException(idx.toByte(), packet) } - crc = ByteBuffer.wrap(packet.copyOfRange(2, 6)).int.toUInt().toLong() + crc = ByteBuffer.wrap(packet.copyOfRange(2, 6)).int.toUnsignedLong() val rest = packet[1].toInt() val end = min(rest, BlePacket.MAX_LEN) if (packet.size < end) { @@ -105,4 +104,6 @@ class PayloadJoiner(private val firstPacket: ByteArray) { return bytes.copyOfRange(0, bytes.size) } -} \ No newline at end of file +} + +private fun Int.toUnsignedLong() = this.toLong() and 0xffffffffL \ No newline at end of file From ee0ac46c5a9d2ef6ca414327e2ba3d3b8060eceb Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sun, 28 Feb 2021 18:21:00 +0100 Subject: [PATCH 067/649] Finish implementing the LTK exchange On the fake pod: ``` INFO[0067] LTK 21f4a9d825ce5e57bad5b4958c6ff95e ``` Logcat: ``` 2021-02-28 18:21:04.763 19530-22490/info.nightscout.androidaps I/PUMPCOMM: [AsyncTask #4]: [OmnipodDashBleManagerImpl.connect():86]: Got LTK: 21f4a9d825ce5e57bad5b4958c6ff95e `` --- .../driver/comm/OmnipodDashBleManagerImpl.kt | 14 +- .../CouldNotParseMessageException.kt | 2 +- .../comm/exceptions/MessageIOException.kt | 4 +- .../pump/omnipod/dash/driver/comm/ltk/LTK.kt | 3 +- .../dash/driver/comm/ltk/LTKExchanger.kt | 150 +++++++++++++----- .../dash/driver/comm/message/MessageIO.kt | 2 +- .../dash/driver/comm/message/MessagePacket.kt | 14 +- .../dash/driver/comm/message/PayloadJoiner.kt | 26 +-- .../message/StringLengthPrefixEncoding.kt | 31 +++- .../dash/driver/comm/packet/BlePacket.kt | 28 ++-- .../pump/omnipod/dash/util/Functions.kt | 2 +- 11 files changed, 191 insertions(+), 85 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 1f8c9ed5b4..50b50d7e07 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -21,6 +21,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEven import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command import io.reactivex.Observable import org.apache.commons.lang3.NotImplementedException +import info.nightscout.androidaps.utils.extensions.toHex import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException @@ -96,8 +97,10 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context val ltkExchanger = LTKExchanger(aapsLogger, msgIO) emitter.onNext(PodEvent.Pairing) - val ltk = ltkExchanger.negotiateLTKAndNonce() - aapsLogger.info(LTag.PUMPCOMM, "Got LTK and Nonce Prefix: ${ltk}") + val ltk = ltkExchanger.negotiateLTK() + + aapsLogger.info(LTag.PUMPCOMM, "Got LTK: ${ltk.ltk.toHex()}") + emitter.onNext(PodEvent.Connected(PodScanner.POD_ID_NOT_ACTIVATED)) // TODO supply actual pod id emitter.onComplete() @@ -110,14 +113,9 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context TODO("not implemented") } - override fun getPodId(): Id { - // TODO: return something meaningful here - return Id.fromInt(4243) - } - companion object { - private const val CONNECT_TIMEOUT_MS = 5000 + private const val CONNECT_TIMEOUT_MS = 7000 const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt index 65df8175e6..5e10a0bb1e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import info.nightscout.androidaps.utils.extensions.toHex -class CouldNotParseMessageException(val payload: ByteArray): Exception("Could not parse message payload: ${payload.toHex()}") \ No newline at end of file +class CouldNotParseMessageException(val payload: ByteArray) : Exception("Could not parse message payload: ${payload.toHex()}") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt index ea4201bc02..30cbac205b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions class MessageIOException : Exception { - constructor(msg: String): super(msg) - constructor(cause: Throwable): super(cause) + constructor(msg: String) : super(msg) + constructor(cause: Throwable) : super(cause) } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt index 407d00a289..06c497ce18 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt @@ -1,8 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk -data class LTK(val ltk: ByteArray, val noncePrefix: ByteArray) { +data class LTK(val ltk: ByteArray) { init { require(ltk.size == 16) - require(noncePrefix.size == 16) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt index cd9dde9b41..330ae955cf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt @@ -3,12 +3,14 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk import com.google.crypto.tink.subtle.X25519 import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManagerImpl import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.MessageIOException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.StringLengthPrefixEncoding.Companion.parseKeys import info.nightscout.androidaps.utils.extensions.hexStringToByteArray import info.nightscout.androidaps.utils.extensions.toHex import org.spongycastle.crypto.engines.AESEngine @@ -23,21 +25,19 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private var podPublic = ByteArray(PUBLIC_KEY_SIZE) private var podNonce = ByteArray(NONCE_SIZE) private val pdmNonce = ByteArray(NONCE_SIZE) - private val confPdm = ByteArray(CONF_SIZE) - private val confPod = ByteArray(CONF_SIZE) - + private val pdmConf = ByteArray(CMAC_SIZE) + private val podConf = ByteArray(CMAC_SIZE) private val controllerId = Id.fromInt(OmnipodDashBleManagerImpl.CONTROLLER_ID) val nodeId = controllerId.increment() private var seq: Byte = 1 private var ltk = ByteArray(CMAC_SIZE) - private var noncePrefix = ByteArray(0) init { val random = SecureRandom() random.nextBytes(pdmNonce) } - fun negotiateLTKAndNonce(): LTK? { + fun negotiateLTK(): LTK { // send SP1, SP2 var sp1sp2 = sp1sp2(nodeId.address, sp2()) msgIO.sendMesssage(sp1sp2.messagePacket) @@ -49,7 +49,6 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI // read SPS1 val podSps1 = msgIO.receiveMessage() - aapsLogger.info(LTag.PUMPBTCOMM, "Received message: %s", podSps1) processSps1FromPod(podSps1) // now we have all the data to generate: confPod, confPdm, ltk and noncePrefix generateKeys() @@ -67,22 +66,22 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI msgIO.sendMesssage(sp0gp0().messagePacket) // read P0 - //TODO: if we fail to read or validate p0 will lead to undefined state - // it could be that: + // TODO: failing to read or validate p0 will lead to undefined state + // It could be that: // - the pod answered with p0 and we did not receive/could not process the answer // - the pod answered with some sort of error + // But if sps2 conf value is incorrect, then we would probablysee this when receiving the pod podSps2(to test) val p0 = msgIO.receiveMessage() validateP0(p0) return LTK( ltk = ltk, - noncePrefix = noncePrefix, ) } private fun sp1sp2(sp1: ByteArray, sp2: ByteArray): PairMessage { val payload = StringLengthPrefixEncoding.formatKeys( - arrayOf("SP1=", ",SP2="), + arrayOf(SP1, SP2), arrayOf(sp1, sp2), ) return PairMessage( @@ -94,10 +93,9 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI } private fun sps1(): PairMessage { - val publicKey = X25519.publicFromPrivate(pdmPrivate) val payload = StringLengthPrefixEncoding.formatKeys( arrayOf("SPS1="), - arrayOf(publicKey + pdmNonce), + arrayOf(pdmPublic + pdmNonce), ) return PairMessage( sequenceNumber = seq, @@ -109,20 +107,41 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private fun processSps1FromPod(msg: MessagePacket) { aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS1 from pod: ${msg.payload.toHex()}") - if (msg.payload.size != 48) { + + val payload = parseKeys(arrayOf(SPS1), msg.payload)[0] + if (payload.size != 48) { throw MessageIOException("Invalid payload size") } - podPublic = msg.payload.copyOfRange(0, PUBLIC_KEY_SIZE) - podNonce = msg.payload.copyOfRange(PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE + NONCE_SIZE) + podPublic = payload.copyOfRange(0, PUBLIC_KEY_SIZE) + podNonce = payload.copyOfRange(PUBLIC_KEY_SIZE, PUBLIC_KEY_SIZE + NONCE_SIZE) } private fun sps2(): PairMessage { - TODO("implement") + val payload = StringLengthPrefixEncoding.formatKeys( + arrayOf(SPS2), + arrayOf(pdmConf), + ) + return PairMessage( + sequenceNumber = seq, + source = controllerId, + destination = nodeId, + payload = payload, + ) } - private fun validatePodSps2(podSps2: MessagePacket) { - TODO("implement") + private fun validatePodSps2(msg: MessagePacket) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Received SPS2 from pod: ${msg.payload.toHex()}") + val payload = parseKeys(arrayOf(SPS2), msg.payload)[0] + aapsLogger.debug(LTag.PUMPBTCOMM, "SPS2 payload from pod: ${payload.toHex()}") + + if (payload.size != CMAC_SIZE) { + throw MessageIOException("Invalid payload size") + } + if (!podConf.contentEquals(payload)) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Received invalid podConf. Expected: ${podConf.toHex()}. Got: ${payload.toHex()}") + throw MessageIOException("Invalid podConf value received") + } } private fun sp2(): ByteArray { @@ -132,39 +151,76 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI } private fun sp0gp0(): PairMessage { - TODO("implement") + val payload = SP0GP0.toByteArray() + return PairMessage( + sequenceNumber = seq, + source = controllerId, + destination = nodeId, + payload = payload, + ) } - private fun validateP0(p0: MessagePacket) { - TODO("implement") + private fun validateP0(msg: MessagePacket) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Received P0 from pod: ${msg.payload.toHex()}") + val payload = parseKeys(arrayOf(P0), msg.payload)[0] + aapsLogger.debug(LTag.PUMPBTCOMM, "P0 payload from pod: ${payload.toHex()}") + if (!payload.contentEquals(UNKNOWN_P0_PAYLOAD)) { + throw MessageIOException("Invalid P0 payload received") + } } fun generateKeys() { val curveLTK = X25519.computeSharedSecret(pdmPrivate, podPublic) - aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, donna key: ${curveLTK.toHex()}") - //first_key = data.pod_public[-4:] + data.pdm_public[-4:] + data.pod_nonce[-4:] + data.pdm_nonce[-4:] val firstKey = podPublic.copyOfRange(podPublic.size - 4, podPublic.size) + - pdmPublic.copyOfRange(pdmPublic.size - 4, pdmPublic.size)+ - podNonce.copyOfRange(podNonce.size - 4, podNonce.size)+ + pdmPublic.copyOfRange(pdmPublic.size - 4, pdmPublic.size) + + podNonce.copyOfRange(podNonce.size - 4, podNonce.size) + pdmNonce.copyOfRange(pdmNonce.size - 4, pdmNonce.size) aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, first key: ${firstKey.toHex()}") - val aesEngine = AESEngine() - val intermediateMac = CMac(aesEngine) - intermediateMac.init(KeyParameter(firstKey)) - intermediateMac.update(curveLTK, 0, curveLTK.size) val intermediateKey = ByteArray(CMAC_SIZE) - intermediateMac.doFinal(intermediateKey, 0) - aapsLogger.debug(LTag.PUMPBTCOMM, "Intermediate key: ${intermediateKey.toHex()}") + aesCmac(firstKey, curveLTK, intermediateKey) - val ltkMac = CMac(aesEngine) - ltkMac.init(KeyParameter(firstKey)) - ltkMac.update(curveLTK, 0, curveLTK.size) - intermediateMac.doFinal(ltk, 0) - aapsLogger.debug(LTag.PUMPBTCOMM, "LTK: ${ltk.toHex()}") + val ltkData = byteArrayOf(2.toByte()) + + INTERMEDIAR_KEY_MAGIC_STRING + + podNonce + + pdmNonce + + byteArrayOf(0.toByte(), 1.toByte()) + aesCmac(intermediateKey, ltkData, ltk) + val confData = byteArrayOf(1.toByte()) + + INTERMEDIAR_KEY_MAGIC_STRING + + podNonce + + pdmNonce + + byteArrayOf(0.toByte(), 1.toByte()) + val confKey = ByteArray(CMAC_SIZE) + aesCmac(intermediateKey, confData, confKey) + + val pdmConfData = PDM_CONF_MAGIC_PREFIX + + pdmNonce + + podNonce + aesCmac(confKey, pdmConfData, pdmConf) + aapsLogger.debug(LTag.PUMPBTCOMM, "pdmConf: ${pdmConf.toHex()}") + + val podConfData = POD_CONF_MAGIC_PREFIX + + podNonce + + pdmNonce + aesCmac(confKey, podConfData, podConf) + aapsLogger.debug(LTag.PUMPBTCOMM, "podConf: ${podConf.toHex()}") + + if (BuildConfig.DEBUG) { + aapsLogger.debug(LTag.PUMPBTCOMM, "pdmPrivate: ${pdmPrivate.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "pdmPublic: ${pdmPublic.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "podPublic: ${podPublic.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "pdmNonce: ${pdmNonce.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "podNonce: ${podNonce.toHex()}") + + aapsLogger.debug(LTag.PUMPBTCOMM, "LTK, donna key: ${curveLTK.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "Intermediate key: ${intermediateKey.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "LTK: ${ltk.toHex()}") + aapsLogger.debug(LTag.PUMPBTCOMM, "Conf KEY: ${confKey.toHex()}") + } } companion object { @@ -172,7 +228,29 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI private val PUBLIC_KEY_SIZE = 32 private val NONCE_SIZE = 16 private val CONF_SIZE = 16 + private val CMAC_SIZE = 16 + + private val INTERMEDIAR_KEY_MAGIC_STRING = "TWIt".toByteArray() + private val PDM_CONF_MAGIC_PREFIX = "KC_2_U".toByteArray() + private val POD_CONF_MAGIC_PREFIX = "KC_2_V".toByteArray() + private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. + + private val SP1 = "SP1=" + private val SP2 = ",SP2=" + private val SPS1 = "SPS1=" + private val SPS2 = "SPS2=" + private val SP0GP0 = "SP0,GP0" + private val P0 = "P0=" + private val UNKNOWN_P0_PAYLOAD = byteArrayOf(0xa5.toByte()) } +} + +private fun aesCmac(key: ByteArray, data: ByteArray, result: ByteArray) { + val aesEngine = AESEngine() + val mac = CMac(aesEngine) + mac.init(KeyParameter(key)) + mac.update(data, 0, data.size) + mac.doFinal(result, 0) } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt index 4b67f33167..0af9d00ece 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessageIO.kt @@ -47,7 +47,7 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) { for (i in 1 until joiner.fullFragments + 1) { joiner.accumulate(bleIO.receivePacket(CharacteristicType.DATA)) } - if (joiner.oneExtra) { + if (joiner.oneExtraPacket) { joiner.accumulate(bleIO.receivePacket(CharacteristicType.DATA)) } val fullPayload = joiner.finalize() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt index 3563745ffe..6a6d800823 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/MessagePacket.kt @@ -76,8 +76,8 @@ data class MessagePacket( if (payload.size < HEADER_SIZE) { throw CouldNotParseMessageException(payload) } - if (payload.copyOfRange(0, 2).toString() != "TW") { - throw info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CouldNotParseMessageException(payload) + if (payload.copyOfRange(0, 2).decodeToString() != MAGIC_PATTERN) { + throw CouldNotParseMessageException(payload) } val f1 = Flag(payload[2].toInt()) val sas = f1.get(3) != 0 @@ -96,7 +96,7 @@ data class MessagePacket( } val sequenceNumber = payload[4] val ackNumber = payload[5] - val size = (payload[6].toInt() shl 3) or (payload[7].toInt() ushr 5) + val size = (payload[6].toInt() shl 3) or (payload[7].toUnsignedInt() ushr 5) if (size + HEADER_SIZE > payload.size) { throw CouldNotParseMessageException(payload) } @@ -114,8 +114,8 @@ data class MessagePacket( sas = sas, tfs = tfs, version = version, - sequenceNumber = payload[4], - ackNumber = payload[5], + sequenceNumber = sequenceNumber, + ackNumber = ackNumber, source = Id(payload.copyOfRange(8, 12)), destination = Id(payload.copyOfRange(12, 16)), payload = payload.copyOfRange(16, payloadEnd), @@ -141,4 +141,6 @@ private class Flag(var value: Int = 0) { return 1 } -} \ No newline at end of file +} + +internal fun Byte.toUnsignedInt() = this.toInt() and 0xff \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt index 9b383b5f22..2a6d772ac5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadJoiner.kt @@ -13,14 +13,14 @@ import java.util.* class PayloadJoiner(private val firstPacket: ByteArray) { - var oneExtra: Boolean = false + var oneExtraPacket: Boolean = false val fullFragments: Int var crc: Long = 0 private var expectedIndex = 0 private val fragments: LinkedList = LinkedList() init { - if (firstPacket.size < 2) { + if (firstPacket.size < FirstBlePacket.HEADER_SIZE_WITH_MIDDLE_PACKETS) { throw IncorrectPacketException(0, firstPacket) } fullFragments = firstPacket[1].toInt() @@ -32,20 +32,20 @@ class PayloadJoiner(private val firstPacket: ByteArray) { fullFragments == 0 -> { crc = ByteBuffer.wrap(firstPacket.copyOfRange(2, 6)).int.toUnsignedLong() val rest = firstPacket[6] - val end = min(rest + 7, BlePacket.MAX_LEN) - oneExtra = rest + 7 > end - fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, end)) + val end = min(rest + FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, BlePacket.MAX_SIZE) + oneExtraPacket = rest + FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS > end if (end > firstPacket.size) { throw IncorrectPacketException(0, firstPacket) } + fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, end)) } // With middle packets - firstPacket.size < BlePacket.MAX_LEN -> + firstPacket.size < BlePacket.MAX_SIZE -> throw IncorrectPacketException(0, firstPacket) else -> { - fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITH_MIDDLE_PACKETS, BlePacket.MAX_LEN)) + fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITH_MIDDLE_PACKETS, BlePacket.MAX_SIZE)) } } } @@ -61,10 +61,10 @@ class PayloadJoiner(private val firstPacket: ByteArray) { expectedIndex++ when { idx < fullFragments -> { // this is a middle fragment - if (packet.size < BlePacket.MAX_LEN) { + if (packet.size < BlePacket.MAX_SIZE) { throw IncorrectPacketException(idx.toByte(), packet) } - fragments.add(packet.copyOfRange(1, BlePacket.MAX_LEN)) + fragments.add(packet.copyOfRange(1, BlePacket.MAX_SIZE)) } idx == fullFragments -> { // this is the last fragment @@ -73,12 +73,12 @@ class PayloadJoiner(private val firstPacket: ByteArray) { } crc = ByteBuffer.wrap(packet.copyOfRange(2, 6)).int.toUnsignedLong() val rest = packet[1].toInt() - val end = min(rest, BlePacket.MAX_LEN) + val end = min(rest + LastBlePacket.HEADER_SIZE, BlePacket.MAX_SIZE) + oneExtraPacket = rest + LastBlePacket.HEADER_SIZE > end if (packet.size < end) { throw IncorrectPacketException(idx.toByte(), packet) } - oneExtra = rest + LastBlePacket.HEADER_SIZE > end - fragments.add(packet.copyOfRange(LastBlePacket.HEADER_SIZE, BlePacket.MAX_LEN)) + fragments.add(packet.copyOfRange(LastBlePacket.HEADER_SIZE, packet.size)) } idx > fullFragments -> { // this is the extra fragment @@ -106,4 +106,4 @@ class PayloadJoiner(private val firstPacket: ByteArray) { } -private fun Int.toUnsignedLong() = this.toLong() and 0xffffffffL \ No newline at end of file +internal fun Int.toUnsignedLong() = this.toLong() and 0xffffffffL \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt index b23e689d9d..7ec6048aed 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.MessageIOException +import info.nightscout.androidaps.utils.extensions.toHex import java.nio.ByteBuffer /*** @@ -9,8 +11,33 @@ class StringLengthPrefixEncoding { companion object { - fun parseKeys(keys: List): List { - TODO("not implemented") + private val LENGTH_BYTES = 2 + + fun parseKeys(keys: Array, payload: ByteArray): Array { + val ret = Array(keys.size, { ByteArray(0) }) + var remaining = payload + for ((index, key) in keys.withIndex()) { + when { + remaining.size < key.length -> + throw MessageIOException("Payload too short: ${payload.toHex()} for key: ${key}") + !(remaining.copyOfRange(0, key.length).decodeToString() == key) -> + throw MessageIOException("Key not found: ${key} in ${payload.toHex()}") + // last key can be empty, no length + index == keys.size - 1 && remaining.size == key.length -> + return ret + + remaining.size < key.length + LENGTH_BYTES -> + throw MessageIOException("Length not found: for ${key} in ${payload.toHex()}") + } + remaining = remaining.copyOfRange(key.length, remaining.size) + val length = (remaining[0].toUnsignedInt() shl 1) or remaining[1].toUnsignedInt() + if (length > remaining.size) { + throw MessageIOException("Payload too short, looking for length ${length} for ${key} in ${payload.toHex()}") + } + ret[index] = remaining.copyOfRange(LENGTH_BYTES, LENGTH_BYTES + length) + remaining = remaining.copyOfRange(LENGTH_BYTES + length, remaining.size) + } + return ret } fun formatKeys(keys: Array, payloads: Array): ByteArray { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index bd67c5a4d3..eb020c5b28 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -8,8 +8,7 @@ sealed class BlePacket { companion object { - const val MAX_LEN = 20 - const val MAX_BLE_BUFFER_LEN = MAX_LEN + 1 // we use this as the size allocated for the ByteBuffer + const val MAX_SIZE = 20 } } @@ -17,7 +16,7 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val override fun asByteArray(): ByteArray { val bb = ByteBuffer - .allocate(MAX_BLE_BUFFER_LEN) + .allocate(MAX_SIZE) .put(0) // index .put(totalFragments) // # of fragments except FirstBlePacket and LastOptionalPlusOneBlePacket crc32?.let { @@ -27,9 +26,12 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val bb.put(size) } bb.put(payload) - val ret = ByteArray(bb.position()) + + val pos = bb.position() + val ret = ByteArray(MAX_SIZE) bb.flip() - bb.get(ret) + bb.get(ret, 0, pos) + return ret } @@ -38,8 +40,8 @@ data class FirstBlePacket(val totalFragments: Byte, val payload: ByteArray, val internal const val HEADER_SIZE_WITHOUT_MIDDLE_PACKETS = 7 // we are using all fields internal const val HEADER_SIZE_WITH_MIDDLE_PACKETS = 2 - internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = MAX_LEN - HEADER_SIZE_WITHOUT_MIDDLE_PACKETS // we are using all fields - internal const val CAPACITY_WITH_MIDDLE_PACKETS = MAX_LEN - HEADER_SIZE_WITH_MIDDLE_PACKETS // we are not using crc32 or size + internal const val CAPACITY_WITHOUT_MIDDLE_PACKETS = MAX_SIZE - HEADER_SIZE_WITHOUT_MIDDLE_PACKETS // we are using all fields + internal const val CAPACITY_WITH_MIDDLE_PACKETS = MAX_SIZE - HEADER_SIZE_WITH_MIDDLE_PACKETS // we are not using crc32 or size internal const val CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET = 18 } } @@ -60,34 +62,34 @@ data class LastBlePacket(val index: Byte, val size: Byte, val payload: ByteArray override fun asByteArray(): ByteArray { val bb = ByteBuffer - .allocate(MAX_BLE_BUFFER_LEN) + .allocate(MAX_SIZE) .put(index) .put(size) .putInt(crc32.toInt()) .put(payload) - val ret = ByteArray(bb.position()) + val pos = bb.position() + val ret = ByteArray(MAX_SIZE) bb.flip() - bb.get(ret) + bb.get(ret, 0, pos) return ret } companion object { internal const val HEADER_SIZE = 6 - internal const val CAPACITY = MAX_LEN - HEADER_SIZE + internal const val CAPACITY = MAX_SIZE - HEADER_SIZE } } data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray, val size: Byte) : BlePacket() { override fun asByteArray(): ByteArray { - return byteArrayOf(index, size) + payload + return byteArrayOf(index, size) + payload + ByteArray(MAX_SIZE - payload.size - 2) } companion object { internal const val HEADER_SIZE = 2 - internal const val CAPACITY = MAX_LEN - HEADER_SIZE } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt index 96d8fbf667..54ad9b345f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt @@ -33,7 +33,7 @@ fun mapProfileToBasalProgram(profile: Profile): BasalProgram { if (previousBasalValue != null) { entries.add( BasalProgram.Segment( - (previousBasalValue!!.timeAsSeconds / 1800).toShort(), + (previousBasalValue.timeAsSeconds / 1800).toShort(), startSlotIndex, (PumpType.Omnipod_Dash.determineCorrectBasalSize(previousBasalValue.value) * 100).roundToInt() ) From b1f099c50693d56f0cb0b60eef54b01d35ba03cf Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sun, 28 Feb 2021 18:25:08 +0100 Subject: [PATCH 068/649] rename LTK to Pair --- .../omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt | 2 +- .../omnipod/dash/driver/comm/{ltk => pair}/LTKExchanger.kt | 6 +++--- .../omnipod/dash/driver/comm/{ltk => pair}/PairMessage.kt | 2 +- .../dash/driver/comm/{ltk/LTK.kt => pair/PairResult.kt} | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{ltk => pair}/LTKExchanger.kt (99%) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{ltk => pair}/PairMessage.kt (98%) rename omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/{ltk/LTK.kt => pair/PairResult.kt} (66%) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index 50b50d7e07..a658a6d5f1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk.LTKExchanger +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair.LTKExchanger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt similarity index 99% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt index 330ae955cf..cddb97bfaf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair import com.google.crypto.tink.subtle.X25519 import info.nightscout.androidaps.logging.AAPSLogger @@ -37,7 +37,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI random.nextBytes(pdmNonce) } - fun negotiateLTK(): LTK { + fun negotiateLTK(): PairResult { // send SP1, SP2 var sp1sp2 = sp1sp2(nodeId.address, sp2()) msgIO.sendMesssage(sp1sp2.messagePacket) @@ -74,7 +74,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI val p0 = msgIO.receiveMessage() validateP0(p0) - return LTK( + return PairResult( ltk = ltk, ) } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt similarity index 98% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt index af7fea3adb..f36baea723 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessagePacket diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt similarity index 66% rename from omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt rename to omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt index 06c497ce18..c2bdb921ef 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ltk/LTK.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt @@ -1,6 +1,6 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.ltk +package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair -data class LTK(val ltk: ByteArray) { +data class PairResult(val ltk: ByteArray) { init { require(ltk.size == 16) } From bf060da878302adcf4b6cbc745e641e44759be5c Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 18:42:17 +0100 Subject: [PATCH 069/649] Fix typo --- .../omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index afdfa1c25b..1b3c531ee9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -28,7 +28,7 @@ class SilenceAlertsCommand private constructor( override fun toString(): String { return "SilenceAlertsCommand{" + - "alterTypes=" + alertTypes + + "alertTypes=" + alertTypes + ", nonce=" + nonce + ", commandType=" + commandType + ", uniqueId=" + uniqueId + From 8e7e2450ae5db473fab91f88f0d843ab2d70703a Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 18:46:49 +0100 Subject: [PATCH 070/649] Update active alerts from default status response in Pod state --- .../dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index 229109a6d2..add92d9567 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -154,8 +154,7 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( podState.pulsesRemaining = response.reservoirPulsesRemaining podState.sequenceNumberOfLastProgrammingCommand = response.sequenceNumberOfLastProgrammingCommand podState.minutesSinceActivation = response.minutesSinceActivation - - // TODO active alerts + podState.activeAlerts = response.activeAlerts podState.lastUpdated = System.currentTimeMillis() store() From 57c2d2d9a1fd397b9aa86a511d3fe6ceb3e9ab75 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sun, 28 Feb 2021 19:11:42 +0100 Subject: [PATCH 071/649] Address review comments: - move think dependency to core_dependencies and make it's version configurable: https://github.com/0pen-dash/AndroidAPS/pull/10#discussion_r584329468 - add message string to exceptions. Renames --- build.gradle | 1 + core/core_dependencies.gradle | 2 +- omnipod-dash/build.gradle | 1 - .../omnipod/dash/driver/comm/exceptions/MessageIOException.kt | 2 +- .../omnipod/dash/driver/comm/message/CrcMismatchException.kt | 4 ++-- .../plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt | 4 +++- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index a3026de30d..fd870b3ad6 100644 --- a/build.gradle +++ b/build.gradle @@ -23,6 +23,7 @@ buildscript { commonscodec_version = '1.15' jodatime_version = '2.10.10' work_version = '2.5.0' + tink_version = '1.5.0' junit_version = '4.13.2' mockitoVersion = '3.7.7' diff --git a/core/core_dependencies.gradle b/core/core_dependencies.gradle index 25ecf5b36c..e5f68665f6 100644 --- a/core/core_dependencies.gradle +++ b/core/core_dependencies.gradle @@ -46,7 +46,7 @@ dependencies { //CryptoUtil api 'com.madgag.spongycastle:core:1.58.0.0' - + api "com.google.crypto.tink:tink-android:$tink_version" // Graphview cannot be upgraded api "com.jjoe64:graphview:4.0.1" diff --git a/omnipod-dash/build.gradle b/omnipod-dash/build.gradle index 34ca4406c5..bf7d1c99c1 100644 --- a/omnipod-dash/build.gradle +++ b/omnipod-dash/build.gradle @@ -22,5 +22,4 @@ dependencies { implementation "androidx.room:room-rxjava2:$room_version" kapt "androidx.room:room-compiler:$room_version" implementation 'com.github.guepardoapps:kulid:1.1.2.0' - implementation 'com.google.crypto.tink:tink-android:1.5.0' } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt index 30cbac205b..5645cb009b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt @@ -2,5 +2,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti class MessageIOException : Exception { constructor(msg: String) : super(msg) - constructor(cause: Throwable) : super(cause) + constructor(cause: Throwable) : super("Caught Exception during Message I/O", cause) } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/CrcMismatchException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/CrcMismatchException.kt index e844cc48ab..343e82cd52 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/CrcMismatchException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/CrcMismatchException.kt @@ -2,5 +2,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message import info.nightscout.androidaps.utils.extensions.toHex -class CrcMismatchException(val expected: Long, val got: Long, val payload: ByteArray) : - Exception("CRC missmatch. Got: ${got}. Expected: ${expected}. Payload: ${payload.toHex()}") \ No newline at end of file +class CrcMismatchException(val expected: Long, val actual: Long, val payload: ByteArray) : + Exception("CRC mismatch. Actual: ${actual}. Expected: ${expected}. Payload: ${payload.toHex()}") \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt index c2bdb921ef..f542e1169d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt @@ -1,7 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair +import info.nightscout.androidaps.utils.extensions.toHex + data class PairResult(val ltk: ByteArray) { init { - require(ltk.size == 16) + require(ltk.size == 16) {"LTK length must be 16 bytes. Received LTK: ${ltk.toHex()}"} } } From 8e7b1d3612168f04eafc854b7e33e7dbec820a42 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Sun, 28 Feb 2021 19:28:52 +0100 Subject: [PATCH 072/649] Review: use fold in AlertUtil.encodeAlerts --- .../pump/omnipod/dash/driver/pod/util/AlertUtil.kt | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt index 04cc4e3ce0..4a63fd91fa 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt @@ -19,11 +19,10 @@ object AlertUtil { } } - fun encodeAlertSet(alertSet: EnumSet): Byte { - var out = 0 - alertSet.forEach { slot -> - out = out or (slot.value.toInt() and 0xff) - } - return out.toByte() - } + fun encodeAlertSet(alertSet: EnumSet): Byte = + alertSet.fold(0, + { out, slot -> + out or (slot.value.toInt() and 0xff) + } + ).toByte() } \ No newline at end of file From a7ca5fd863b0dfbd649af612f36cfde72964ccf1 Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sun, 28 Feb 2021 19:44:10 +0100 Subject: [PATCH 073/649] format code: Ctrl+Alt+L --- .../omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt | 4 ++-- .../plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index a658a6d5f1..be03f69525 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -13,15 +13,15 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair.LTKExchanger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair.LTKExchanger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status.ConnectionStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command +import info.nightscout.androidaps.utils.extensions.toHex import io.reactivex.Observable import org.apache.commons.lang3.NotImplementedException -import info.nightscout.androidaps.utils.extensions.toHex import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingDeque import java.util.concurrent.TimeoutException diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt index f542e1169d..2a659e63fd 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairResult.kt @@ -4,6 +4,6 @@ import info.nightscout.androidaps.utils.extensions.toHex data class PairResult(val ltk: ByteArray) { init { - require(ltk.size == 16) {"LTK length must be 16 bytes. Received LTK: ${ltk.toHex()}"} + require(ltk.size == 16) { "LTK length must be 16 bytes. Received LTK: ${ltk.toHex()}" } } } From c8bded99ab6c7afff9312b209468da19d24ef92b Mon Sep 17 00:00:00 2001 From: Andrei Vereha Date: Sun, 28 Feb 2021 19:45:21 +0100 Subject: [PATCH 074/649] remove tailing comma --- .../pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt index cddb97bfaf..cc76bd232f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt @@ -75,7 +75,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI validateP0(p0) return PairResult( - ltk = ltk, + ltk = ltk ) } @@ -88,7 +88,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI sequenceNumber = seq, source = controllerId, destination = nodeId, - payload = payload, + payload = payload ) } @@ -101,7 +101,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI sequenceNumber = seq, source = controllerId, destination = nodeId, - payload = payload, + payload = payload ) } @@ -125,7 +125,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI sequenceNumber = seq, source = controllerId, destination = nodeId, - payload = payload, + payload = payload ) } @@ -156,7 +156,7 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI sequenceNumber = seq, source = controllerId, destination = nodeId, - payload = payload, + payload = payload ) } From 59bfa7a04da295eb410b7aace334bde2f76b8376 Mon Sep 17 00:00:00 2001 From: Bart Sopers Date: Mon, 1 Mar 2021 01:23:40 +0100 Subject: [PATCH 075/649] Implement Pod activation command flow --- .../omnipod/dash/driver/OmnipodDashManager.kt | 5 +- .../dash/driver/OmnipodDashManagerImpl.kt | 287 ++++++++++++++++-- .../pod/definition/ActivationProgress.kt | 3 +- .../pod/state/OmnipodDashPodStateManager.kt | 2 +- .../state/OmnipodDashPodStateManagerImpl.kt | 14 +- .../action/DashInitializePodViewModel.kt | 4 +- .../action/DashInsertCannulaViewModel.kt | 24 +- 7 files changed, 313 insertions(+), 26 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index c567702331..4d7523eff6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTrigger import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram import io.reactivex.Observable @@ -9,9 +10,9 @@ import java.util.* interface OmnipodDashManager { - fun activatePodPart1(): Observable + fun activatePodPart1(lowReservoirAlertTrigger: AlertTrigger.ReservoirVolumeTrigger?): Observable - fun activatePodPart2(): Observable + fun activatePodPart2(basalProgram: BasalProgram): Observable fun getStatus(): Observable diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 8426a62e07..884e755db7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -4,21 +4,15 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.OmnipodDashBleManager import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event.PodEvent -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.GetVersionCommand.Companion.DEFAULT_UNIQUE_ID -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.ActivationProgress -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BasalProgram -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.SetUniqueIdResponse -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.VersionResponse +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.* +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.retryWithBackoff import io.reactivex.Observable +import io.reactivex.functions.Action import io.reactivex.functions.Consumer import java.util.* import java.util.concurrent.TimeUnit @@ -42,9 +36,109 @@ class OmnipodDashManagerImpl @Inject constructor( } } + private val observePodReadyForActivationPart2: Observable + get() = Observable.defer { + if (podStateManager.activationProgress.isAtLeast(ActivationProgress.PHASE_1_COMPLETED) && podStateManager.activationProgress.isBefore(ActivationProgress.COMPLETED)) { + Observable.empty() + } else { + Observable.error(IllegalStateException("Pod is in an incorrect state")) + } + } + private val observeConnectToPod: Observable get() = Observable.defer { bleManager.connect().retryWithBackoff(retries = 2, delay = 3, timeUnit = TimeUnit.SECONDS) } // TODO are these reasonable values? + private fun observeSendProgramBolusCommand(units: Double, rateInEighthPulsesPerSeconds: Byte, confirmationBeeps: Boolean, completionBeeps: Boolean): Observable { + return Observable.defer { + bleManager.sendCommand(ProgramBolusCommand.Builder() + .setUniqueId(podStateManager.uniqueId!!.toInt()) + .setSequenceNumber(podStateManager.messageSequenceNumber) + .setNonce(1229869870) // TODO + .setNumberOfUnits(units) + .setDelayBetweenPulsesInEighthSeconds(rateInEighthPulsesPerSeconds) + .setProgramReminder(ProgramReminder(confirmationBeeps, completionBeeps, 0)) + .build() + ) + } + } + + private fun observeSendGetPodStatusCommand(type: ResponseType.StatusResponseType = ResponseType.StatusResponseType.DEFAULT_STATUS_RESPONSE): Observable { + return Observable.defer { + bleManager.sendCommand( + GetStatusCommand.Builder() + .setUniqueId(podStateManager.uniqueId!!.toInt()) + .setSequenceNumber(podStateManager.messageSequenceNumber) + .setStatusResponseType(type) + .build() + ) + } + } + + private val observeVerifyCannulaInsertion: Observable + get() = Observable.defer { + observeSendGetPodStatusCommand() + .ignoreElements() // + .andThen(Observable.defer { + if (podStateManager.podStatus == PodStatus.RUNNING_ABOVE_MIN_VOLUME) { + Observable.empty() + } else { + Observable.error(IllegalStateException("Unexpected Pod status")) + } + }) + } + + private fun observeSendProgramAlertsCommand(alertConfigurations: List, multiCommandFlag: Boolean = false): Observable { + return Observable.defer { + bleManager.sendCommand( + ProgramAlertsCommand.Builder() + .setUniqueId(podStateManager.uniqueId!!.toInt()) + .setSequenceNumber(podStateManager.messageSequenceNumber) + .setNonce(1229869870) // TODO + .setAlertConfigurations(alertConfigurations) + .build() + ) + } + } + + private fun observeProgramBasalCommand(basalProgram: BasalProgram): Observable { + return Observable.defer { + bleManager.sendCommand( + ProgramBasalCommand.Builder() + .setUniqueId(podStateManager.uniqueId!!.toInt()) + .setSequenceNumber(podStateManager.messageSequenceNumber) + .setNonce(1229869870) // TODO + .setProgramReminder(ProgramReminder(atStart = false, atEnd = false, atInterval = 0)) + .setBasalProgram(basalProgram) + .setCurrentTime(Date()) + .build() + ) + } + } + + private val observeVerifyPrime: Observable + get() = Observable.defer { + observeSendGetPodStatusCommand() + .ignoreElements() // + .andThen(Observable.defer { + if (podStateManager.podStatus == PodStatus.CLUTCH_DRIVE_ENGAGED) { + Observable.empty() + } else { + Observable.error(IllegalStateException("Unexpected Pod status")) + } + }) + } + + private val observeSendSetUniqueIdCommand: Observable + get() = Observable.defer { + bleManager.sendCommand(SetUniqueIdCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(podStateManager.uniqueId!!.toInt()) // + .setLotNumber(podStateManager.lotNumber!!.toInt()) // + .setPodSequenceNumber(podStateManager.podSequenceNumber!!.toInt()) + .setInitializationTime(Date()) + .build()) // + } + private val observeSendGetVersionCommand: Observable get() = Observable.defer { bleManager.sendCommand(GetVersionCommand.Builder() // @@ -53,22 +147,169 @@ class OmnipodDashManagerImpl @Inject constructor( .build()) // } - override fun activatePodPart1(): Observable { + override fun activatePodPart1(lowReservoirAlertTrigger: AlertTrigger.ReservoirVolumeTrigger?): Observable { return Observable.concat( observePodReadyForActivationPart1, observeConnectToPod, - observeSendGetVersionCommand - // ... Send more commands - ) // + observeActivationPart1Commands(lowReservoirAlertTrigger) + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.PHASE_1_COMPLETED)) // TODO these would be common for any observable returned in a public function in this class .doOnNext(PodEventInterceptor()) // .doOnError(ErrorInterceptor()) .subscribeOn(aapsSchedulers.io) } - override fun activatePodPart2(): Observable { - // TODO - return Observable.empty() + private fun observeActivationPart1Commands(lowReservoirAlertTrigger: AlertTrigger.ReservoirVolumeTrigger?): Observable { + val observables = createActivationPart1Observables(lowReservoirAlertTrigger) + + return if (observables.isEmpty()) { + Observable.empty() + } else { + Observable.concat(observables) + } + } + + private fun createActivationPart1Observables(lowReservoirAlertTrigger: AlertTrigger.ReservoirVolumeTrigger?): List> { + val observables = ArrayList>() + + if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIME_COMPLETED)) { + observables.add( + observeVerifyPrime.doOnComplete(ActivationProgressUpdater(ActivationProgress.PRIME_COMPLETED)) + ) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.PRIMING)) { + observables.add( + observeSendProgramBolusCommand( + podStateManager.firstPrimeBolusVolume!! * 0.05, + podStateManager.primePulseRate!!.toByte(), + confirmationBeeps = false, + completionBeeps = false + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.PRIMING)) + ) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.REPROGRAMMED_LUMP_OF_COAL_ALERT)) { + observables.add( + observeSendProgramAlertsCommand( + listOf( + AlertConfiguration( + AlertType.EXPIRATION, + enabled = true, + durationInMinutes = 55, + autoOff = false, + AlertTrigger.TimerTrigger(5), + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX5 + ) + ) + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.REPROGRAMMED_LUMP_OF_COAL_ALERT)) + ) + } + if (lowReservoirAlertTrigger != null && podStateManager.activationProgress.isBefore(ActivationProgress.PROGRAMMED_LOW_RESERVOIR_ALERTS)) { + observables.add( + observeSendProgramAlertsCommand( + listOf( + AlertConfiguration( + AlertType.LOW_RESERVOIR, + enabled = true, + durationInMinutes = 0, + autoOff = false, + lowReservoirAlertTrigger, + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX + ) + ) + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.PROGRAMMED_LOW_RESERVOIR_ALERTS)) + ) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.SET_UNIQUE_ID)) { + observables.add( + observeSendSetUniqueIdCommand.doOnComplete(ActivationProgressUpdater(ActivationProgress.SET_UNIQUE_ID)) + ) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.GOT_POD_VERSION)) { + observables.add( + observeSendGetVersionCommand.doOnComplete(ActivationProgressUpdater(ActivationProgress.GOT_POD_VERSION)) + ) + } + + return observables.reversed() + } + + override fun activatePodPart2(basalProgram: BasalProgram): Observable { + return Observable.concat( + observePodReadyForActivationPart2, + observeConnectToPod, + observeActivationPart2Commands(basalProgram) + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.COMPLETED)) + // TODO these would be common for any observable returned in a public function in this class + .doOnNext(PodEventInterceptor()) // + .doOnError(ErrorInterceptor()) + .subscribeOn(aapsSchedulers.io) + } + + private fun observeActivationPart2Commands(basalProgram: BasalProgram): Observable { + val observables = createActivationPart2Observables(basalProgram) + + return if (observables.isEmpty()) { + Observable.empty() + } else { + Observable.concat(observables) + } + } + + private fun createActivationPart2Observables(basalProgram: BasalProgram): List> { + val observables = ArrayList>() + + if (podStateManager.activationProgress.isBefore(ActivationProgress.CANNULA_INSERTED)) { + observables.add( + observeVerifyCannulaInsertion + .doOnComplete(ActivationProgressUpdater(ActivationProgress.CANNULA_INSERTED)) + ) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.INSERTING_CANNULA)) { + observables.add( + observeSendProgramBolusCommand( + podStateManager.secondPrimeBolusVolume!! * 0.05, + podStateManager.primePulseRate!!.toByte(), + confirmationBeeps = false, + completionBeeps = false + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.INSERTING_CANNULA)) + ) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.UPDATED_EXPIRATION_ALERTS)) { + observables.add(observeSendProgramAlertsCommand( + listOf( + // FIXME use user configured expiration alert + AlertConfiguration( + AlertType.EXPIRATION, + enabled = true, + durationInMinutes = TimeUnit.HOURS.toMinutes(7).toShort(), + autoOff = false, + AlertTrigger.TimerTrigger(TimeUnit.HOURS.toMinutes(73).toShort()), // FIXME use activation time + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX3 + ), + AlertConfiguration( + AlertType.EXPIRATION_IMMINENT, + enabled = true, + durationInMinutes = TimeUnit.HOURS.toMinutes(1).toShort(), + autoOff = false, + AlertTrigger.TimerTrigger(TimeUnit.HOURS.toMinutes(79).toShort()), // FIXME use activation time + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX4 + ) + ), + multiCommandFlag = true + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.UPDATED_EXPIRATION_ALERTS))) + } + if (podStateManager.activationProgress.isBefore(ActivationProgress.PROGRAMMED_BASAL)) { + observables.add( + observeProgramBasalCommand(basalProgram) + .doOnComplete(ActivationProgressUpdater(ActivationProgress.PROGRAMMED_BASAL)) + ) + } + + return observables.reversed() } override fun getStatus(): Observable { @@ -149,6 +390,10 @@ class OmnipodDashManagerImpl @Inject constructor( podStateManager.uniqueId = event.uniqueId } + is PodEvent.CommandSent -> { + podStateManager.increaseMessageSequenceNumber() + } + is PodEvent.ResponseReceived -> { podStateManager.increaseMessageSequenceNumber() handleResponse(event.response) @@ -189,4 +434,12 @@ class OmnipodDashManagerImpl @Inject constructor( } } + + inner class ActivationProgressUpdater(private val value: ActivationProgress) : Action { + + override fun run() { + podStateManager.activationProgress = value + } + + } } \ No newline at end of file diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt index e43a277f2e..f9455e5528 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt @@ -8,10 +8,9 @@ enum class ActivationProgress { REPROGRAMMED_LUMP_OF_COAL_ALERT, PRIMING, PRIME_COMPLETED, - PROGRAMMED_USER_SET_EXPIRATION_ALERT, PHASE_1_COMPLETED, PROGRAMMED_BASAL, - PROGRAMMED_CANCEL_LOC_ETC_ALERT, + UPDATED_EXPIRATION_ALERTS, INSERTING_CANNULA, CANNULA_INSERTED, COMPLETED; diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index b0a069b5bc..a97cad8974 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -21,7 +21,7 @@ interface OmnipodDashPodStateManager { val messageSequenceNumber: Short val sequenceNumberOfLastProgrammingCommand: Short? val activationTime: Long? - var uniqueId: Long? + var uniqueId: Long? // TODO make Int var bluetoothAddress: String? val bluetoothVersion: SoftwareVersion? diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index add92d9567..78254c74e8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -3,6 +3,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state import com.google.gson.Gson import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.pump.omnipod.dash.EventOmnipodDashPumpValuesChanged import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.* import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse @@ -18,7 +20,8 @@ import javax.inject.Singleton @Singleton class OmnipodDashPodStateManagerImpl @Inject constructor( private val logger: AAPSLogger, - private val sharedPreferences: SP + private val sharedPreferences: SP, + private val rxBus: RxBusWrapper ) : OmnipodDashPodStateManager { private var podState: PodState @@ -158,6 +161,7 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( podState.lastUpdated = System.currentTimeMillis() store() + rxBus.send(EventOmnipodDashPumpValuesChanged()) } override fun updateFromVersionResponse(response: VersionResponse) { @@ -169,6 +173,7 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( podState.lastUpdated = System.currentTimeMillis() store() + rxBus.send(EventOmnipodDashPumpValuesChanged()) } override fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse) { @@ -186,10 +191,15 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( podState.lastUpdated = System.currentTimeMillis() store() + rxBus.send(EventOmnipodDashPumpValuesChanged()) } override fun updateFromAlarmStatusResponse(response: AlarmStatusResponse) { - TODO("Not yet implemented") + // TODO + logger.error(LTag.PUMP, "Not implemented: OmnipodDashPodStateManagerImpl.updateFromAlarmStatusResponse(AlarmStatusResponse)") + + store() + rxBus.send(EventOmnipodDashPumpValuesChanged()) } override fun reset() { diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index dd2daa8e3b..ac3ea5f9d2 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -8,6 +8,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InitializePodViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTrigger import io.reactivex.Single import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject @@ -26,7 +27,8 @@ class DashInitializePodViewModel @Inject constructor( override fun doExecuteAction(): Single = Single.create { source -> - val disposable = omnipodManager.activatePodPart1().subscribeBy( + // TODO use configured value for low reservoir trigger + val disposable = omnipodManager.activatePodPart1(AlertTrigger.ReservoirVolumeTrigger(200)).subscribeBy( onNext = { podEvent -> logger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 1: $podEvent") }, onError = { throwable -> logger.error(LTag.PUMP, "Error in Pod activation part 1", throwable) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt index 0b5ef6bc66..fc6c428ca2 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -5,12 +5,17 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.viewmodel.action.InsertCannulaViewModel import info.nightscout.androidaps.plugins.pump.omnipod.dash.R +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.OmnipodDashManager +import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.mapProfileToBasalProgram import io.reactivex.Single +import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject class DashInsertCannulaViewModel @Inject constructor( + private val omnipodManager: OmnipodDashManager, private val profileFunction: ProfileFunction, injector: HasAndroidInjector, logger: AAPSLogger @@ -22,7 +27,24 @@ class DashInsertCannulaViewModel @Inject constructor( override fun isPodDeactivatable(): Boolean = true // TODO - override fun doExecuteAction(): Single = Single.just(PumpEnactResult(injector).success(false).comment("TODO")) // TODO + override fun doExecuteAction(): Single = Single.create { source -> + val profile = profileFunction.getProfile() + if (profile == null) { + source.onError(IllegalStateException("No profile set")) + } else { + val disposable = omnipodManager.activatePodPart2(mapProfileToBasalProgram(profile)).subscribeBy( + onNext = { podEvent -> logger.debug(LTag.PUMP, "Received PodEvent in Pod activation part 2: $podEvent") }, + onError = { throwable -> + logger.error(LTag.PUMP, "Error in Pod activation part 2", throwable) + source.onSuccess(PumpEnactResult(injector).success(false).comment(throwable.message)) + }, + onComplete = { + logger.debug("Pod activation part 2 completed") + source.onSuccess(PumpEnactResult(injector).success(true)) + } + ) + } + } @StringRes override fun getTitleId(): Int = R.string.omnipod_common_pod_activation_wizard_insert_cannula_title From 070ba1cfc2722323df85d984d68a78de2b0acb30 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 1 Mar 2021 12:34:47 +0100 Subject: [PATCH 076/649] add ktlint and detekt --- build.gradle | 5 + gradle/wrapper/gradle-wrapper.properties | 2 +- omnipod-dash/build.gradle | 7 + omnipod-dash/detekt-config.yml | 689 +++++++++++++++++++++++ 4 files changed, 702 insertions(+), 1 deletion(-) create mode 100644 omnipod-dash/detekt-config.yml diff --git a/build.gradle b/build.gradle index fd870b3ad6..c335d90c7a 100644 --- a/build.gradle +++ b/build.gradle @@ -58,6 +58,11 @@ buildscript { } } +plugins { + id "io.gitlab.arturbosch.detekt" version "1.15.0-RC2" + id "org.jlleitschuh.gradle.ktlint" version "9.4.1" +} + allprojects { repositories { google() diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9a5b8e899d..a4d9e76064 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip diff --git a/omnipod-dash/build.gradle b/omnipod-dash/build.gradle index bf7d1c99c1..9d48cfa1c1 100644 --- a/omnipod-dash/build.gradle +++ b/omnipod-dash/build.gradle @@ -2,6 +2,8 @@ apply plugin: 'com.android.library' apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' apply plugin: 'com.hiya.jacoco-android' +apply plugin: "io.gitlab.arturbosch.detekt" // TODO move to `subprojects` section in global build.gradle +apply plugin: "org.jlleitschuh.gradle.ktlint" // TODO move to `subprojects` section in global build.gradle apply from: "${project.rootDir}/gradle/android_dependencies.gradle" apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle" @@ -14,6 +16,11 @@ android { } } +detekt { // TODO move to `subprojects` section in global build.gradle + toolVersion = "1.15.0-RC2" + config = files("./detekt-config.yml") // TODO move to global space and use "../detekt-config.yml" +} + dependencies { implementation project(':core') implementation project(':omnipod-common') diff --git a/omnipod-dash/detekt-config.yml b/omnipod-dash/detekt-config.yml new file mode 100644 index 0000000000..60e3fee286 --- /dev/null +++ b/omnipod-dash/detekt-config.yml @@ -0,0 +1,689 @@ +build: + maxIssues: 0 + excludeCorrectable: false + weights: + # complexity: 2 + # LongParameterList: 1 + # style: 1 + # comments: 1 + +config: + validation: true + warningsAsErrors: false + # when writing own rules with new properties, exclude the property path e.g.: 'my_rule_set,.*>.*>[my_property]' + excludes: '' + +processors: + active: true + exclude: + - 'DetektProgressListener' + # - 'FunctionCountProcessor' + # - 'PropertyCountProcessor' + # - 'ClassCountProcessor' + # - 'PackageCountProcessor' + # - 'KtFileCountProcessor' + +console-reports: + active: true + exclude: + - 'ProjectStatisticsReport' + - 'ComplexityReport' + - 'NotificationReport' + # - 'FindingsReport' + - 'FileBasedFindingsReport' + +output-reports: + active: true + exclude: + # - 'TxtOutputReport' + # - 'XmlOutputReport' + # - 'HtmlOutputReport' + +comments: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + AbsentOrWrongFileLicense: + active: false + licenseTemplateFile: 'license.template' + CommentOverPrivateFunction: + active: false + CommentOverPrivateProperty: + active: false + EndOfSentenceFormat: + active: false + endOfSentenceFormat: '([.?!][ \t\n\r\f<])|([.?!:]$)' + UndocumentedPublicClass: + active: false + searchInNestedClass: true + searchInInnerClass: true + searchInInnerObject: true + searchInInnerInterface: true + UndocumentedPublicFunction: + active: false + UndocumentedPublicProperty: + active: false + +complexity: + active: true + ComplexCondition: + active: true + threshold: 4 + ComplexInterface: + active: false + threshold: 10 + includeStaticDeclarations: false + includePrivateDeclarations: false + ComplexMethod: + active: true + threshold: 15 + ignoreSingleWhenExpression: false + ignoreSimpleWhenEntries: false + ignoreNestingFunctions: false + nestingFunctions: [run, let, apply, with, also, use, forEach, isNotNull, ifNull] + LabeledExpression: + active: false + ignoredLabels: [] + LargeClass: + active: true + threshold: 600 + LongMethod: + active: true + threshold: 60 + LongParameterList: + active: true + functionThreshold: 6 + constructorThreshold: 7 + ignoreDefaultParameters: false + ignoreDataClasses: true + ignoreAnnotated: [] + MethodOverloading: + active: false + threshold: 6 + NamedArguments: + active: false + threshold: 3 + NestedBlockDepth: + active: true + threshold: 4 + ReplaceSafeCallChainWithRun: + active: false + StringLiteralDuplication: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + threshold: 3 + ignoreAnnotation: true + excludeStringsWithLessThan5Characters: true + ignoreStringsRegex: '$^' + TooManyFunctions: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + thresholdInFiles: 11 + thresholdInClasses: 11 + thresholdInInterfaces: 11 + thresholdInObjects: 11 + thresholdInEnums: 11 + ignoreDeprecated: false + ignorePrivate: false + ignoreOverridden: false + +coroutines: + active: true + GlobalCoroutineUsage: + active: false + RedundantSuspendModifier: + active: false + SuspendFunWithFlowReturnType: + active: false + +empty-blocks: + active: true + EmptyCatchBlock: + active: true + allowedExceptionNameRegex: '_|(ignore|expected).*' + EmptyClassBlock: + active: true + EmptyDefaultConstructor: + active: true + EmptyDoWhileBlock: + active: true + EmptyElseBlock: + active: true + EmptyFinallyBlock: + active: true + EmptyForBlock: + active: true + EmptyFunctionBlock: + active: true + ignoreOverridden: false + EmptyIfBlock: + active: true + EmptyInitBlock: + active: true + EmptyKtFile: + active: true + EmptySecondaryConstructor: + active: true + EmptyTryBlock: + active: true + EmptyWhenBlock: + active: true + EmptyWhileBlock: + active: true + +exceptions: + active: true + ExceptionRaisedInUnexpectedLocation: + active: false + methodNames: [toString, hashCode, equals, finalize] + InstanceOfCheckForException: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + NotImplementedDeclaration: + active: false + PrintStackTrace: + active: false + RethrowCaughtException: + active: false + ReturnFromFinally: + active: false + ignoreLabeled: false + SwallowedException: + active: false + ignoredExceptionTypes: + - InterruptedException + - NumberFormatException + - ParseException + - MalformedURLException + allowedExceptionNameRegex: '_|(ignore|expected).*' + ThrowingExceptionFromFinally: + active: false + ThrowingExceptionInMain: + active: false + ThrowingExceptionsWithoutMessageOrCause: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + exceptions: + - IllegalArgumentException + - IllegalStateException + - IOException + ThrowingNewInstanceOfSameException: + active: false + TooGenericExceptionCaught: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + exceptionNames: + - ArrayIndexOutOfBoundsException + - Error + - Exception + - IllegalMonitorStateException + - NullPointerException + - IndexOutOfBoundsException + - RuntimeException + - Throwable + allowedExceptionNameRegex: '_|(ignore|expected).*' + TooGenericExceptionThrown: + active: true + exceptionNames: + - Error + - Exception + - Throwable + - RuntimeException + +formatting: + active: true + android: false + autoCorrect: true + AnnotationOnSeparateLine: + active: false + autoCorrect: true + AnnotationSpacing: + active: false + autoCorrect: true + ArgumentListWrapping: + active: false + autoCorrect: true + ChainWrapping: + active: true + autoCorrect: true + CommentSpacing: + active: true + autoCorrect: true + EnumEntryNameCase: + active: false + autoCorrect: true + Filename: + active: true + FinalNewline: + active: true + autoCorrect: true + insertFinalNewLine: true + ImportOrdering: + active: false + autoCorrect: true + layout: 'idea' + Indentation: + active: false + autoCorrect: true + indentSize: 4 + continuationIndentSize: 4 + MaximumLineLength: + active: true + maxLineLength: 120 + ModifierOrdering: + active: true + autoCorrect: true + MultiLineIfElse: + active: true + autoCorrect: true + NoBlankLineBeforeRbrace: + active: true + autoCorrect: true + NoConsecutiveBlankLines: + active: true + autoCorrect: true + NoEmptyClassBody: + active: true + autoCorrect: true + NoEmptyFirstLineInMethodBlock: + active: false + autoCorrect: true + NoLineBreakAfterElse: + active: true + autoCorrect: true + NoLineBreakBeforeAssignment: + active: true + autoCorrect: true + NoMultipleSpaces: + active: true + autoCorrect: true + NoSemicolons: + active: true + autoCorrect: true + NoTrailingSpaces: + active: true + autoCorrect: true + NoUnitReturn: + active: true + autoCorrect: true + NoUnusedImports: + active: true + autoCorrect: true + NoWildcardImports: + active: true + PackageName: + active: true + autoCorrect: true + ParameterListWrapping: + active: true + autoCorrect: true + indentSize: 4 + SpacingAroundColon: + active: true + autoCorrect: true + SpacingAroundComma: + active: true + autoCorrect: true + SpacingAroundCurly: + active: true + autoCorrect: true + SpacingAroundDot: + active: true + autoCorrect: true + SpacingAroundDoubleColon: + active: false + autoCorrect: true + SpacingAroundKeyword: + active: true + autoCorrect: true + SpacingAroundOperators: + active: true + autoCorrect: true + SpacingAroundParens: + active: true + autoCorrect: true + SpacingAroundRangeOperator: + active: true + autoCorrect: true + SpacingBetweenDeclarationsWithAnnotations: + active: false + autoCorrect: true + SpacingBetweenDeclarationsWithComments: + active: false + autoCorrect: true + StringTemplate: + active: true + autoCorrect: true + +naming: + active: true + ClassNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + classPattern: '[A-Z][a-zA-Z0-9]*' + ConstructorParameterNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + parameterPattern: '[a-z][A-Za-z0-9]*' + privateParameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + EnumNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + enumEntryPattern: '[A-Z][_a-zA-Z0-9]*' + ForbiddenClassName: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + forbiddenName: [] + FunctionMaxLength: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + maximumFunctionNameLength: 30 + FunctionMinLength: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + minimumFunctionNameLength: 3 + FunctionNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + functionPattern: '([a-z][a-zA-Z0-9]*)|(`.*`)' + excludeClassPattern: '$^' + ignoreOverridden: true + ignoreAnnotated: ['Composable'] + FunctionParameterNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + parameterPattern: '[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + InvalidPackageDeclaration: + active: false + rootPackage: '' + MatchingDeclarationName: + active: true + mustBeFirst: true + MemberNameEqualsClassName: + active: true + ignoreOverridden: true + NonBooleanPropertyPrefixedWithIs: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + ObjectPropertyNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + constantPattern: '[A-Za-z][_A-Za-z0-9]*' + propertyPattern: '[A-Za-z][_A-Za-z0-9]*' + privatePropertyPattern: '(_)?[A-Za-z][_A-Za-z0-9]*' + PackageNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + packagePattern: '[a-z]+(\.[a-z][A-Za-z0-9]*)*' + TopLevelPropertyNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + constantPattern: '[A-Z][_A-Z0-9]*' + propertyPattern: '[A-Za-z][_A-Za-z0-9]*' + privatePropertyPattern: '_?[A-Za-z][_A-Za-z0-9]*' + VariableMaxLength: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + maximumVariableNameLength: 64 + VariableMinLength: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + minimumVariableNameLength: 1 + VariableNaming: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + variablePattern: '[a-z][A-Za-z0-9]*' + privateVariablePattern: '(_)?[a-z][A-Za-z0-9]*' + excludeClassPattern: '$^' + ignoreOverridden: true + +performance: + active: true + ArrayPrimitive: + active: true + ForEachOnRange: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + SpreadOperator: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + UnnecessaryTemporaryInstantiation: + active: true + +potential-bugs: + active: true + Deprecation: + active: false + DuplicateCaseInWhenExpression: + active: true + EqualsAlwaysReturnsTrueOrFalse: + active: true + EqualsWithHashCodeExist: + active: true + ExplicitGarbageCollectionCall: + active: true + HasPlatformType: + active: false + IgnoredReturnValue: + active: false + restrictToAnnotatedMethods: true + returnValueAnnotations: ['*.CheckReturnValue', '*.CheckResult'] + ImplicitDefaultLocale: + active: false + ImplicitUnitReturnType: + active: false + allowExplicitReturnType: true + InvalidRange: + active: true + IteratorHasNextCallsNextMethod: + active: true + IteratorNotThrowingNoSuchElementException: + active: true + LateinitUsage: + active: false + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + excludeAnnotatedProperties: [] + ignoreOnClassesPattern: '' + MapGetWithNotNullAssertionOperator: + active: false + MissingWhenCase: + active: true + allowElseExpression: true + NullableToStringCall: + active: false + RedundantElseInWhen: + active: true + UnconditionalJumpStatementInLoop: + active: false + UnnecessaryNotNullOperator: + active: false + UnnecessarySafeCall: + active: false + UnreachableCode: + active: true + UnsafeCallOnNullableType: + active: true + UnsafeCast: + active: false + UselessPostfixExpression: + active: false + WrongEqualsTypeParameter: + active: true + +style: + active: true + ClassOrdering: + active: false + CollapsibleIfStatements: + active: false + DataClassContainsFunctions: + active: false + conversionFunctionPrefix: 'to' + DataClassShouldBeImmutable: + active: false + EqualsNullCall: + active: true + EqualsOnSignatureLine: + active: false + ExplicitCollectionElementAccessMethod: + active: false + ExplicitItLambdaParameter: + active: false + ExpressionBodySyntax: + active: false + includeLineWrapping: false + ForbiddenComment: + active: true + values: ['TODO:', 'FIXME:', 'STOPSHIP:'] + allowedPatterns: '' + ForbiddenImport: + active: false + imports: [] + forbiddenPatterns: '' + ForbiddenMethodCall: + active: false + methods: ['kotlin.io.println', 'kotlin.io.print'] + ForbiddenPublicDataClass: + active: false + ignorePackages: ['*.internal', '*.internal.*'] + ForbiddenVoid: + active: false + ignoreOverridden: false + ignoreUsageInGenerics: false + FunctionOnlyReturningConstant: + active: true + ignoreOverridableFunction: true + excludedFunctions: 'describeContents' + excludeAnnotatedFunction: ['dagger.Provides'] + LibraryCodeMustSpecifyReturnType: + active: true + LibraryEntitiesShouldNotBePublic: + active: false + LoopWithTooManyJumpStatements: + active: true + maxJumpCount: 1 + MagicNumber: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + ignoreNumbers: ['-1', '0', '1', '2'] + ignoreHashCodeFunction: true + ignorePropertyDeclaration: false + ignoreLocalVariableDeclaration: false + ignoreConstantDeclaration: true + ignoreCompanionObjectPropertyDeclaration: true + ignoreAnnotation: false + ignoreNamedArgument: true + ignoreEnums: false + ignoreRanges: false + MandatoryBracesIfStatements: + active: false + MandatoryBracesLoops: + active: false + MaxLineLength: + active: true + maxLineLength: 120 + excludePackageStatements: true + excludeImportStatements: true + excludeCommentStatements: false + MayBeConst: + active: true + ModifierOrder: + active: true + NestedClassesVisibility: + active: false + NewLineAtEndOfFile: + active: false + NoTabs: + active: false + OptionalAbstractKeyword: + active: true + OptionalUnit: + active: false + OptionalWhenBraces: + active: false + PreferToOverPairSyntax: + active: false + ProtectedMemberInFinalClass: + active: true + RedundantExplicitType: + active: false + RedundantHigherOrderMapUsage: + active: false + RedundantVisibilityModifierRule: + active: false + ReturnCount: + active: true + max: 2 + excludedFunctions: 'equals' + excludeLabeled: false + excludeReturnFromLambda: true + excludeGuardClauses: false + SafeCast: + active: true + SerialVersionUIDInSerializableClass: + active: false + SpacingBetweenPackageAndImports: + active: false + ThrowsCount: + active: true + max: 2 + TrailingWhitespace: + active: false + UnderscoresInNumericLiterals: + active: false + acceptableDecimalLength: 5 + UnnecessaryAbstractClass: + active: true + excludeAnnotatedClasses: ['dagger.Module'] + UnnecessaryAnnotationUseSiteTarget: + active: false + UnnecessaryApply: + active: false + UnnecessaryInheritance: + active: true + UnnecessaryLet: + active: false + UnnecessaryParentheses: + active: false + UntilInsteadOfRangeTo: + active: false + UnusedImports: + active: false + UnusedPrivateClass: + active: true + UnusedPrivateMember: + active: false + allowedNames: '(_|ignored|expected|serialVersionUID)' + UseArrayLiteralsInAnnotations: + active: false + UseCheckNotNull: + active: false + UseCheckOrError: + active: false + UseDataClass: + active: false + excludeAnnotatedClasses: [] + allowVars: false + UseEmptyCounterpart: + active: false + UseIfEmptyOrIfBlank: + active: false + UseIfInsteadOfWhen: + active: false + UseRequire: + active: false + UseRequireNotNull: + active: false + UselessCallOnNotNull: + active: true + UtilityClassWithPublicConstructor: + active: true + VarCouldBeVal: + active: false + WildcardImport: + active: true + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + excludeImports: ['java.util.*', 'kotlinx.android.synthetic.*'] \ No newline at end of file From 3ebcc1c71e0243b1347b659d4b22cdb0b1cd868c Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 1 Mar 2021 13:34:34 +0100 Subject: [PATCH 077/649] make detekt work --- .editorconfig | 5 +++++ build.gradle | 7 +++++-- gradle/wrapper/gradle-wrapper.properties | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..4ce4a9be35 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,5 @@ +root = true + + +[*{kt,kts}] +disabled_rules=no-wildcard-imports \ No newline at end of file diff --git a/build.gradle b/build.gradle index c335d90c7a..3b9caa5038 100644 --- a/build.gradle +++ b/build.gradle @@ -44,9 +44,10 @@ buildscript { } } maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2 + maven { url "https://dl.bintray.com/kotlin/kotlinx" } } dependencies { - classpath 'com.android.tools.build:gradle:4.0.1' + classpath 'com.android.tools.build:gradle:4.1.2' classpath 'com.google.gms:google-services:4.3.4' classpath 'com.google.firebase:firebase-crashlytics-gradle:2.4.1' @@ -59,7 +60,7 @@ buildscript { } plugins { - id "io.gitlab.arturbosch.detekt" version "1.15.0-RC2" + id "io.gitlab.arturbosch.detekt" version "1.16.0-RC2" id "org.jlleitschuh.gradle.ktlint" version "9.4.1" } @@ -83,6 +84,8 @@ allprojects { includeModule("org.jetbrains.trove4j", "trove4j") } } + maven { url "https://dl.bintray.com/kotlin/kotlinx" } + } //Support @JvmDefault tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a4d9e76064..e53b7051f9 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip From 77c816e8135cd3a21fe16731cec23f5962eb4783 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 1 Mar 2021 13:39:02 +0100 Subject: [PATCH 078/649] ktlint format --- .../omnipod/dash/history/DashHistoryTest.kt | 6 +- .../omnipod/dash/history/RxSchedulerRule.kt | 3 +- .../dash/EventOmnipodDashPumpValuesChanged.kt | 2 +- .../omnipod/dash/OmnipodDashPumpPlugin.kt | 2 +- .../dash/dagger/OmnipodDashHistoryModule.kt | 3 +- .../omnipod/dash/dagger/OmnipodDashModule.kt | 2 +- .../OmnipodDashWizardViewModelsModule.kt | 2 +- .../omnipod/dash/driver/OmnipodDashManager.kt | 2 +- .../dash/driver/OmnipodDashManagerImpl.kt | 126 ++++++++++-------- .../pump/omnipod/dash/driver/comm/Id.kt | 3 +- .../dash/driver/comm/OmnipodDashBleManager.kt | 2 +- .../driver/comm/OmnipodDashBleManagerImpl.kt | 9 +- .../dash/driver/comm/ServiceDiscoverer.kt | 7 +- .../driver/comm/callbacks/BleCommCallbacks.kt | 31 +++-- .../CharacteristicWriteConfirmation.kt | 2 +- .../callbacks/DescriptorWriteConfirmation.kt | 2 +- .../driver/comm/command/BleCommandHello.kt | 5 +- .../driver/comm/command/BleCommandType.kt | 2 +- .../comm/exceptions/BleIOBusyException.kt | 2 +- .../CharacteristicNotFoundException.kt | 2 +- ...CouldNotConfirmDescriptorWriteException.kt | 6 +- .../CouldNotConfirmWriteException.kt | 6 +- .../exceptions/CouldNotEnableNotifications.kt | 2 +- .../CouldNotParseMessageException.kt | 2 +- .../exceptions/CouldNotSendBleException.kt | 2 +- .../exceptions/DescriptorNotFoundException.kt | 2 +- .../DiscoveredInvalidPodException.kt | 2 +- .../exceptions/FailedToConnectException.kt | 2 +- .../comm/exceptions/MessageIOException.kt | 2 +- .../comm/exceptions/ScanFailException.kt | 2 +- .../ScanFailFoundTooManyException.kt | 2 +- .../exceptions/ScanFailNotFoundException.kt | 2 +- .../exceptions/ServiceNotFoundException.kt | 2 +- .../exceptions/UnexpectedCommandException.kt | 2 +- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 2 +- .../dash/driver/comm/io/CharacteristicType.kt | 2 +- .../omnipod/dash/driver/comm/io/IOState.kt | 2 +- .../comm/message/CrcMismatchException.kt | 2 +- .../comm/message/IncorrectPacketException.kt | 2 +- .../dash/driver/comm/message/MessageIO.kt | 2 +- .../dash/driver/comm/message/MessagePacket.kt | 6 +- .../dash/driver/comm/message/MessageType.kt | 2 +- .../dash/driver/comm/message/PayloadJoiner.kt | 13 +- .../driver/comm/message/PayloadSplitter.kt | 72 +++++----- .../message/StringLengthPrefixEncoding.kt | 16 +-- .../dash/driver/comm/packet/BlePacket.kt | 1 - .../dash/driver/comm/pair/LTKExchanger.kt | 2 +- .../dash/driver/comm/pair/PairMessage.kt | 2 +- .../driver/comm/scan/BleDiscoveredDevice.kt | 3 +- .../dash/driver/comm/scan/PodScanner.kt | 2 +- .../dash/driver/comm/scan/ScanCollector.kt | 3 +- .../driver/comm/status/ConnectionStatus.kt | 2 +- .../omnipod/dash/driver/event/PodEvent.kt | 1 - .../driver/pod/command/DeactivateCommand.kt | 16 ++- .../driver/pod/command/GetStatusCommand.kt | 17 +-- .../driver/pod/command/GetVersionCommand.kt | 16 ++- .../pod/command/ProgramAlertsCommand.kt | 2 +- .../driver/pod/command/ProgramBasalCommand.kt | 26 ++-- .../driver/pod/command/ProgramBeepsCommand.kt | 22 +-- .../driver/pod/command/ProgramBolusCommand.kt | 34 +++-- .../pod/command/ProgramInsulinCommand.kt | 7 +- .../pod/command/ProgramTempBasalCommand.kt | 20 +-- .../driver/pod/command/SetUniqueIdCommand.kt | 34 ++--- .../pod/command/SilenceAlertsCommand.kt | 18 +-- .../driver/pod/command/StopDeliveryCommand.kt | 18 +-- .../dash/driver/pod/command/base/Command.kt | 2 +- .../driver/pod/command/base/CommandType.kt | 10 +- .../pod/command/base/NonceEnabledCommand.kt | 2 +- .../command/base/builder/CommandBuilder.kt | 2 +- .../builder/HeaderEnabledCommandBuilder.kt | 2 +- .../builder/NonceEnabledCommandBuilder.kt | 2 +- .../program/BasalInsulinProgramElement.kt | 2 +- .../BasalShortInsulinProgramElement.kt | 12 +- .../BolusShortInsulinProgramElement.kt | 2 +- .../CurrentBasalInsulinProgramElement.kt | 2 +- .../command/insulin/program/CurrentSlot.kt | 2 +- .../program/ShortInsulinProgramElement.kt | 2 +- .../program/TempBasalInsulinProgramElement.kt | 2 +- .../insulin/program/util/ProgramBasalUtil.kt | 2 +- .../program/util/ProgramTempBasalUtil.kt | 2 +- .../pod/definition/ActivationProgress.kt | 2 +- .../dash/driver/pod/definition/AlarmType.kt | 3 +- .../pod/definition/AlertConfiguration.kt | 18 +-- .../driver/pod/definition/AlertTrigger.kt | 2 +- .../dash/driver/pod/definition/AlertType.kt | 2 +- .../driver/pod/definition/BasalProgram.kt | 2 +- .../pod/definition/BeepRepetitionType.kt | 3 +- .../dash/driver/pod/definition/BeepType.kt | 2 +- .../driver/pod/definition/DeliveryStatus.kt | 2 +- .../dash/driver/pod/definition/Encodable.kt | 2 +- .../driver/pod/definition/NakErrorType.kt | 2 +- .../dash/driver/pod/definition/PodStatus.kt | 2 +- .../driver/pod/definition/ProgramReminder.kt | 12 +- .../pod/response/ActivationResponseBase.kt | 2 +- .../response/AdditionalStatusResponseBase.kt | 2 +- .../pod/response/AlarmStatusResponse.kt | 3 +- .../pod/response/DefaultStatusResponse.kt | 1 - .../dash/driver/pod/response/NakResponse.kt | 2 +- .../dash/driver/pod/response/Response.kt | 2 +- .../dash/driver/pod/response/ResponseBase.kt | 3 +- .../dash/driver/pod/response/ResponseType.kt | 2 +- .../pod/response/SetUniqueIdResponse.kt | 3 +- .../driver/pod/response/VersionResponse.kt | 3 +- .../pod/state/OmnipodDashPodStateManager.kt | 2 +- .../state/OmnipodDashPodStateManagerImpl.kt | 2 +- .../omnipod/dash/driver/pod/util/AlertUtil.kt | 5 +- .../omnipod/dash/driver/pod/util/HasValue.kt | 2 +- .../dash/driver/pod/util/MessageUtil.kt | 2 +- .../pump/omnipod/dash/history/DashHistory.kt | 27 ++-- .../pump/omnipod/dash/history/data/Record.kt | 6 +- .../omnipod/dash/history/data/ResultStates.kt | 2 +- .../dash/history/database/Converters.kt | 2 +- .../history/database/DashHistoryDatabase.kt | 6 +- .../dash/history/database/HistoryRecordDao.kt | 3 +- .../history/database/HistoryRecordEntity.kt | 4 +- .../dash/history/mapper/HistoryMapper.kt | 6 +- .../dash/ui/DashPodManagementActivity.kt | 24 ++-- .../dash/ui/OmnipodDashOverviewFragment.kt | 85 +++++++----- .../DashPodActivationWizardActivity.kt | 2 +- .../action/DashInsertCannulaViewModel.kt | 2 +- .../viewmodel/info/DashAttachPodViewModel.kt | 2 +- .../info/DashPodActivatedViewModel.kt | 2 +- .../info/DashStartPodActivationViewModel.kt | 2 +- .../DashPodDeactivationWizardActivity.kt | 2 +- .../action/DashDeactivatePodViewModel.kt | 2 +- .../info/DashPodDeactivatedViewModel.kt | 3 +- .../info/DashPodDiscardedViewModel.kt | 2 +- .../info/DashStartPodDeactivationViewModel.kt | 2 +- .../pump/omnipod/dash/util/Functions.kt | 2 +- .../pod/command/DeactivateCommandTest.kt | 2 +- .../pod/command/GetStatusCommandTest.kt | 2 +- .../pod/command/GetVersionCommandTest.kt | 2 +- .../pod/command/ProgramAlertsCommandTest.kt | 4 +- .../pod/command/ProgramBasalCommandTest.kt | 2 +- .../pod/command/ProgramBeepsCommandTest.kt | 2 +- .../pod/command/ProgramBolusCommandTest.kt | 2 +- .../command/ProgramTempBasalCommandTest.kt | 2 +- .../pod/command/SetUniqueIdCommandTest.kt | 2 +- .../pod/command/SilenceAlertsCommandTest.kt | 2 +- .../pod/command/StopDeliveryCommandTest.kt | 2 +- .../pod/response/AlarmStatusResponseTest.kt | 2 +- .../pod/response/DefaultStatusResponseTest.kt | 2 +- .../driver/pod/response/NakResponseTest.kt | 3 +- .../pod/response/SetUniqueIdResponseTest.kt | 2 +- .../pod/response/VersionResponseTest.kt | 2 +- .../pump/omnipod/dash/util/FunctionsTest.kt | 45 ++++--- 146 files changed, 557 insertions(+), 467 deletions(-) diff --git a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt index 9edd38f85e..df9b08ef74 100644 --- a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt +++ b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistoryTest.kt @@ -30,7 +30,9 @@ class DashHistoryTest { fun setUp() { val context = ApplicationProvider.getApplicationContext() database = Room.inMemoryDatabaseBuilder( - context, DashHistoryDatabase::class.java).build() + context, + DashHistoryDatabase::class.java + ).build() dao = database.historyRecordDao() dashHistory = DashHistory(dao, HistoryMapper()) } @@ -69,4 +71,4 @@ class DashHistoryTest { fun tearDown() { database.close() } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt index 6073957e5f..a649da837d 100644 --- a/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt +++ b/omnipod-dash/src/androidTest/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/RxSchedulerRule.kt @@ -26,7 +26,6 @@ class RxSchedulerRule(val scheduler: Scheduler) : TestRule { RxJavaPlugins.reset() RxAndroidPlugins.reset() } - } } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt index 953819cad3..7aa04163dd 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/EventOmnipodDashPumpValuesChanged.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash import info.nightscout.androidaps.events.Event -class EventOmnipodDashPumpValuesChanged : Event() \ No newline at end of file +class EventOmnipodDashPumpValuesChanged : Event() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index 4f6b4e7e8c..48cb6d25f4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -207,4 +207,4 @@ class OmnipodDashPumpPlugin @Inject constructor( override fun timezoneOrDSTChanged(timeChangeType: TimeChangeType) { // TODO } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt index 172dd497b0..16ab403d63 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashHistoryModule.kt @@ -29,5 +29,4 @@ class OmnipodDashHistoryModule { @Singleton internal fun provideDashHistory(dao: HistoryRecordDao, historyMapper: HistoryMapper) = DashHistory(dao, historyMapper) - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt index 98780b10d9..cbd7e42804 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashModule.kt @@ -47,4 +47,4 @@ abstract class OmnipodDashModule { @Binds abstract fun bindsOmnipodDashManagerImpl(omnipodManager: OmnipodDashManagerImpl): OmnipodDashManager -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt index 1b1aaf6f13..fc0f0f4e52 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/dagger/OmnipodDashWizardViewModelsModule.kt @@ -86,4 +86,4 @@ abstract class OmnipodDashWizardViewModelsModule { @OmnipodPluginQualifier @ViewModelKey(PodDiscardedViewModel::class) internal abstract fun podDiscardedViewModel(viewModel: DashPodDiscardedViewModel): ViewModel -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt index 4d7523eff6..aa5879f898 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManager.kt @@ -37,4 +37,4 @@ interface OmnipodDashManager { fun silenceAlerts(alerts: EnumSet): Observable fun deactivatePod(): Observable -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt index 884e755db7..7f115860cf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/OmnipodDashManagerImpl.kt @@ -50,14 +50,15 @@ class OmnipodDashManagerImpl @Inject constructor( private fun observeSendProgramBolusCommand(units: Double, rateInEighthPulsesPerSeconds: Byte, confirmationBeeps: Boolean, completionBeeps: Boolean): Observable { return Observable.defer { - bleManager.sendCommand(ProgramBolusCommand.Builder() - .setUniqueId(podStateManager.uniqueId!!.toInt()) - .setSequenceNumber(podStateManager.messageSequenceNumber) - .setNonce(1229869870) // TODO - .setNumberOfUnits(units) - .setDelayBetweenPulsesInEighthSeconds(rateInEighthPulsesPerSeconds) - .setProgramReminder(ProgramReminder(confirmationBeeps, completionBeeps, 0)) - .build() + bleManager.sendCommand( + ProgramBolusCommand.Builder() + .setUniqueId(podStateManager.uniqueId!!.toInt()) + .setSequenceNumber(podStateManager.messageSequenceNumber) + .setNonce(1229869870) // TODO + .setNumberOfUnits(units) + .setDelayBetweenPulsesInEighthSeconds(rateInEighthPulsesPerSeconds) + .setProgramReminder(ProgramReminder(confirmationBeeps, completionBeeps, 0)) + .build() ) } } @@ -78,13 +79,15 @@ class OmnipodDashManagerImpl @Inject constructor( get() = Observable.defer { observeSendGetPodStatusCommand() .ignoreElements() // - .andThen(Observable.defer { - if (podStateManager.podStatus == PodStatus.RUNNING_ABOVE_MIN_VOLUME) { - Observable.empty() - } else { - Observable.error(IllegalStateException("Unexpected Pod status")) + .andThen( + Observable.defer { + if (podStateManager.podStatus == PodStatus.RUNNING_ABOVE_MIN_VOLUME) { + Observable.empty() + } else { + Observable.error(IllegalStateException("Unexpected Pod status")) + } } - }) + ) } private fun observeSendProgramAlertsCommand(alertConfigurations: List, multiCommandFlag: Boolean = false): Observable { @@ -119,32 +122,38 @@ class OmnipodDashManagerImpl @Inject constructor( get() = Observable.defer { observeSendGetPodStatusCommand() .ignoreElements() // - .andThen(Observable.defer { - if (podStateManager.podStatus == PodStatus.CLUTCH_DRIVE_ENGAGED) { - Observable.empty() - } else { - Observable.error(IllegalStateException("Unexpected Pod status")) + .andThen( + Observable.defer { + if (podStateManager.podStatus == PodStatus.CLUTCH_DRIVE_ENGAGED) { + Observable.empty() + } else { + Observable.error(IllegalStateException("Unexpected Pod status")) + } } - }) + ) } private val observeSendSetUniqueIdCommand: Observable get() = Observable.defer { - bleManager.sendCommand(SetUniqueIdCommand.Builder() // - .setSequenceNumber(podStateManager.messageSequenceNumber) // - .setUniqueId(podStateManager.uniqueId!!.toInt()) // - .setLotNumber(podStateManager.lotNumber!!.toInt()) // - .setPodSequenceNumber(podStateManager.podSequenceNumber!!.toInt()) - .setInitializationTime(Date()) - .build()) // + bleManager.sendCommand( + SetUniqueIdCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(podStateManager.uniqueId!!.toInt()) // + .setLotNumber(podStateManager.lotNumber!!.toInt()) // + .setPodSequenceNumber(podStateManager.podSequenceNumber!!.toInt()) + .setInitializationTime(Date()) + .build() + ) // } private val observeSendGetVersionCommand: Observable get() = Observable.defer { - bleManager.sendCommand(GetVersionCommand.Builder() // - .setSequenceNumber(podStateManager.messageSequenceNumber) // - .setUniqueId(DEFAULT_UNIQUE_ID) // - .build()) // + bleManager.sendCommand( + GetVersionCommand.Builder() // + .setSequenceNumber(podStateManager.messageSequenceNumber) // + .setUniqueId(DEFAULT_UNIQUE_ID) // + .build() + ) // } override fun activatePodPart1(lowReservoirAlertTrigger: AlertTrigger.ReservoirVolumeTrigger?): Observable { @@ -277,30 +286,32 @@ class OmnipodDashManagerImpl @Inject constructor( ) } if (podStateManager.activationProgress.isBefore(ActivationProgress.UPDATED_EXPIRATION_ALERTS)) { - observables.add(observeSendProgramAlertsCommand( - listOf( - // FIXME use user configured expiration alert - AlertConfiguration( - AlertType.EXPIRATION, - enabled = true, - durationInMinutes = TimeUnit.HOURS.toMinutes(7).toShort(), - autoOff = false, - AlertTrigger.TimerTrigger(TimeUnit.HOURS.toMinutes(73).toShort()), // FIXME use activation time - BeepType.FOUR_TIMES_BIP_BEEP, - BeepRepetitionType.XXX3 + observables.add( + observeSendProgramAlertsCommand( + listOf( + // FIXME use user configured expiration alert + AlertConfiguration( + AlertType.EXPIRATION, + enabled = true, + durationInMinutes = TimeUnit.HOURS.toMinutes(7).toShort(), + autoOff = false, + AlertTrigger.TimerTrigger(TimeUnit.HOURS.toMinutes(73).toShort()), // FIXME use activation time + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX3 + ), + AlertConfiguration( + AlertType.EXPIRATION_IMMINENT, + enabled = true, + durationInMinutes = TimeUnit.HOURS.toMinutes(1).toShort(), + autoOff = false, + AlertTrigger.TimerTrigger(TimeUnit.HOURS.toMinutes(79).toShort()), // FIXME use activation time + BeepType.FOUR_TIMES_BIP_BEEP, + BeepRepetitionType.XXX4 + ) ), - AlertConfiguration( - AlertType.EXPIRATION_IMMINENT, - enabled = true, - durationInMinutes = TimeUnit.HOURS.toMinutes(1).toShort(), - autoOff = false, - AlertTrigger.TimerTrigger(TimeUnit.HOURS.toMinutes(79).toShort()), // FIXME use activation time - BeepType.FOUR_TIMES_BIP_BEEP, - BeepRepetitionType.XXX4 - ) - ), - multiCommandFlag = true - ).doOnComplete(ActivationProgressUpdater(ActivationProgress.UPDATED_EXPIRATION_ALERTS))) + multiCommandFlag = true + ).doOnComplete(ActivationProgressUpdater(ActivationProgress.UPDATED_EXPIRATION_ALERTS)) + ) } if (podStateManager.activationProgress.isBefore(ActivationProgress.PROGRAMMED_BASAL)) { observables.add( @@ -399,7 +410,7 @@ class OmnipodDashManagerImpl @Inject constructor( handleResponse(event.response) } - else -> { + else -> { // Do nothing } } @@ -424,7 +435,6 @@ class OmnipodDashManagerImpl @Inject constructor( } } } - } inner class ErrorInterceptor : Consumer { @@ -432,7 +442,6 @@ class OmnipodDashManagerImpl @Inject constructor( override fun accept(throwable: Throwable) { logger.debug(LTag.PUMP, "Intercepted error in OmnipodDashManagerImpl: ${throwable.javaClass.simpleName}") } - } inner class ActivationProgressUpdater(private val value: ActivationProgress) : Action { @@ -440,6 +449,5 @@ class OmnipodDashManagerImpl @Inject constructor( override fun run() { podStateManager.activationProgress = value } - } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt index 866c65b922..3ca97e76b4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/Id.kt @@ -22,7 +22,7 @@ data class Id(val address: ByteArray) { override fun toString(): String { val asInt = ByteBuffer.wrap(address).int - return "${asInt}/${address.toHex()}" + return "$asInt/${address.toHex()}" } companion object { @@ -33,5 +33,4 @@ data class Id(val address: ByteArray) { return Id(ByteBuffer.allocate(4).putInt(v).array()) } } - } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt index aa0b64e641..11e808ba73 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManager.kt @@ -14,4 +14,4 @@ interface OmnipodDashBleManager { fun connect(): Observable fun disconnect() -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt index be03f69525..1f4c92bbf5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/OmnipodDashBleManagerImpl.kt @@ -39,8 +39,10 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context // TODO: locking? val podDevice = bluetoothAdapter.getRemoteDevice(podAddress) val incomingPackets: Map> = - mapOf(CharacteristicType.CMD to LinkedBlockingDeque(), - CharacteristicType.DATA to LinkedBlockingDeque()) + mapOf( + CharacteristicType.CMD to LinkedBlockingDeque(), + CharacteristicType.DATA to LinkedBlockingDeque() + ) val bleCommCallbacks = BleCommCallbacks(aapsLogger, incomingPackets) aapsLogger.debug(LTag.PUMPBTCOMM, "Connecting to $podAddress") var autoConnect = true @@ -118,5 +120,4 @@ class OmnipodDashBleManagerImpl @Inject constructor(private val context: Context private const val CONNECT_TIMEOUT_MS = 7000 const val CONTROLLER_ID = 4242 // TODO read from preferences or somewhere else. } - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt index 8ebde34478..ceb471cabb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/ServiceDiscoverer.kt @@ -4,7 +4,6 @@ import android.bluetooth.BluetoothGatt import android.bluetooth.BluetoothGattCharacteristic import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag - import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.CharacteristicNotFoundException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ServiceNotFoundException @@ -29,8 +28,10 @@ class ServiceDiscoverer(private val logger: AAPSLogger, private val gatt: Blueto ?: throw CharacteristicNotFoundException(CharacteristicType.CMD.value) val dataChar = service.getCharacteristic(CharacteristicType.DATA.uuid) // TODO: this is never used ?: throw CharacteristicNotFoundException(CharacteristicType.DATA.value) - var chars = mapOf(CharacteristicType.CMD to cmdChar, - CharacteristicType.DATA to dataChar) + var chars = mapOf( + CharacteristicType.CMD to cmdChar, + CharacteristicType.DATA to dataChar + ) return chars } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt index 451a723296..49094d7d3b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/BleCommCallbacks.kt @@ -77,8 +77,11 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP } else { CharacteristicWriteConfirmationError(status) } - aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicWrite with status/char/value " + - status + "/" + byValue(characteristic.uuid.toString()) + "/" + characteristic.value.toHex()) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "OnCharacteristicWrite with status/char/value " + + status + "/" + byValue(characteristic.uuid.toString()) + "/" + characteristic.value.toHex() + ) try { if (writeQueue.size > 0) { aapsLogger.warn(LTag.PUMPBTCOMM, "Write confirm queue should be empty. found: " + writeQueue.size) @@ -97,9 +100,12 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP super.onCharacteristicChanged(gatt, characteristic) val payload = characteristic.value val characteristicType = byValue(characteristic.uuid.toString()) - aapsLogger.debug(LTag.PUMPBTCOMM, "OnCharacteristicChanged with char/value " + - characteristicType + "/" + - payload.toHex()) + aapsLogger.debug( + LTag.PUMPBTCOMM, + "OnCharacteristicChanged with char/value " + + characteristicType + "/" + + payload.toHex() + ) incomingPackets[characteristicType]!!.add(payload) } @@ -109,12 +115,13 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP ?: throw TimeoutException() when (confirmed) { is DescriptorWriteConfirmationError -> throw CouldNotConfirmWriteException(confirmed.status) - is DescriptorWriteConfirmationUUID -> if (confirmed.uuid != descriptorUUID) { - aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got ${confirmed.uuid}. Expected: $descriptorUUID") - throw CouldNotConfirmDescriptorWriteException(descriptorUUID, confirmed.uuid) - } else { - aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed descriptor write : " + confirmed.uuid) - } + is DescriptorWriteConfirmationUUID -> + if (confirmed.uuid != descriptorUUID) { + aapsLogger.warn(LTag.PUMPBTCOMM, "Could not confirm descriptor write. Got ${confirmed.uuid}. Expected: $descriptorUUID") + throw CouldNotConfirmDescriptorWriteException(descriptorUUID, confirmed.uuid) + } else { + aapsLogger.debug(LTag.PUMPBTCOMM, "Confirmed descriptor write : " + confirmed.uuid) + } } } @@ -144,4 +151,4 @@ class BleCommCallbacks(private val aapsLogger: AAPSLogger, private val incomingP private const val WRITE_CONFIRM_TIMEOUT_MS = 10 // the confirmation queue should be empty anyway } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt index 31e3595050..575bd19c0f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/CharacteristicWriteConfirmation.kt @@ -4,4 +4,4 @@ sealed class CharacteristicWriteConfirmation data class CharacteristicWriteConfirmationPayload(val payload: ByteArray) : CharacteristicWriteConfirmation() -data class CharacteristicWriteConfirmationError(val status: Int) : CharacteristicWriteConfirmation() \ No newline at end of file +data class CharacteristicWriteConfirmationError(val status: Int) : CharacteristicWriteConfirmation() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt index fbbb5b7f1b..83fc9d41c8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/callbacks/DescriptorWriteConfirmation.kt @@ -4,4 +4,4 @@ sealed class DescriptorWriteConfirmation data class DescriptorWriteConfirmationUUID(val uuid: String) : DescriptorWriteConfirmation() -data class DescriptorWriteConfirmationError(val status: Int) : DescriptorWriteConfirmation() \ No newline at end of file +data class DescriptorWriteConfirmationError(val status: Int) : DescriptorWriteConfirmation() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt index 03414989b2..d10ae85aa1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandHello.kt @@ -2,9 +2,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command import java.nio.ByteBuffer -class BleCommandHello(controllerId: Int) : BleCommand(BleCommandType.HELLO, +class BleCommandHello(controllerId: Int) : BleCommand( + BleCommandType.HELLO, ByteBuffer.allocate(6) .put(1.toByte()) // TODO find the meaning of this constant .put(4.toByte()) // TODO find the meaning of this constant .putInt(controllerId).array() -) \ No newline at end of file +) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt index 5c096d4410..8557bfb4e9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/command/BleCommandType.kt @@ -10,4 +10,4 @@ enum class BleCommandType(val value: Byte) { values().firstOrNull { it.value == value } ?: throw IllegalArgumentException("Unknown BleCommandType: $value") } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt index 6029d66998..1fa748a391 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/BleIOBusyException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class BleIOBusyException : Exception() \ No newline at end of file +class BleIOBusyException : Exception() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt index 730b6eeda0..dedd9399ab 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CharacteristicNotFoundException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class CharacteristicNotFoundException(cmdCharacteristicUuid: String) : FailedToConnectException("characteristic not found: $cmdCharacteristicUuid") \ No newline at end of file +class CharacteristicNotFoundException(cmdCharacteristicUuid: String) : FailedToConnectException("characteristic not found: $cmdCharacteristicUuid") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt index 75c9f82344..ffc37a29da 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmDescriptorWriteException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions class CouldNotConfirmDescriptorWriteException(override val message: String?) : Exception(message) { - constructor(sent: String, confirmed: String) : this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") - constructor(status: Int) : this("Could not confirm write. Write status: ${status}") -} \ No newline at end of file + constructor(sent: String, confirmed: String) : this("Could not confirm write. Sent: {$sent} .Received: $confirmed") + constructor(status: Int) : this("Could not confirm write. Write status: $status") +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt index 9217668e77..7e5573d1ca 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotConfirmWriteException.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions class CouldNotConfirmWriteException(override val message: String?) : Exception(message) { - constructor(sent: ByteArray, confirmed: ByteArray) : this("Could not confirm write. Sent: {$sent} .Received: ${confirmed}") - constructor(status: Int) : this("Could not confirm write. Write status: ${status}") -} \ No newline at end of file + constructor(sent: ByteArray, confirmed: ByteArray) : this("Could not confirm write. Sent: {$sent} .Received: $confirmed") + constructor(status: Int) : this("Could not confirm write. Write status: $status") +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt index b9987da037..1e982d21a0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotEnableNotifications.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType -class CouldNotEnableNotifications(cmd: CharacteristicType) : Exception(cmd.value) \ No newline at end of file +class CouldNotEnableNotifications(cmd: CharacteristicType) : Exception(cmd.value) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt index 5e10a0bb1e..816d062636 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotParseMessageException.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import info.nightscout.androidaps.utils.extensions.toHex -class CouldNotParseMessageException(val payload: ByteArray) : Exception("Could not parse message payload: ${payload.toHex()}") \ No newline at end of file +class CouldNotParseMessageException(val payload: ByteArray) : Exception("Could not parse message payload: ${payload.toHex()}") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt index 63abcb9a68..83680ec002 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/CouldNotSendBleException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class CouldNotSendBleException(msg: String?) : Exception(msg) \ No newline at end of file +class CouldNotSendBleException(msg: String?) : Exception(msg) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt index 202fcaf3b1..4a87e667e9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DescriptorNotFoundException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class DescriptorNotFoundException : Exception() \ No newline at end of file +class DescriptorNotFoundException : Exception() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt index a4f7b52f75..5606ceb3ad 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/DiscoveredInvalidPodException.kt @@ -5,4 +5,4 @@ import android.os.ParcelUuid class DiscoveredInvalidPodException : Exception { constructor(message: String) : super(message) constructor(message: String, serviceUUIds: List) : super("$message service UUIDs: $serviceUUIds") -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt index 8d6782aadb..4c138d0b2e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/FailedToConnectException.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti open class FailedToConnectException : Exception { constructor() : super() constructor(message: String?) : super(message) -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt index 5645cb009b..1deed2f63c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/MessageIOException.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti class MessageIOException : Exception { constructor(msg: String) : super(msg) constructor(cause: Throwable) : super("Caught Exception during Message I/O", cause) -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt index 396cdffcf4..15b3432ec3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailException.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti open class ScanFailException : Exception { constructor(message: String) : super(message) constructor(errorCode: Int) : super("errorCode$errorCode") -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt index 002ecabf3d..88d678ab88 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailFoundTooManyException.kt @@ -8,4 +8,4 @@ class ScanFailFoundTooManyException(devices: List) : ScanFa private val devices: List = ArrayList(devices) val discoveredDevices: List get() = Collections.unmodifiableList(devices) -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt index 55b189baff..848331257a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ScanFailNotFoundException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class ScanFailNotFoundException : ScanFailException("No Pod found") \ No newline at end of file +class ScanFailNotFoundException : ScanFailException("No Pod found") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt index dc792f5825..16c19f65a9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/ServiceNotFoundException.kt @@ -1,3 +1,3 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions -class ServiceNotFoundException(serviceUuid: String) : FailedToConnectException("service not found: $serviceUuid") \ No newline at end of file +class ServiceNotFoundException(serviceUuid: String) : FailedToConnectException("service not found: $serviceUuid") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt index 149909032d..82a2950f2d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/exceptions/UnexpectedCommandException.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.excepti import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command.BleCommand -class UnexpectedCommandException(val cmd: BleCommand) : Exception("Unexpected command: ${cmd}") \ No newline at end of file +class UnexpectedCommandException(val cmd: BleCommand) : Exception("Unexpected command: $cmd") diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index 3340d1daf1..de2125a2b5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -97,4 +97,4 @@ class BleIO(private val aapsLogger: AAPSLogger, private val chars: Map throw IncorrectPacketException(0, firstPacket) - fullFragments == 0 -> { + fullFragments == 0 -> { crc = ByteBuffer.wrap(firstPacket.copyOfRange(2, 6)).int.toUnsignedLong() val rest = firstPacket[6] val end = min(rest + FirstBlePacket.HEADER_SIZE_WITHOUT_MIDDLE_PACKETS, BlePacket.MAX_SIZE) @@ -41,10 +41,10 @@ class PayloadJoiner(private val firstPacket: ByteArray) { } // With middle packets - firstPacket.size < BlePacket.MAX_SIZE -> + firstPacket.size < BlePacket.MAX_SIZE -> throw IncorrectPacketException(0, firstPacket) - else -> { + else -> { fragments.add(firstPacket.copyOfRange(FirstBlePacket.HEADER_SIZE_WITH_MIDDLE_PACKETS, BlePacket.MAX_SIZE)) } } @@ -60,7 +60,7 @@ class PayloadJoiner(private val firstPacket: ByteArray) { } expectedIndex++ when { - idx < fullFragments -> { // this is a middle fragment + idx < fullFragments -> { // this is a middle fragment if (packet.size < BlePacket.MAX_SIZE) { throw IncorrectPacketException(idx.toByte(), packet) } @@ -81,7 +81,7 @@ class PayloadJoiner(private val firstPacket: ByteArray) { fragments.add(packet.copyOfRange(LastBlePacket.HEADER_SIZE, packet.size)) } - idx > fullFragments -> { // this is the extra fragment + idx > fullFragments -> { // this is the extra fragment val size = packet[1].toInt() if (packet.size < LastOptionalPlusOneBlePacket.HEADER_SIZE + size) { throw IncorrectPacketException(idx.toByte(), packet) @@ -103,7 +103,6 @@ class PayloadJoiner(private val firstPacket: ByteArray) { } return bytes.copyOfRange(0, bytes.size) } - } -internal fun Int.toUnsignedLong() = this.toLong() and 0xffffffffL \ No newline at end of file +internal fun Int.toUnsignedLong() = this.toLong() and 0xffffffffL diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt index bd5e5811db..efee6a52ae 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/PayloadSplitter.kt @@ -15,51 +15,63 @@ internal class PayloadSplitter(private val payload: ByteArray) { val crc32 = payload.crc32() if (payload.size <= FirstBlePacket.CAPACITY_WITH_THE_OPTIONAL_PLUS_ONE_PACKET) { val end = min(FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS, payload.size) - ret.add(FirstBlePacket( - totalFragments = 0, - payload = payload.copyOfRange(0, end), - size = payload.size.toByte(), - crc32 = crc32, - )) + ret.add( + FirstBlePacket( + totalFragments = 0, + payload = payload.copyOfRange(0, end), + size = payload.size.toByte(), + crc32 = crc32, + ) + ) if (payload.size > FirstBlePacket.CAPACITY_WITHOUT_MIDDLE_PACKETS) { - ret.add(LastOptionalPlusOneBlePacket( - index = 1, - payload = payload.copyOfRange(end, payload.size), - size = (payload.size - end).toByte(), - )) + ret.add( + LastOptionalPlusOneBlePacket( + index = 1, + payload = payload.copyOfRange(end, payload.size), + size = (payload.size - end).toByte(), + ) + ) } return ret } val middleFragments = (payload.size - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS) / MiddleBlePacket.CAPACITY val rest = ((payload.size - middleFragments * MiddleBlePacket.CAPACITY) - FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS).toByte() - ret.add(FirstBlePacket( - totalFragments = (middleFragments + 1).toByte(), - payload = payload.copyOfRange(0, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS), - )) + ret.add( + FirstBlePacket( + totalFragments = (middleFragments + 1).toByte(), + payload = payload.copyOfRange(0, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS), + ) + ) for (i in 1..middleFragments) { val p = if (i == 1) { payload.copyOfRange(FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + MiddleBlePacket.CAPACITY) } else { payload.copyOfRange(FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + (i - 1) * MiddleBlePacket.CAPACITY, FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + i * MiddleBlePacket.CAPACITY) } - ret.add(MiddleBlePacket( - index = i.toByte(), - payload = p, - )) + ret.add( + MiddleBlePacket( + index = i.toByte(), + payload = p, + ) + ) } val end = min(LastBlePacket.CAPACITY, rest.toInt()) - ret.add(LastBlePacket( - index = (middleFragments + 1).toByte(), - size = rest, - payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + end), - crc32 = crc32, - )) + ret.add( + LastBlePacket( + index = (middleFragments + 1).toByte(), + size = rest, + payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS, middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + end), + crc32 = crc32, + ) + ) if (rest > LastBlePacket.CAPACITY) { - ret.add(LastOptionalPlusOneBlePacket( - index = (middleFragments + 2).toByte(), - size = (rest - LastBlePacket.CAPACITY).toByte(), - payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + LastBlePacket.CAPACITY, payload.size), - )) + ret.add( + LastOptionalPlusOneBlePacket( + index = (middleFragments + 2).toByte(), + size = (rest - LastBlePacket.CAPACITY).toByte(), + payload = payload.copyOfRange(middleFragments * MiddleBlePacket.CAPACITY + FirstBlePacket.CAPACITY_WITH_MIDDLE_PACKETS + LastBlePacket.CAPACITY, payload.size), + ) + ) } return ret } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt index 7ec6048aed..786a210bfb 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/message/StringLengthPrefixEncoding.kt @@ -18,21 +18,21 @@ class StringLengthPrefixEncoding { var remaining = payload for ((index, key) in keys.withIndex()) { when { - remaining.size < key.length -> - throw MessageIOException("Payload too short: ${payload.toHex()} for key: ${key}") + remaining.size < key.length -> + throw MessageIOException("Payload too short: ${payload.toHex()} for key: $key") !(remaining.copyOfRange(0, key.length).decodeToString() == key) -> - throw MessageIOException("Key not found: ${key} in ${payload.toHex()}") + throw MessageIOException("Key not found: $key in ${payload.toHex()}") // last key can be empty, no length - index == keys.size - 1 && remaining.size == key.length -> + index == keys.size - 1 && remaining.size == key.length -> return ret - remaining.size < key.length + LENGTH_BYTES -> - throw MessageIOException("Length not found: for ${key} in ${payload.toHex()}") + remaining.size < key.length + LENGTH_BYTES -> + throw MessageIOException("Length not found: for $key in ${payload.toHex()}") } remaining = remaining.copyOfRange(key.length, remaining.size) val length = (remaining[0].toUnsignedInt() shl 1) or remaining[1].toUnsignedInt() if (length > remaining.size) { - throw MessageIOException("Payload too short, looking for length ${length} for ${key} in ${payload.toHex()}") + throw MessageIOException("Payload too short, looking for length $length for $key in ${payload.toHex()}") } ret[index] = remaining.copyOfRange(LENGTH_BYTES, LENGTH_BYTES + length) remaining = remaining.copyOfRange(LENGTH_BYTES + length, remaining.size) @@ -60,4 +60,4 @@ class StringLengthPrefixEncoding { return ret } } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt index eb020c5b28..7bb51c2789 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/packet/BlePacket.kt @@ -92,4 +92,3 @@ data class LastOptionalPlusOneBlePacket(val index: Byte, val payload: ByteArray, internal const val HEADER_SIZE = 2 } } - diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt index cc76bd232f..a6cc8b3bb5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt @@ -253,4 +253,4 @@ private fun aesCmac(key: ByteArray, data: ByteArray, result: ByteArray) { mac.init(KeyParameter(key)) mac.update(data, 0, data.size) mac.doFinal(result, 0) -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt index f36baea723..af705fd720 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/PairMessage.kt @@ -17,4 +17,4 @@ data class PairMessage( sequenceNumber = sequenceNumber, sas = true // TODO: understand why this is true for PairMessages ), -) \ No newline at end of file +) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt index bf3d3dd74c..4439eecf95 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/BleDiscoveredDevice.kt @@ -15,7 +15,6 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: Sc val serviceUuids = scanRecord.serviceUuids if (serviceUuids.size != 9) { throw DiscoveredInvalidPodException("Expected 9 service UUIDs, got" + serviceUuids.size, serviceUuids) - } if (extractUUID16(serviceUuids[0]) != MAIN_SERVICE_UUID) { // this is the service that we filtered for @@ -79,4 +78,4 @@ class BleDiscoveredDevice(val scanResult: ScanResult, private val scanRecord: Sc lotNo = parseLotNo() sequenceNo = parseSeqNo() } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt index e898b755fe..4a9932a4de 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/PodScanner.kt @@ -45,4 +45,4 @@ class PodScanner(private val logger: AAPSLogger, private val bluetoothAdapter: B const val POD_ID_NOT_ACTIVATED = 0xFFFFFFFFL private const val SCAN_DURATION_MS = 5000 } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt index 658f3b69ff..82c249d492 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/scan/ScanCollector.kt @@ -45,5 +45,4 @@ class ScanCollector(private val logger: AAPSLogger, private val podID: Long) : S } return Collections.unmodifiableList(ret) } - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt index 3f11ca87b5..8343887516 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/status/ConnectionStatus.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.status enum class ConnectionStatus { CONNECTED, NOT_CONNECTED; -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt index 0bc6bf5125..b0429dd1d5 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/event/PodEvent.kt @@ -20,4 +20,3 @@ sealed class PodEvent { class CommandSent(val command: Command) : PodEvent() class ResponseReceived(val response: Response) : PodEvent() } - diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt index ec122495bc..da35042d78 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommand.kt @@ -13,12 +13,14 @@ class DeactivateCommand private constructor( ) : NonceEnabledCommand(CommandType.DEACTIVATE, uniqueId, sequenceNumber, multiCommandFlag, nonce) { override val encoded: ByteArray - get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .putInt(nonce) // - .array()) + get() = appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(nonce) // + .array() + ) override fun toString(): String = "DeactivateCommand{" + "nonce=" + nonce + @@ -39,4 +41,4 @@ class DeactivateCommand private constructor( private const val LENGTH: Short = 6 private const val BODY_LENGTH: Byte = 4 } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt index ac9228125a..b5f262da17 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommand.kt @@ -14,12 +14,14 @@ class GetStatusCommand private constructor( ) : HeaderEnabledCommand(CommandType.GET_STATUS, uniqueId, sequenceNumber, multiCommandFlag) { override val encoded: ByteArray - get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .put(statusResponseType.value) // - .array()) + get() = appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .put(statusResponseType.value) // + .array() + ) class Builder : HeaderEnabledCommandBuilder() { @@ -35,7 +37,6 @@ class GetStatusCommand private constructor( return GetStatusCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, statusResponseType!!) } - } companion object { @@ -43,4 +44,4 @@ class GetStatusCommand private constructor( private const val LENGTH: Short = 3 private const val BODY_LENGTH: Byte = 1 } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt index a06a3624e6..26c480e999 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommand.kt @@ -12,12 +12,14 @@ class GetVersionCommand private constructor( ) : HeaderEnabledCommand(CommandType.GET_VERSION, uniqueId, sequenceNumber, multiCommandFlag) { override val encoded: ByteArray - get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .putInt(uniqueId) // - .array()) + get() = appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(uniqueId) // + .array() + ) override fun toString(): String { return "GetVersionCommand{" + @@ -41,4 +43,4 @@ class GetVersionCommand private constructor( private const val LENGTH: Short = 6 private const val BODY_LENGTH: Byte = 4 } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt index 44c8505a49..11191e8812 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommand.kt @@ -67,4 +67,4 @@ class ProgramAlertsCommand private constructor( init { this.alertConfigurations = ArrayList(alertConfigurations) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt index 9e9afdd3d3..17d83d3e5a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommand.kt @@ -49,11 +49,13 @@ class ProgramBasalCommand private constructor( val basalCommand = buffer.array() val interlockCommand = interlockCommand.encoded val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (basalCommand.size + interlockCommand.size).toShort(), multiCommandFlag) - return appendCrc(ByteBuffer.allocate(basalCommand.size + interlockCommand.size + header.size) // - .put(header) // - .put(interlockCommand) // - .put(basalCommand) // - .array()) + return appendCrc( + ByteBuffer.allocate(basalCommand.size + interlockCommand.size + header.size) // + .put(header) // + .put(interlockCommand) // + .put(basalCommand) // + .array() + ) } override fun toString(): String { @@ -102,12 +104,16 @@ class ProgramBasalCommand private constructor( val longInsulinProgramElements: List = mapTenthPulsesPerSlotToLongInsulinProgramElements(ProgramBasalUtil.mapBasalProgramToTenthPulsesPerSlot(basalProgram!!)) val shortInsulinProgramElements = ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) val currentBasalInsulinProgramElement = ProgramBasalUtil.calculateCurrentLongInsulinProgramElement(longInsulinProgramElements, currentTime) - val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, + val interlockCommand = ProgramInsulinCommand( + uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, shortInsulinProgramElements, checksum, currentSlot.index, currentSlot.eighthSecondsRemaining, - currentSlot.pulsesRemaining, ProgramInsulinCommand.DeliveryType.BASAL) - return ProgramBasalCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, + currentSlot.pulsesRemaining, ProgramInsulinCommand.DeliveryType.BASAL + ) + return ProgramBasalCommand( + interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, longInsulinProgramElements, programReminder!!, currentBasalInsulinProgramElement.index, - currentBasalInsulinProgramElement.remainingTenthPulses, currentBasalInsulinProgramElement.delayUntilNextTenthPulseInUsec) + currentBasalInsulinProgramElement.remainingTenthPulses, currentBasalInsulinProgramElement.delayUntilNextTenthPulseInUsec + ) } } @@ -118,4 +124,4 @@ class ProgramBasalCommand private constructor( this.remainingTenthPulsesInCurrentInsulinProgramElement = remainingTenthPulsesInCurrentInsulinProgramElement this.delayUntilNextTenthPulseInUsec = delayUntilNextTenthPulseInUsec } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt index d9412e7363..a6f2efd180 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommand.kt @@ -18,15 +18,17 @@ class ProgramBeepsCommand private constructor( ) : HeaderEnabledCommand(CommandType.PROGRAM_BEEPS, uniqueId, sequenceNumber, multiCommandFlag) { override val encoded: ByteArray - get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .put(immediateBeepType.value) // - .put(basalReminder.encoded) // - .put(tempBasalReminder.encoded) // - .put(bolusReminder.encoded) // - .array()) + get() = appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .put(immediateBeepType.value) // + .put(basalReminder.encoded) // + .put(tempBasalReminder.encoded) // + .put(bolusReminder.encoded) // + .array() + ) class Builder : HeaderEnabledCommandBuilder() { @@ -70,4 +72,4 @@ class ProgramBeepsCommand private constructor( private const val LENGTH: Short = 6 private const val BODY_LENGTH: Byte = 4 } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt index c02f1d3ef0..c16533501f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommand.kt @@ -32,11 +32,13 @@ class ProgramBolusCommand private constructor( .array() val interlockCommand = interlockCommand.encoded val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (bolusCommand.size + interlockCommand.size).toShort(), multiCommandFlag) - return appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + bolusCommand.size) // - .put(header) // - .put(interlockCommand) // - .put(bolusCommand) // - .array()) + return appendCrc( + ByteBuffer.allocate(header.size + interlockCommand.size + bolusCommand.size) // + .put(header) // + .put(interlockCommand) // + .put(bolusCommand) // + .array() + ) } override fun toString(): String { @@ -82,8 +84,10 @@ class ProgramBolusCommand private constructor( val numberOfPulses = Math.round(numberOfUnits!! * 20).toShort() val byte10And11 = (numberOfPulses * delayBetweenPulsesInEighthSeconds!!).toShort() - val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, listOf(BolusShortInsulinProgramElement(numberOfPulses)), calculateChecksum(0x01.toByte(), byte10And11, numberOfPulses), - 0x01.toByte(), byte10And11, numberOfPulses, ProgramInsulinCommand.DeliveryType.BOLUS) + val interlockCommand = ProgramInsulinCommand( + uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, listOf(BolusShortInsulinProgramElement(numberOfPulses)), calculateChecksum(0x01.toByte(), byte10And11, numberOfPulses), + 0x01.toByte(), byte10And11, numberOfPulses, ProgramInsulinCommand.DeliveryType.BOLUS + ) val delayUntilFirstTenthPulseInUsec = delayBetweenPulsesInEighthSeconds!! / 8 * 100000 return ProgramBolusCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, programReminder!!, (numberOfPulses * 10).toShort(), delayUntilFirstTenthPulseInUsec) } @@ -94,12 +98,14 @@ class ProgramBolusCommand private constructor( private const val LENGTH: Short = 15 private const val BODY_LENGTH: Byte = 13 private fun calculateChecksum(numberOfSlots: Byte, byte10And11: Short, numberOfPulses: Short): Short { - return MessageUtil.calculateChecksum(ByteBuffer.allocate(7) // - .put(numberOfSlots) // - .putShort(byte10And11) // - .putShort(numberOfPulses) // - .putShort(numberOfPulses) // - .array()) + return MessageUtil.calculateChecksum( + ByteBuffer.allocate(7) // + .put(numberOfSlots) // + .putShort(byte10And11) // + .putShort(numberOfPulses) // + .putShort(numberOfPulses) // + .array() + ) } } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt index 0020407056..437d52029c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramInsulinCommand.kt @@ -11,8 +11,9 @@ class ProgramInsulinCommand internal constructor( uniqueId: Int, sequenceNumber: Short, multiCommandFlag: Boolean, - nonce: Int, insulinProgramElements: - List, + nonce: Int, + insulinProgramElements: + List, private val checksum: Short, private val byte9: Byte, private val byte10And11: Short, @@ -66,4 +67,4 @@ class ProgramInsulinCommand internal constructor( ", multiCommandFlag=" + multiCommandFlag + '}' } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt index c0179ed62e..987cd0cca8 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommand.kt @@ -59,9 +59,11 @@ class ProgramTempBasalCommand private constructor( val tenthPulsesPerSlot = ProgramTempBasalUtil.mapTempBasalToTenthPulsesPerSlot(durationInSlots.toInt(), rateInUnitsPerHour!!) val shortInsulinProgramElements = ProgramTempBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) val insulinProgramElements = ProgramTempBasalUtil.mapTenthPulsesPerSlotToLongInsulinProgramElements(tenthPulsesPerSlot) - val interlockCommand = ProgramInsulinCommand(uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, shortInsulinProgramElements, + val interlockCommand = ProgramInsulinCommand( + uniqueId!!, sequenceNumber!!, multiCommandFlag, nonce!!, shortInsulinProgramElements, ProgramTempBasalUtil.calculateChecksum(durationInSlots, pulsesPerSlot[0], pulsesPerSlot), durationInSlots, - 0x3840.toShort(), pulsesPerSlot[0], ProgramInsulinCommand.DeliveryType.TEMP_BASAL) + 0x3840.toShort(), pulsesPerSlot[0], ProgramInsulinCommand.DeliveryType.TEMP_BASAL + ) return ProgramTempBasalCommand(interlockCommand, uniqueId!!, sequenceNumber!!, multiCommandFlag, programReminder!!, insulinProgramElements) } } @@ -91,10 +93,12 @@ class ProgramTempBasalCommand private constructor( val tempBasalCommand = buffer.array() val interlockCommand = interlockCommand.encoded val header: ByteArray = encodeHeader(uniqueId, sequenceNumber, (tempBasalCommand.size + interlockCommand.size).toShort(), multiCommandFlag) - return appendCrc(ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) // - .put(header) // - .put(interlockCommand) // - .put(tempBasalCommand) // - .array()) + return appendCrc( + ByteBuffer.allocate(header.size + interlockCommand.size + tempBasalCommand.size) // + .put(header) // + .put(interlockCommand) // + .put(tempBasalCommand) // + .array() + ) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt index 04d62e99ac..e70b7629dc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommand.kt @@ -16,17 +16,19 @@ class SetUniqueIdCommand private constructor( ) : HeaderEnabledCommand(CommandType.SET_UNIQUE_ID, uniqueId, sequenceNumber, multiCommandFlag) { override val encoded: ByteArray - get() = appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .putInt(uniqueId) // - .put(0x14.toByte()) // FIXME ?? - .put(0x04.toByte()) // FIXME ?? - .put(encodeInitializationTime(initializationTime)) // - .putInt(lotNumber) // - .putInt(podSequenceNumber) // - .array()) + get() = appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(DEFAULT_UNIQUE_ID, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(uniqueId) // + .put(0x14.toByte()) // FIXME ?? + .put(0x04.toByte()) // FIXME ?? + .put(encodeInitializationTime(initializationTime)) // + .putInt(lotNumber) // + .putInt(podSequenceNumber) // + .array() + ) override fun toString(): String { return "SetUniqueIdCommand{" + @@ -78,12 +80,12 @@ class SetUniqueIdCommand private constructor( val instance = Calendar.getInstance() instance.time = date return byteArrayOf( // - (instance[Calendar.MONTH] + 1).toByte(), // - instance[Calendar.DATE].toByte(), // - (instance[Calendar.YEAR] % 100).toByte(), // - instance[Calendar.HOUR_OF_DAY].toByte(), // + (instance[Calendar.MONTH] + 1).toByte(), // + instance[Calendar.DATE].toByte(), // + (instance[Calendar.YEAR] % 100).toByte(), // + instance[Calendar.HOUR_OF_DAY].toByte(), // instance[Calendar.MINUTE].toByte() // ) } } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt index 1b3c531ee9..68d2738c89 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommand.kt @@ -18,13 +18,15 @@ class SilenceAlertsCommand private constructor( override val encoded: ByteArray get() = - appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .putInt(nonce) // - .put(AlertUtil.encodeAlertSet(alertTypes)) // - .array()) + appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(nonce) // + .put(AlertUtil.encodeAlertSet(alertTypes)) // + .array() + ) override fun toString(): String { return "SilenceAlertsCommand{" + @@ -57,4 +59,4 @@ class SilenceAlertsCommand private constructor( private const val LENGTH = 7.toShort() private const val BODY_LENGTH = 5.toByte() } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt index 603a7ff09d..17ee811b30 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommand.kt @@ -19,13 +19,15 @@ class StopDeliveryCommand private constructor( override val encoded: ByteArray get() { - return appendCrc(ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // - .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // - .put(commandType.value) // - .put(BODY_LENGTH) // - .putInt(nonce) // - .put((beepType.value.toInt() shl 4 or deliveryType.encoded[0].toInt()).toByte()) // - .array()) + return appendCrc( + ByteBuffer.allocate(LENGTH + HEADER_LENGTH) // + .put(encodeHeader(uniqueId, sequenceNumber, LENGTH, multiCommandFlag)) // + .put(commandType.value) // + .put(BODY_LENGTH) // + .putInt(nonce) // + .put((beepType.value.toInt() shl 4 or deliveryType.encoded[0].toInt()).toByte()) // + .array() + ) } override fun toString(): String { @@ -81,4 +83,4 @@ class StopDeliveryCommand private constructor( private const val LENGTH: Short = 7 private const val BODY_LENGTH: Byte = 5 } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt index bbe29cb2e5..0b509a8ae1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/Command.kt @@ -6,4 +6,4 @@ import java.io.Serializable interface Command : Encodable, Serializable { val commandType: CommandType -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt index 1cc50ff135..1cbcf8ae97 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/CommandType.kt @@ -6,12 +6,12 @@ enum class CommandType(val value: Byte) { GET_VERSION(0x07.toByte()), GET_STATUS(0x0e.toByte()), SILENCE_ALERTS(0x11.toByte()), - PROGRAM_BASAL(0x13.toByte()), // Always preceded by 0x1a - PROGRAM_TEMP_BASAL(0x16.toByte()), // Always preceded by 0x1a - PROGRAM_BOLUS(0x17.toByte()), // Always preceded by 0x1a + PROGRAM_BASAL(0x13.toByte()), // Always preceded by 0x1a + PROGRAM_TEMP_BASAL(0x16.toByte()), // Always preceded by 0x1a + PROGRAM_BOLUS(0x17.toByte()), // Always preceded by 0x1a PROGRAM_ALERTS(0x19.toByte()), - PROGRAM_INSULIN(0x1a.toByte()), // Always followed by one of: 0x13, 0x16, 0x17 + PROGRAM_INSULIN(0x1a.toByte()), // Always followed by one of: 0x13, 0x16, 0x17 DEACTIVATE(0x1c.toByte()), PROGRAM_BEEPS(0x1e.toByte()), STOP_DELIVERY(0x1f.toByte()); -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt index ef905673e9..5d943a777f 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/NonceEnabledCommand.kt @@ -6,4 +6,4 @@ abstract class NonceEnabledCommand protected constructor( sequenceNumber: Short, multiCommandFlag: Boolean, protected val nonce: Int -) : HeaderEnabledCommand(commandType, uniqueId, sequenceNumber, multiCommandFlag) \ No newline at end of file +) : HeaderEnabledCommand(commandType, uniqueId, sequenceNumber, multiCommandFlag) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt index 1798f08ca8..3e7aa921de 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/CommandBuilder.kt @@ -5,4 +5,4 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b interface CommandBuilder { fun build(): R -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt index f6fc7151b8..046d990b5e 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/HeaderEnabledCommandBuilder.kt @@ -31,4 +31,4 @@ abstract class HeaderEnabledCommandBuilder } protected abstract fun buildCommand(): R -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt index 04ee98a2d3..04e14ac856 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/base/builder/NonceEnabledCommandBuilder.kt @@ -15,4 +15,4 @@ abstract class NonceEnabledCommandBuilder, this.nonce = nonce return this as T } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt index cb700d64f2..8e9f2eabb9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt @@ -31,4 +31,4 @@ open class BasalInsulinProgramElement( ", delayBetweenTenthPulsesInUsec=" + delayBetweenTenthPulsesInUsec + '}' } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt index f30c4a8170..5d84e12ca3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalShortInsulinProgramElement.kt @@ -5,15 +5,17 @@ import kotlin.experimental.and class BasalShortInsulinProgramElement( private val numberOfSlots: Byte, // 4 bits - private val pulsesPerSlot: Short, //10 bits + private val pulsesPerSlot: Short, // 10 bits private val extraAlternatePulse: Boolean ) : ShortInsulinProgramElement { override val encoded: ByteArray get() { - val firstByte = (numberOfSlots - 1 and 0x0f shl 4 // - or ((if (extraAlternatePulse) 1 else 0) shl 3) // - or (pulsesPerSlot.toInt() ushr 8 and 0x03)).toByte() + val firstByte = ( + numberOfSlots - 1 and 0x0f shl 4 // + or ((if (extraAlternatePulse) 1 else 0) shl 3) // + or (pulsesPerSlot.toInt() ushr 8 and 0x03) + ).toByte() return ByteBuffer.allocate(2) // .put(firstByte) // .put((pulsesPerSlot and 0xff).toByte()) // @@ -27,4 +29,4 @@ class BasalShortInsulinProgramElement( ", extraAlternatePulse=" + extraAlternatePulse + '}' } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt index 6a2948404b..6527662b3c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BolusShortInsulinProgramElement.kt @@ -8,4 +8,4 @@ class BolusShortInsulinProgramElement( override val encoded: ByteArray get() = ByteBuffer.allocate(2).putShort(numberOfPulses).array() -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt index 04f27cf9bf..66d8efe3d7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentBasalInsulinProgramElement.kt @@ -13,4 +13,4 @@ class CurrentBasalInsulinProgramElement( ", delayUntilNextTenthPulseInUsec=" + delayUntilNextTenthPulseInUsec + ", remainingTenthPulses=" + remainingTenthPulses + '}' -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt index 49b2af59dc..077318299d 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/CurrentSlot.kt @@ -13,4 +13,4 @@ class CurrentSlot( ", eighthSecondsRemaining=" + eighthSecondsRemaining + ", pulsesRemaining=" + pulsesRemaining + '}' -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt index 2ff92c2c24..ac7e66a81a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/ShortInsulinProgramElement.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command. import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable import java.io.Serializable -interface ShortInsulinProgramElement : Encodable, Serializable \ No newline at end of file +interface ShortInsulinProgramElement : Encodable, Serializable diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt index 4c58755591..a1b5f9310b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/TempBasalInsulinProgramElement.kt @@ -21,4 +21,4 @@ class TempBasalInsulinProgramElement( } return buffer.array() } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt index 93b144787f..6c789796a0 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramBasalUtil.kt @@ -205,4 +205,4 @@ object ProgramBasalUtil { } return MessageUtil.calculateChecksum(buffer.array()) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt index 8c66abc626..3cdf5299ed 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/util/ProgramTempBasalUtil.kt @@ -59,4 +59,4 @@ object ProgramTempBasalUtil { fun mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot: ShortArray?): List = ProgramBasalUtil.mapPulsesPerSlotToShortInsulinProgramElements(pulsesPerSlot) -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt index f9455e5528..fc7f1f33fc 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ActivationProgress.kt @@ -18,4 +18,4 @@ enum class ActivationProgress { fun isBefore(other: ActivationProgress): Boolean = ordinal < other.ordinal fun isAtLeast(other: ActivationProgress): Boolean = ordinal >= other.ordinal -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt index 90f794a3cb..fdb6729124 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlarmType.kt @@ -159,5 +159,4 @@ enum class AlarmType(override val value: Byte) : HasValue { ALARM_BLE_QN_EXCEED_MAX_RETRY(0xc1.toByte()), ALARM_BLE_QN_CRIT_VAR_FAIL(0xc2.toByte()), UNKNOWN(0xff.toByte()); - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt index 4040ac5831..aab7cde138 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertConfiguration.kt @@ -29,15 +29,17 @@ class AlertConfiguration( return ByteBuffer.allocate(6) // .put(firstByte) .put(durationInMinutes.toByte()) // - .putShort(when (trigger) { - is AlertTrigger.ReservoirVolumeTrigger -> { - trigger.thresholdInMicroLiters - } + .putShort( + when (trigger) { + is AlertTrigger.ReservoirVolumeTrigger -> { + trigger.thresholdInMicroLiters + } - is AlertTrigger.TimerTrigger -> { - trigger.offsetInMinutes + is AlertTrigger.TimerTrigger -> { + trigger.offsetInMinutes + } } - }) // + ) // .put(beepRepetition.value) // .put(beepType.value) // .array() @@ -54,4 +56,4 @@ class AlertConfiguration( ", beepRepetition=" + beepRepetition + '}' } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt index 48df9b25bf..7c76903127 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertTrigger.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti sealed class AlertTrigger { class TimerTrigger(val offsetInMinutes: Short) : AlertTrigger() class ReservoirVolumeTrigger(val thresholdInMicroLiters: Short) : AlertTrigger() -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt index ec6d472066..8ee60d2568 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/AlertType.kt @@ -20,4 +20,4 @@ enum class AlertType(val index: Byte) : HasValue { } else { (1 shl index.toInt()).toByte() } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt index ef8f764f91..b003fba0d1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BasalProgram.kt @@ -87,4 +87,4 @@ class BasalProgram( override fun hashCode(): Int { return segments.hashCode() } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt index 402141e875..0668852456 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepRepetitionType.kt @@ -10,5 +10,4 @@ enum class BeepRepetitionType( XXX3(0x05.toByte()), // Used in user pod expiration alert XXX4(0x06.toByte()), // Used in pod expiration alert XXX5(0x08.toByte()); // Used in imminent pod expiration alert - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt index d997663b6f..ad41a53654 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/BeepType.kt @@ -5,4 +5,4 @@ enum class BeepType(val value: Byte) { SILENT(0x00.toByte()), FOUR_TIMES_BIP_BEEP(0x02.toByte()), // Used in low reservoir alert, user expiration alert, expiration alert, imminent expiration alert, lump of coal alert LONG_SINGLE_BEEP(0x06.toByte()); // Used in stop delivery command -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt index daaedab7db..db2a6b3710 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/DeliveryStatus.kt @@ -11,4 +11,4 @@ enum class DeliveryStatus(override val value: Byte) : HasValue { BOLUS_AND_BASAL_ACTIVE(0x05.toByte()), BOLUS_AND_TEMP_BASAL_ACTIVE(0x06.toByte()), UNKNOWN(0xff.toByte()); -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt index 28276e2abf..94f5798175 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/Encodable.kt @@ -3,4 +3,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definiti interface Encodable { val encoded: ByteArray -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt index e3f110e565..c700c11388 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/NakErrorType.kt @@ -34,4 +34,4 @@ enum class NakErrorType(override val value: Byte) : HasValue { IGNORE_COMMAND(0x1c.toByte()), INVALID_CRC(0x1d.toByte()), UNKNOWN(0xff.toByte()); -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt index b5d0dadacf..9dca9d1c57 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/PodStatus.kt @@ -23,4 +23,4 @@ enum class PodStatus(override val value: Byte) : HasValue { UNKNOWN(0xff.toByte()); fun isRunning(): Boolean = this == RUNNING_ABOVE_MIN_VOLUME || this == RUNNING_BELOW_MIN_VOLUME -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt index 09a63370f0..371f90d9e4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/definition/ProgramReminder.kt @@ -10,7 +10,11 @@ class ProgramReminder( ) : Encodable, Serializable { override val encoded: ByteArray - get() = byteArrayOf(((if (atStart) 1 else 0) shl 7 - or ((if (atEnd) 1 else 0) shl 6) - or ((atInterval and 0x3f).toInt())).toByte()) -} \ No newline at end of file + get() = byteArrayOf( + ( + (if (atStart) 1 else 0) shl 7 + or ((if (atEnd) 1 else 0) shl 6) + or ((atInterval and 0x3f).toInt()) + ).toByte() + ) +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt index 676bc85c07..d12ce055ea 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ActivationResponseBase.kt @@ -5,4 +5,4 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response. abstract class ActivationResponseBase( val activationResponseType: ActivationResponseType, encoded: ByteArray -) : ResponseBase(ResponseType.ACTIVATION_RESPONSE, encoded) \ No newline at end of file +) : ResponseBase(ResponseType.ACTIVATION_RESPONSE, encoded) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt index 0ce01d962d..501033468a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AdditionalStatusResponseBase.kt @@ -5,4 +5,4 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response. open class AdditionalStatusResponseBase internal constructor( val statusResponseType: StatusResponseType, encoded: ByteArray -) : ResponseBase(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded) \ No newline at end of file +) : ResponseBase(ResponseType.ADDITIONAL_STATUS_RESPONSE, encoded) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt index 847eaa903c..333af17c03 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponse.kt @@ -84,5 +84,4 @@ class AlarmStatusResponse( } infix fun Byte.shr(i: Int): Int = toInt() shr i - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt index fde2951b31..c0424c5822 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponse.kt @@ -34,7 +34,6 @@ class DefaultStatusResponse( ", minutesSinceActivation=$minutesSinceActivation" + ", reservoirPulsesRemaining=$reservoirPulsesRemaining)" } - } infix fun Byte.ushr(i: Int) = toInt() ushr i diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt index 0cde181a8d..f2a6cfb1cd 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponse.kt @@ -46,4 +46,4 @@ class NakResponse( ", encoded=" + encoded.contentToString() + '}' } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt index 0f1a0f06a0..f64cca766c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/Response.kt @@ -6,4 +6,4 @@ interface Response : Serializable { val responseType: ResponseType val encoded: ByteArray -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt index 1df5c6f988..9eacc0d1ef 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseBase.kt @@ -6,5 +6,4 @@ abstract class ResponseBase( ) : Response { override val encoded: ByteArray = encoded.copyOf(encoded.size) - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt index 10d355f380..283a1cd284 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/ResponseType.kt @@ -30,4 +30,4 @@ enum class ResponseType(override val value: Byte) : HasValue { SET_UNIQUE_ID_RESPONSE(0x1b.toByte()), UNKNOWN(0xff.toByte()); } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt index e91b750a6a..f0153ef5e7 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt @@ -55,5 +55,4 @@ class SetUniqueIdResponse( ", encoded=" + encoded.contentToString() + '}' } - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt index 243c191efb..59165eb0f4 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponse.kt @@ -49,5 +49,4 @@ class VersionResponse( ", encoded=" + Arrays.toString(encoded) + '}' } - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt index a97cad8974..8270e1cd18 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManager.kt @@ -53,4 +53,4 @@ interface OmnipodDashPodStateManager { fun reset() data class TempBasal(val startTime: Long, val rate: Double, val durationInMinutes: Short) : Serializable -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt index 78254c74e8..fb528cc1ec 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/state/OmnipodDashPodStateManagerImpl.kt @@ -261,4 +261,4 @@ class OmnipodDashPodStateManagerImpl @Inject constructor( var basalProgram: BasalProgram? = null var tempBasal: OmnipodDashPodStateManager.TempBasal? = null } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt index 4a63fd91fa..9d5db05579 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt @@ -20,9 +20,10 @@ object AlertUtil { } fun encodeAlertSet(alertSet: EnumSet): Byte = - alertSet.fold(0, + alertSet.fold( + 0, { out, slot -> out or (slot.value.toInt() and 0xff) } ).toByte() -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt index 3794ddf850..0976efd028 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/HasValue.kt @@ -7,4 +7,4 @@ interface HasValue { inline fun byValue(value: Byte, default: T): T where T : Enum, T : HasValue { return enumValues().firstOrNull { it.value == value } ?: default -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt index b9ff49d4b3..5699d004be 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/MessageUtil.kt @@ -42,4 +42,4 @@ object MessageUtil { } return sum } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt index b5c1c5367d..d8c9bf36c1 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt @@ -38,22 +38,24 @@ class DashHistory @Inject constructor( val id = ULID.random() when { - commandType == SET_BOLUS && bolusRecord == null -> + commandType == SET_BOLUS && bolusRecord == null -> return Single.error(IllegalArgumentException("bolusRecord missing on SET_BOLUS")) commandType == SET_TEMPORARY_BASAL && tempBasalRecord == null -> return Single.error(IllegalArgumentException("tempBasalRecord missing on SET_TEMPORARY_BASAL")) } - return dao.save(HistoryRecordEntity( - id = id, - date = date, - createdAt = currentTimeMillis(), - commandType = commandType, - tempBasalRecord = tempBasalRecord, - bolusRecord = bolusRecord, - initialResult = initialResult, - resolvedResult = resolveResult, - resolvedAt = resolvedAt) + return dao.save( + HistoryRecordEntity( + id = id, + date = date, + createdAt = currentTimeMillis(), + commandType = commandType, + tempBasalRecord = tempBasalRecord, + bolusRecord = bolusRecord, + initialResult = initialResult, + resolvedResult = resolveResult, + resolvedAt = resolvedAt + ) ).toSingle { id } } @@ -61,5 +63,4 @@ class DashHistory @Inject constructor( dao.all().map { list -> list.map(historyMapper::entityToDomain) } fun getRecordsAfter(time: Long): Single> = dao.allSince(time) - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt index 6344c9fcd7..a4f636c497 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/Record.kt @@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data sealed class Record -data class BolusRecord(val amout: Double, val bolusType: BolusType): Record() +data class BolusRecord(val amout: Double, val bolusType: BolusType) : Record() -data class TempBasalRecord(val duration: Long, val rate: Double): Record() +data class TempBasalRecord(val duration: Long, val rate: Double) : Record() enum class BolusType { DEFAULT, SMB -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt index 53dc608e60..8f0c353763 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/data/ResultStates.kt @@ -6,4 +6,4 @@ enum class InitialResult { enum class ResolvedResult { SUCCESS, FAILURE -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt index 2395695f1e..8d21ea751a 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/Converters.kt @@ -31,4 +31,4 @@ class Converters { @TypeConverter fun fromOmnipodCommandType(omnipodCommandType: OmnipodCommandType) = omnipodCommandType.name -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt index 75b21716ba..c018328a9b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/DashHistoryDatabase.kt @@ -5,7 +5,6 @@ import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters -import androidx.room.migration.Migration @Database( entities = [HistoryRecordEntity::class], @@ -15,7 +14,7 @@ import androidx.room.migration.Migration @TypeConverters(Converters::class) abstract class DashHistoryDatabase : RoomDatabase() { - abstract fun historyRecordDao() : HistoryRecordDao + abstract fun historyRecordDao(): HistoryRecordDao companion object { @@ -26,5 +25,4 @@ abstract class DashHistoryDatabase : RoomDatabase() { .fallbackToDestructiveMigration() .build() } - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt index e5c425dd24..93b292c067 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordDao.kt @@ -32,5 +32,4 @@ abstract class HistoryRecordDao { @Query("UPDATE historyrecords SET resolvedResult = :resolvedResult, resolvedAt = :resolvedAt WHERE id = :id ") abstract fun markResolved(id: String, resolvedResult: ResolvedResult, resolvedAt: Long): Completable - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt index 4eea309c5a..18ff9c14d2 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/database/HistoryRecordEntity.kt @@ -19,5 +19,5 @@ data class HistoryRecordEntity( @Embedded(prefix = "tempBasalRecord_") val tempBasalRecord: TempBasalRecord?, @Embedded(prefix = "bolusRecord_") val bolusRecord: BolusRecord?, val resolvedResult: ResolvedResult?, - val resolvedAt: Long?) - + val resolvedAt: Long? +) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt index e3eeb39320..57df60dfa3 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt @@ -21,7 +21,8 @@ class HistoryMapper { ) fun entityToDomain(entity: HistoryRecordEntity): HistoryRecord = - HistoryRecord(id = entity.id, + HistoryRecord( + id = entity.id, createdAt = entity.createdAt, date = entity.date, initialResult = entity.initialResult, @@ -30,5 +31,4 @@ class HistoryMapper { resolvedResult = entity.resolvedResult, resolvedAt = entity.resolvedAt ) - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt index 26aa52b5df..86ec8ff628 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/DashPodManagementActivity.kt @@ -66,10 +66,13 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { } binding.buttonDiscardPod.setOnClickListener { - OKDialog.showConfirmation(this, - resourceHelper.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), Thread { - // TODO discard Pod - }) + OKDialog.showConfirmation( + this, + resourceHelper.gs(R.string.omnipod_common_pod_management_discard_pod_confirmation), + Thread { + // TODO discard Pod + } + ) } binding.buttonPlayTestBeep.setOnClickListener { @@ -77,13 +80,16 @@ class DashPodManagementActivity : NoSplashAppCompatActivity() { binding.buttonPlayTestBeep.isEnabled = false binding.buttonPlayTestBeep.setText(R.string.omnipod_common_pod_management_button_playing_test_beep) - commandQueue.customCommand(CommandPlayTestBeep(), object : Callback() { - override fun run() { - if (!result.success) { - displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, resourceHelper.gs(R.string.omnipod_common_error_failed_to_play_test_beep), result.comment), false) + commandQueue.customCommand( + CommandPlayTestBeep(), + object : Callback() { + override fun run() { + if (!result.success) { + displayErrorDialog(resourceHelper.gs(R.string.omnipod_common_warning), resourceHelper.gs(R.string.omnipod_common_two_strings_concatenated_by_colon, resourceHelper.gs(R.string.omnipod_common_error_failed_to_play_test_beep), result.comment), false) + } } } - }) + ) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt index 223547e68a..6e4c959799 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt @@ -107,38 +107,47 @@ class OmnipodDashOverviewFragment : DaggerFragment() { buttonBinding.buttonResumeDelivery.setOnClickListener { disablePodActionButtons() - commandQueue.customCommand(CommandResumeDelivery(), - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_delivery_resumed))) + commandQueue.customCommand( + CommandResumeDelivery(), + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_resume_delivery), true).messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_delivery_resumed)) + ) } buttonBinding.buttonRefreshStatus.setOnClickListener { disablePodActionButtons() - commandQueue.readStatus("REQUESTED BY USER", - DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_refresh_status), false)) + commandQueue.readStatus( + "REQUESTED BY USER", + DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_refresh_status), false) + ) } buttonBinding.buttonSilenceAlerts.setOnClickListener { disablePodActionButtons() - commandQueue.customCommand(CommandAcknowledgeAlerts(), + commandQueue.customCommand( + CommandAcknowledgeAlerts(), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_silence_alerts), false) .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_silenced_alerts)) - .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) }) + .actionOnSuccess { rxBus.send(EventDismissNotification(Notification.OMNIPOD_POD_ALERTS)) } + ) } buttonBinding.buttonSuspendDelivery.setOnClickListener { disablePodActionButtons() - commandQueue.customCommand(CommandSuspendDelivery(), + commandQueue.customCommand( + CommandSuspendDelivery(), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_suspend_delivery), true) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_suspended_delivery))) + .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_suspended_delivery)) + ) } buttonBinding.buttonSetTime.setOnClickListener { disablePodActionButtons() - commandQueue.customCommand(CommandHandleTimeChange(true), + commandQueue.customCommand( + CommandHandleTimeChange(true), DisplayResultDialogCallback(resourceHelper.gs(R.string.omnipod_common_error_failed_to_set_time), true) - .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_time_on_pod_updated))) + .messageOnSuccess(resourceHelper.gs(R.string.omnipod_common_confirmation_time_on_pod_updated)) + ) } - } override fun onResume() { @@ -147,23 +156,32 @@ class OmnipodDashOverviewFragment : DaggerFragment() { disposables += rxBus .toObservable(EventOmnipodDashPumpValuesChanged::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ - updateOmnipodStatus() - updatePodActionButtons() - }, fabricPrivacy::logException) + .subscribe( + { + updateOmnipodStatus() + updatePodActionButtons() + }, + fabricPrivacy::logException + ) disposables += rxBus .toObservable(EventQueueChanged::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ - updateQueueStatus() - updatePodActionButtons() - }, fabricPrivacy::logException) + .subscribe( + { + updateQueueStatus() + updatePodActionButtons() + }, + fabricPrivacy::logException + ) disposables += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(aapsSchedulers.main) - .subscribe({ - updatePodActionButtons() - }, fabricPrivacy::logException) + .subscribe( + { + updatePodActionButtons() + }, + fabricPrivacy::logException + ) updateUi() } @@ -267,16 +285,18 @@ class OmnipodDashOverviewFragment : DaggerFragment() { podInfoBinding.reservoir.setTextColor(Color.WHITE) } else { // TODO - //val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits + // val lowReservoirThreshold = (omnipodAlertUtil.lowReservoirAlertUnits // ?: OmnipodConstants.DEFAULT_MAX_RESERVOIR_ALERT_THRESHOLD).toDouble() val lowReservoirThreshold: Short = 20 podInfoBinding.reservoir.text = resourceHelper.gs(R.string.omnipod_common_overview_reservoir_value, podStateManager.pulsesRemaining) - podInfoBinding.reservoir.setTextColor(if (podStateManager.pulsesRemaining!! < lowReservoirThreshold) { - Color.RED - } else { - Color.WHITE - }) + podInfoBinding.reservoir.setTextColor( + if (podStateManager.pulsesRemaining!! < lowReservoirThreshold) { + Color.RED + } else { + Color.WHITE + } + ) } podInfoBinding.podActiveAlerts.text = if (podStateManager.activeAlerts!!.size > 0) { @@ -345,7 +365,7 @@ class OmnipodDashOverviewFragment : DaggerFragment() { } } - val podStatusColor = if (!podStateManager.isActivationCompleted ||/* TODO podStateManager.isPodDead || */ podStateManager.isSuspended) { + val podStatusColor = if (!podStateManager.isActivationCompleted || /* TODO podStateManager.isPodDead || */ podStateManager.isSuspended) { Color.RED } else { Color.WHITE @@ -417,8 +437,8 @@ class OmnipodDashOverviewFragment : DaggerFragment() { } private fun updateRefreshStatusButton() { - buttonBinding.buttonRefreshStatus.isEnabled = podStateManager.isUniqueIdSet && podStateManager.activationProgress.isAtLeast(ActivationProgress.PHASE_1_COMPLETED) - && isQueueEmpty() + buttonBinding.buttonRefreshStatus.isEnabled = podStateManager.isUniqueIdSet && podStateManager.activationProgress.isAtLeast(ActivationProgress.PHASE_1_COMPLETED) && + isQueueEmpty() } private fun updateResumeDeliveryButton() { @@ -576,5 +596,4 @@ class OmnipodDashOverviewFragment : DaggerFragment() { return this } } - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt index 6f87bfd8f6..ad340053bf 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/DashPodActivationWizardActivity.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.activatio import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.activation.PodActivationWizardActivity -class DashPodActivationWizardActivity : PodActivationWizardActivity() \ No newline at end of file +class DashPodActivationWizardActivity : PodActivationWizardActivity() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt index fc6c428ca2..1ed9dd45fe 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -51,4 +51,4 @@ class DashInsertCannulaViewModel @Inject constructor( @StringRes override fun getTextId() = R.string.omnipod_common_pod_activation_wizard_insert_cannula_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt index dfad36eb91..36b00e5738 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashAttachPodViewModel.kt @@ -12,4 +12,4 @@ class DashAttachPodViewModel @Inject constructor() : AttachPodViewModel() { @StringRes override fun getTextId() = R.string.omnipod_common_pod_activation_wizard_attach_pod_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt index 88721268a9..de6d558662 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashPodActivatedViewModel.kt @@ -12,4 +12,4 @@ class DashPodActivatedViewModel @Inject constructor() : PodActivatedViewModel() @StringRes override fun getTextId() = R.string.omnipod_common_pod_activation_wizard_pod_activated_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt index 0e7538b621..1bb7ae1a22 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/info/DashStartPodActivationViewModel.kt @@ -12,4 +12,4 @@ class DashStartPodActivationViewModel @Inject constructor() : StartPodActivation @StringRes override fun getTextId(): Int = R.string.omnipod_dash_pod_activation_wizard_start_pod_activation_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt index 0a45f38be8..adce6f5806 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/DashPodDeactivationWizardActivity.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.ui.wizard.deactivat import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.deactivation.PodDeactivationWizardActivity -class DashPodDeactivationWizardActivity : PodDeactivationWizardActivity() \ No newline at end of file +class DashPodDeactivationWizardActivity : PodDeactivationWizardActivity() diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt index 8d7c393cf4..cc2e867599 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/action/DashDeactivatePodViewModel.kt @@ -25,4 +25,4 @@ class DashDeactivatePodViewModel @Inject constructor( @StringRes override fun getTextId(): Int = R.string.omnipod_common_pod_deactivation_wizard_deactivating_pod_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt index 3496076606..a848db0bd6 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDeactivatedViewModel.kt @@ -12,5 +12,4 @@ class DashPodDeactivatedViewModel @Inject constructor() : PodDeactivatedViewMode @StringRes override fun getTextId() = R.string.omnipod_common_pod_deactivation_wizard_pod_deactivated_text - -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt index 27fb8fd625..a7cce31cce 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashPodDiscardedViewModel.kt @@ -12,4 +12,4 @@ class DashPodDiscardedViewModel @Inject constructor() : PodDiscardedViewModel() @StringRes override fun getTextId() = R.string.omnipod_common_pod_deactivation_wizard_pod_discarded_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt index 099ce1f53c..1f929af9ae 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/deactivation/viewmodel/info/DashStartPodDeactivationViewModel.kt @@ -12,4 +12,4 @@ class DashStartPodDeactivationViewModel @Inject constructor() : StartPodDeactiva @StringRes override fun getTextId() = R.string.omnipod_common_pod_deactivation_wizard_start_pod_deactivation_text -} \ No newline at end of file +} diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt index 54ad9b345f..baa0ecf7c9 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/Functions.kt @@ -60,4 +60,4 @@ fun mapProfileToBasalProgram(profile: Profile): BasalProgram { ) return BasalProgram(entries) -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt index 55dc2ff96e..45cb0d9d97 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/DeactivateCommandTest.kt @@ -17,4 +17,4 @@ class DeactivateCommandTest { Assert.assertArrayEquals(Hex.decodeHex("0242000114061C04494E532E001C"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt index 4a73a9ebb4..e0ab87267d 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetStatusCommandTest.kt @@ -18,4 +18,4 @@ class GetStatusCommandTest { Assert.assertArrayEquals(Hex.decodeHex("024200023C030E0100024C"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt index c092142361..9c4e963df8 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/GetVersionCommandTest.kt @@ -16,4 +16,4 @@ class GetVersionCommandTest { Assert.assertArrayEquals(Hex.decodeHex("FFFFFFFF00060704FFFFFFFF82B2"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt index 63c5063c0e..b3bb3ba60d 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramAlertsCommandTest.kt @@ -1,8 +1,8 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertConfiguration -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertTrigger +import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepRepetitionType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.BeepType import org.apache.commons.codec.DecoderException @@ -75,4 +75,4 @@ class ProgramAlertsCommandTest { Assert.assertArrayEquals(Hex.decodeHex("02420003280C190A494E532E7837000508020356"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt index ce33402475..93fba68a72 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBasalCommandTest.kt @@ -29,4 +29,4 @@ class ProgramBasalCommandTest { Assert.assertArrayEquals(Hex.decodeHex("0242000128241A12494E532E0005E81D1708000CF01EF01EF01E130E40001593004C4B403840005B8D80827C"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt index cd5d06c451..8030767ab9 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBeepsCommandTest.kt @@ -22,4 +22,4 @@ class ProgramBeepsCommandTest { Assert.assertArrayEquals(Hex.decodeHex("024200022C061E0402000000800F"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt index ce9ea9c24e..daface569f 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramBolusCommandTest.kt @@ -21,4 +21,4 @@ class ProgramBolusCommandTest { Assert.assertArrayEquals(Hex.decodeHex("02420001381F1A0E494E532E02010F01064000640064170D4003E800030D4000000000000080F6"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt index f7875cf2b4..e4f8079b24 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/ProgramTempBasalCommandTest.kt @@ -33,4 +33,4 @@ class ProgramTempBasalCommandTest { Assert.assertArrayEquals(Hex.decodeHex("024200011C201A0E494E532E0100820A384000009000160EC000000A6B49D200000AEB49D20001DE"), command.encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt index 4dda5f9a38..f98387cdbb 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SetUniqueIdCommandTest.kt @@ -20,4 +20,4 @@ class SetUniqueIdCommandTest { Assert.assertArrayEquals(Hex.decodeHex("FFFFFFFF18150313024200031404020A150E2908146CC1000A67278344"), encoded) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt index 0f9c267578..63bf3e18cb 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/SilenceAlertsCommandTest.kt @@ -22,4 +22,4 @@ class SilenceAlertsCommandTest { } // TODO capture more silence alerts commands -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt index a9463e1785..ffa5737246 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/StopDeliveryCommandTest.kt @@ -35,4 +35,4 @@ class StopDeliveryCommandTest { } // TODO test cancel bolus -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt index 06e6337afd..c57fb20a82 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/AlarmStatusResponseTest.kt @@ -41,4 +41,4 @@ class AlarmStatusResponseTest { Assert.assertEquals(PodStatus.UNINITIALIZED, response.podStatusWhenAlarmOccurred2) Assert.assertEquals(26378.toShort(), response.returnAddressOfPodAlarmHandlerCaller) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt index f925642d38..f24e02e87c 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/DefaultStatusResponseTest.kt @@ -25,4 +25,4 @@ class DefaultStatusResponseTest { Assert.assertEquals(280.toShort(), response.minutesSinceActivation) Assert.assertEquals(1023.toShort(), response.reservoirPulsesRemaining) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt index 206ac491aa..b5254eca1d 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/NakResponseTest.kt @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlarmType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.NakErrorType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus -import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType import org.apache.commons.codec.DecoderException import org.apache.commons.codec.binary.Hex import org.junit.Assert @@ -24,4 +23,4 @@ class NakResponseTest { Assert.assertEquals(PodStatus.RUNNING_BELOW_MIN_VOLUME, response.podStatus) Assert.assertEquals(0x00.toShort(), response.securityNakSyncCount) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt index 6f627c5d80..311be2c08b 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponseTest.kt @@ -36,4 +36,4 @@ class SetUniqueIdResponseTest { Assert.assertEquals(611540L, response.podSequenceNumber) Assert.assertEquals(37879809L, response.uniqueIdReceivedInCommand) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt index 2ae37834d1..58e3585cae 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/VersionResponseTest.kt @@ -32,4 +32,4 @@ class VersionResponseTest { Assert.assertEquals(0.toByte(), response.receiverLowerGain) Assert.assertEquals(4294967295L, response.uniqueIdReceivedInCommand) } -} \ No newline at end of file +} diff --git a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt index a046e21e17..0febb3f35a 100644 --- a/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt +++ b/omnipod-dash/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/FunctionsTest.kt @@ -26,11 +26,13 @@ class FunctionsTest { val value3 = Mockito.mock(ProfileValue::class.java) value3.timeAsSeconds = 50400 value3.value = 3.05 - PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( - value1, - value2, - value3 - )) + PowerMockito.`when`(profile.basalValues).thenReturn( + arrayOf( + value1, + value2, + value3 + ) + ) val basalProgram: BasalProgram = mapProfileToBasalProgram(profile) val entries: List = basalProgram.segments assertEquals(3, entries.size) @@ -69,8 +71,11 @@ class FunctionsTest { val value = Mockito.mock(ProfileValue::class.java) value.timeAsSeconds = 1800 value.value = 0.5 - PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( - value)) + PowerMockito.`when`(profile.basalValues).thenReturn( + arrayOf( + value + ) + ) mapProfileToBasalProgram(profile) } @@ -85,10 +90,12 @@ class FunctionsTest { val value2 = Mockito.mock(ProfileValue::class.java) value2.timeAsSeconds = 86400 value2.value = 0.5 - PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( - value1, - value2 - )) + PowerMockito.`when`(profile.basalValues).thenReturn( + arrayOf( + value1, + value2 + ) + ) mapProfileToBasalProgram(profile) } @@ -99,8 +106,11 @@ class FunctionsTest { val value = Mockito.mock(ProfileValue::class.java) value.timeAsSeconds = -1 value.value = 0.5 - PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( - value)) + PowerMockito.`when`(profile.basalValues).thenReturn( + arrayOf( + value + ) + ) mapProfileToBasalProgram(profile) } @@ -109,10 +119,13 @@ class FunctionsTest { val value = Mockito.mock(ProfileValue::class.java) value.timeAsSeconds = 0 value.value = 0.04 - PowerMockito.`when`(profile.basalValues).thenReturn(arrayOf( - value)) + PowerMockito.`when`(profile.basalValues).thenReturn( + arrayOf( + value + ) + ) val basalProgram: BasalProgram = mapProfileToBasalProgram(profile) val basalProgramElement: BasalProgram.Segment = basalProgram.segments[0] assertEquals(5, basalProgramElement.basalRateInHundredthUnitsPerHour) } -} \ No newline at end of file +} From e7b3d85639ca92d85fc6aa2a8f00d0232d2a0290 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 1 Mar 2021 13:49:39 +0100 Subject: [PATCH 079/649] detekt resolve a few --- omnipod-dash/detekt-config.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/omnipod-dash/detekt-config.yml b/omnipod-dash/detekt-config.yml index 60e3fee286..850cd898e5 100644 --- a/omnipod-dash/detekt-config.yml +++ b/omnipod-dash/detekt-config.yml @@ -567,7 +567,8 @@ style: maxJumpCount: 1 MagicNumber: active: true - excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**'] + # TODO: re-enable omnipod-dash + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/jsTest/**', '**/iosTest/**', '**/omnipod-dash/**'] ignoreNumbers: ['-1', '0', '1', '2'] ignoreHashCodeFunction: true ignorePropertyDeclaration: false From 5ef07dd0beea8845d8a76b312f23c11101db230b Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 1 Mar 2021 13:52:43 +0100 Subject: [PATCH 080/649] detekt resolve a few more --- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 1 + .../dash/driver/comm/pair/LTKExchanger.kt | 22 +++++++++---------- .../pump/omnipod/dash/history/DashHistory.kt | 1 + 3 files changed, 13 insertions(+), 11 deletions(-) diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt index de2125a2b5..dbfc1ff344 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/io/BleIO.kt @@ -1,3 +1,4 @@ +@file:Suppress("WildcardImport") package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io import android.bluetooth.BluetoothGatt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt index a6cc8b3bb5..d43b8e0479 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/comm/pair/LTKExchanger.kt @@ -225,24 +225,24 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI companion object { - private val PUBLIC_KEY_SIZE = 32 - private val NONCE_SIZE = 16 - private val CONF_SIZE = 16 + private const val PUBLIC_KEY_SIZE = 32 + private const val NONCE_SIZE = 16 + private const val CONF_SIZE = 16 - private val CMAC_SIZE = 16 + private const val CMAC_SIZE = 16 private val INTERMEDIAR_KEY_MAGIC_STRING = "TWIt".toByteArray() private val PDM_CONF_MAGIC_PREFIX = "KC_2_U".toByteArray() private val POD_CONF_MAGIC_PREFIX = "KC_2_V".toByteArray() - private val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. + private const val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that. - private val SP1 = "SP1=" - private val SP2 = ",SP2=" - private val SPS1 = "SPS1=" - private val SPS2 = "SPS2=" - private val SP0GP0 = "SP0,GP0" - private val P0 = "P0=" + private const val SP1 = "SP1=" + private const val SP2 = ",SP2=" + private const val SPS1 = "SPS1=" + private const val SPS2 = "SPS2=" + private const val SP0GP0 = "SP0,GP0" + private const val P0 = "P0=" private val UNKNOWN_P0_PAYLOAD = byteArrayOf(0xa5.toByte()) } } diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt index d8c9bf36c1..81cfa6475c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/DashHistory.kt @@ -26,6 +26,7 @@ class DashHistory @Inject constructor( fun markFailure(id: String, date: Long): Completable = dao.markResolved(id, ResolvedResult.FAILURE, currentTimeMillis()) + @Suppress("ReturnCount") fun createRecord( commandType: OmnipodCommandType, date: Long, From 89ff502518e8878e2989e8d3a4b76e6d0c870853 Mon Sep 17 00:00:00 2001 From: AdrianLxM Date: Mon, 1 Mar 2021 14:35:50 +0100 Subject: [PATCH 081/649] a bit more formatting --- .idea/codeStyles/Project.xml | 17 +- omnipod-dash/detekt-config.yml | 2 +- .../omnipod/dash/OmnipodDashPumpPlugin.kt | 26 +- .../dash/dagger/OmnipodDashHistoryModule.kt | 3 +- .../dash/driver/OmnipodDashManagerImpl.kt | 30 +- .../driver/comm/OmnipodDashBleManagerImpl.kt | 38 ++- .../dash/driver/comm/ServiceDiscoverer.kt | 6 +- .../driver/comm/callbacks/BleCommCallbacks.kt | 31 ++- .../driver/comm/command/BleCommandType.kt | 10 +- .../CouldNotConfirmWriteException.kt | 6 +- .../pump/omnipod/dash/driver/comm/io/BleIO.kt | 25 +- .../comm/message/IncorrectPacketException.kt | 5 +- .../dash/driver/comm/message/MessagePacket.kt | 3 +- .../dash/driver/comm/message/PayloadJoiner.kt | 24 +- .../driver/comm/message/PayloadSplitter.kt | 23 +- .../message/StringLengthPrefixEncoding.kt | 6 +- .../dash/driver/comm/packet/BlePacket.kt | 13 +- .../dash/driver/comm/pair/LTKExchanger.kt | 8 +- .../driver/comm/scan/BleDiscoveredDevice.kt | 16 +- .../driver/pod/command/DeactivateCommand.kt | 7 +- .../driver/pod/command/ProgramBasalCommand.kt | 33 ++- .../driver/pod/command/ProgramBeepsCommand.kt | 10 +- .../driver/pod/command/ProgramBolusCommand.kt | 29 +- .../pod/command/ProgramInsulinCommand.kt | 2 +- .../pod/command/ProgramTempBasalCommand.kt | 50 +++- .../driver/pod/command/SetUniqueIdCommand.kt | 9 +- .../driver/pod/command/StopDeliveryCommand.kt | 16 +- .../pod/command/base/HeaderEnabledCommand.kt | 7 +- .../insulin/program/util/ProgramBasalUtil.kt | 73 ++++- .../program/util/ProgramTempBasalUtil.kt | 8 +- .../pod/definition/AlertConfiguration.kt | 2 +- .../pod/response/DefaultStatusResponse.kt | 9 +- .../pod/response/SetUniqueIdResponse.kt | 39 ++- .../driver/pod/response/VersionResponse.kt | 39 ++- .../state/OmnipodDashPodStateManagerImpl.kt | 34 ++- .../dash/driver/pod/util/MessageUtil.kt | 259 +++++++++++++++++- .../pump/omnipod/dash/history/DashHistory.kt | 14 +- .../history/database/DashHistoryDatabase.kt | 6 +- .../dash/ui/DashPodManagementActivity.kt | 10 +- .../dash/ui/OmnipodDashOverviewFragment.kt | 114 ++++++-- .../action/DashInitializePodViewModel.kt | 7 +- .../action/DashInsertCannulaViewModel.kt | 7 +- .../action/DashDeactivatePodViewModel.kt | 4 +- 43 files changed, 927 insertions(+), 153 deletions(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 3542887fac..3a7ab749b3 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -22,6 +22,7 @@