Merge branch 'dev' into carbs-required

This commit is contained in:
Milos Kozak 2020-05-12 17:01:29 +02:00 committed by GitHub
commit 65982ab94a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
805 changed files with 12827 additions and 14629 deletions

1
.gitignore vendored
View file

@ -8,7 +8,6 @@
build/
.idea/*
!.idea/codeStyles/
app/src/main/jniLibs
full/
debug/
release/

View file

@ -124,11 +124,11 @@ android {
ndkVersion "21.1.6352462"
defaultConfig {
minSdkVersion 23
minSdkVersion 24
targetSdkVersion 28
multiDexEnabled true
versionCode 1500
version "2.6.5-dev"
version "2.6.6-dev"
buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
@ -242,6 +242,9 @@ dependencies {
wearApp project(':wear')
implementation project(':core')
implementation project(':dana')
implementation project(':danars')
implementation project(':danar')
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.google.android.gms:play-services-wearable:17.0.0'
@ -266,7 +269,6 @@ dependencies {
implementation "androidx.activity:activity-ktx:${activityVersion}"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.wdullaer:materialdatetimepicker:4.2.3'
implementation "io.reactivex.rxjava2:rxandroid:2.1.1"
@ -355,30 +357,6 @@ dependencies {
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}
task downloadZipFile(type: Download) {
src 'https://github.com/MilosKozak/danars-support-lib/archive/master.zip'
dest new File(buildDir, 'danars.zip')
}
task downloadAndUnzipFile(dependsOn: downloadZipFile, type: Copy) {
from zipTree(downloadZipFile.dest)
def outputDir = file("${buildDir}/unpacked/dist")
into outputDir
}
task copyLibs(dependsOn: downloadAndUnzipFile, type: Copy) {
def src = file("${buildDir}/unpacked/dist/danars-support-lib-master")
def target = file("src/main/jniLibs/")
from src
into target
}
task full_clean(type: Delete) {
delete file("src/main/jniLibs")
}
/*
// Run 'adb' shell command to clear application data of main app for 'debug' variant
task clearMainAppData(type: Exec) {
@ -410,8 +388,6 @@ tasks.whenTaskAdded { task ->
}
}
*/
clean.dependsOn full_clean
preBuild.dependsOn copyLibs
printf('--------------\n')
printf('isMaster: %s\n', isMaster().toString())

View file

@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugi
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin
import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
import info.nightscout.androidaps.plugins.source.RandomBgPlugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
@ -42,7 +42,7 @@ class RealPumpTest {
private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}"
@Inject lateinit var pump : DanaRv2Plugin
@Inject lateinit var pump : info.nightscout.androidaps.danaRv2.DanaRv2Plugin
@Inject lateinit var randomBgPlugin :RandomBgPlugin
@Inject lateinit var localProfilePlugin: LocalProfilePlugin
@Inject lateinit var profileFunction: ProfileFunction

View file

@ -58,15 +58,6 @@
</intent-filter>
</activity>
<activity android:name=".activities.PreferencesActivity" />
<activity
android:name=".activities.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity
android:name=".activities.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".plugins.pump.danaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.pump.danaR.activities.DanaRUserOptionsActivity" />
<activity android:name=".activities.TDDStatsActivity" />
<activity android:name=".plugins.general.overview.activities.QuickWizardListActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity" />
@ -74,14 +65,6 @@
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".plugins.pump.danaRS.activities.BLEScanActivity">
<intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpDanaRS.activities.BLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".plugins.pump.danaRS.activities.PairingHelperActivity" />
<activity android:name=".plugins.general.maintenance.activities.PrefImportListActivity" />
<activity android:name=".historyBrowser.HistoryBrowseActivity" />
<activity android:name=".activities.SurveyActivity" />
@ -152,22 +135,6 @@
<service
android:name=".services.LocationService"
android:exported="false" />
<service
android:name=".plugins.pump.danaR.services.DanaRExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.pump.danaRKorean.services.DanaRKoreanExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.pump.danaRv2.services.DanaRv2ExecutionService"
android:enabled="true"
android:exported="false" />
<service
android:name=".plugins.pump.danaRS.services.DanaRSService"
android:enabled="true"
android:exported="true" />
<service
android:name=".plugins.general.wear.wearintegration.WatchUpdaterService"
android:exported="true">

View file

@ -7,26 +7,21 @@ import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import androidx.annotation.StringRes;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import net.danlew.android.joda.JodaTimeAndroid;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DaggerApplication;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.StaticInjector;
import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
@ -45,7 +40,7 @@ import info.nightscout.androidaps.utils.ActivityMonitor;
import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class MainApp extends DaggerApplication implements DatabaseHelperInterface {
public class MainApp extends DaggerApplication {
static MainApp sInstance;
private static Resources sResources;
@ -57,12 +52,13 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac
@Inject ActivityMonitor activityMonitor;
@Inject VersionCheckerUtils versionCheckersUtils;
@Inject SP sp;
@Inject NSUpload nsUpload;
@Inject ConfigBuilderPlugin configBuilderPlugin;
@Inject KeepAliveReceiver.KeepAliveManager keepAliveManager;
@Inject List<PluginBase> plugins;
@Inject StaticInjector staticInjector; // TODO remove , fake only to initialize
@Inject StaticInjector staticInjector; // TODO avoid , here fake only to initialize
@Override
public void onCreate() {
@ -99,7 +95,7 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac
pluginStore.setPlugins(plugins);
configBuilderPlugin.initialize();
NSUpload.uploadAppStart();
nsUpload.uploadAppStart();
new Thread(() -> keepAliveManager.setAlarm(this)).start();
doMigrations();
@ -107,7 +103,6 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac
private void doMigrations() {
}
@Override
@ -118,6 +113,7 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac
.build();
}
@SuppressWarnings("deprecation")
private void registerLocalBroadcastReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(Intents.ACTION_NEW_TREATMENT);
@ -152,16 +148,6 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac
registerReceiver(new BTReceiver(), filter);
}
@Deprecated
public static String gs(@StringRes int id) {
return sResources.getString(id);
}
@Deprecated
public static MainApp instance() {
return sInstance;
}
public static DatabaseHelper getDbHelper() {
return sDatabaseHelper;
}
@ -173,8 +159,4 @@ public class MainApp extends DaggerApplication implements DatabaseHelperInterfac
keepAliveManager.cancelAlarm(this);
super.onTerminate();
}
@NotNull @Override public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
return getDbHelper().getAllBgreadingsDataFromTime(mills, ascending);
}
}

View file

@ -25,7 +25,6 @@ import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
@ -35,13 +34,12 @@ import info.nightscout.androidaps.plugins.general.wear.WearPlugin
import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin
import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin
import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
@ -74,7 +72,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin
@Inject lateinit var danaRv2Plugin: DanaRv2Plugin
@Inject lateinit var danaRSPlugin: DanaRSPlugin
@Inject lateinit var careportalPlugin: CareportalPlugin
@Inject lateinit var comboPlugin: ComboPlugin
@Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin
@Inject lateinit var loopPlugin: LoopPlugin
@ -162,7 +159,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
addPreferencesFromResourceIfEnabled(tomatoPlugin, rootKey)
addPreferencesFromResourceIfEnabled(poctechPlugin, rootKey)
addPreferencesFromResourceIfEnabled(glimpPlugin, rootKey)
addPreferencesFromResourceIfEnabled(careportalPlugin, rootKey)
addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, config.APS)
addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, config.APS)
addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, config.APS)

View file

@ -0,0 +1,72 @@
package info.nightscout.androidaps.db;
import com.j256.ormlite.dao.CloseableIterator;
import org.jetbrains.annotations.NotNull;
import java.sql.SQLException;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
@Singleton
public class DatabaseHelperProvider implements DatabaseHelperInterface {
@Inject DatabaseHelperProvider() {}
@NotNull @Override public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
return MainApp.getDbHelper().getAllBgreadingsDataFromTime(mills, ascending);
}
@Override public void createOrUpdate(@NotNull CareportalEvent careportalEvent) {
MainApp.getDbHelper().createOrUpdate(careportalEvent);
}
@Override public void createOrUpdate(@NotNull DanaRHistoryRecord record) {
MainApp.getDbHelper().createOrUpdate(record);
}
@NotNull @Override public List<DanaRHistoryRecord> getDanaRHistoryRecordsByType(byte type) {
return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type);
}
@NotNull @Override public List<TDD> getTDDs() {
return MainApp.getDbHelper().getTDDs();
}
@Override public long size(@NotNull String table) {
return MainApp.getDbHelper().size(table);
}
@Override public void create(@NotNull DbRequest record) {
try {
MainApp.getDbHelper().create(record);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override public void deleteAllDbRequests() {
MainApp.getDbHelper().deleteAllDbRequests();
}
@Override public int deleteDbRequest(@NotNull String id) {
return MainApp.getDbHelper().deleteDbRequest(id);
}
@Override public void deleteDbRequestbyMongoId(@NotNull String action, @NotNull String _id) {
MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id);
}
@NotNull @Override public CloseableIterator<DbRequest> getDbRequestInterator() {
return MainApp.getDbHelper().getDbRequestInterator();
}
@Override public long roundDateToSec(long date) {
return MainApp.getDbHelper().roundDateToSec(date);
}
}

View file

@ -17,12 +17,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread
abstract class APSModule {
@ContributesAndroidInjector abstract fun loggerCallbackInjector(): LoggerCallback
@ContributesAndroidInjector abstract fun apsResultInjector(): APSResult
@ContributesAndroidInjector abstract fun determineBasalResultSMBInjector(): DetermineBasalResultSMB
@ContributesAndroidInjector abstract fun determineBasalResultAMAInjector(): DetermineBasalResultAMA
@ContributesAndroidInjector abstract fun determineBasalAdapterAMAJSInjector(): DetermineBasalAdapterAMAJS
@ContributesAndroidInjector abstract fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS
@ContributesAndroidInjector abstract fun autosensDataInjector(): AutosensData
@ContributesAndroidInjector abstract fun iobCobThreadInjector(): IobCobThread
@ContributesAndroidInjector abstract fun iobCobOref1ThreadInjector(): IobCobOref1Thread
}

View file

@ -11,10 +11,6 @@ import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizar
import info.nightscout.androidaps.plugins.general.smsCommunicator.activities.SmsCommunicatorOtpActivity
import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRHistoryActivity
import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRUserOptionsActivity
import info.nightscout.androidaps.plugins.pump.danaRS.activities.BLEScanActivity
import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity
import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity
import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity
import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity
@ -25,11 +21,6 @@ import info.nightscout.androidaps.setupwizard.SetupWizardActivity
@Suppress("unused")
abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity
@ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity
@ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaRHistoryActivity
@ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaRUserOptionsActivity
@ContributesAndroidInjector abstract fun contributeErrorHelperActivity(): ErrorHelperActivity
@ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity
@ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity
@ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity
@ -37,7 +28,6 @@ abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity
@ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity
@ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity
@ContributesAndroidInjector abstract fun contributesPairingHelperActivity(): PairingHelperActivity
@ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity
@ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity
@ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity
@ -48,6 +38,5 @@ abstract class ActivitiesModule {
@ContributesAndroidInjector abstract fun contributesSmsCommunicatorOtpActivity(): SmsCommunicatorOtpActivity
@ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity
@ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity
@ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity
@ContributesAndroidInjector abstract fun contributesPrefImportListActivity(): PrefImportListActivity
}

View file

@ -5,14 +5,18 @@ import dagger.Component
import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.core.dependencyInjection.CoreModule
import info.nightscout.androidaps.core.di.CoreModule
import info.nightscout.androidaps.dana.di.DanaModule
import info.nightscout.androidaps.danar.di.DanaRServicesModule
import info.nightscout.androidaps.danars.di.DanaRSModule
import javax.inject.Singleton
@Singleton
@Component(
modules = [
AndroidInjectionModule::class,
CoreModule::class,
PluginsModule::class,
SkinsModule::class,
ActivitiesModule::class,
FragmentsModule::class,
AppModule::class,
@ -28,7 +32,11 @@ import javax.inject.Singleton
OverviewModule::class,
DataClassesModule::class,
SMSModule::class,
UIModule::class
UIModule::class,
CoreModule::class,
DanaModule::class,
DanaRServicesModule::class,
DanaRSModule::class
]
)
interface AppComponent : AndroidInjector<MainApp> {

View file

@ -8,45 +8,34 @@ import dagger.Provides
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.db.DatabaseHelperProvider
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import info.nightscout.androidaps.utils.androidNotification.NotificationHolder
import info.nightscout.androidaps.utils.storage.FileStorage
import info.nightscout.androidaps.utils.storage.Storage
import javax.inject.Singleton
@Module(includes = [
AppModule.AppBindings::class,
PluginsModule::class,
SkinsModule::class
AppModule.AppBindings::class
])
open class AppModule {
@Provides
@Singleton
fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy): ProfileFunction {
return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin, fabricPrivacy)
}
@Provides
fun providesPlugins(configInterface: ConfigInterface,
@PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>,
@PluginsModule.PumpDriver pumpDrivers: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.NotNSClient notNsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.NSClient nsClient: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>,
@PluginsModule.APS aps: Lazy<Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>>)
: List<@JvmSuppressWildcards PluginBase> {
val plugins = allConfigs.toMutableMap()
if (configInterface.PUMPDRIVERS) plugins += pumpDrivers.get()
if (configInterface.APS) plugins += aps.get()
if (!configInterface.NSCLIENT) plugins += notNsClient.get()
if (configInterface.NSCLIENT) plugins += nsClient.get()
return plugins.toList().sortedBy { it.first }.map { it.second }
}
@ -61,11 +50,13 @@ open class AppModule {
@Binds fun bindContext(mainApp: MainApp): Context
@Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector
@Binds fun bindDatabaseHelperInterface(mainApp: MainApp): DatabaseHelperInterface
@Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider
@Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider
@Binds fun configInterfaceProvider(config: Config): ConfigInterface
@Binds fun treatmentInterfaceProvider(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface
@Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider
@Binds fun bindConfigInterface(config: Config): ConfigInterface
@Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilderInterface
@Binds fun bindTreatmentInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface
@Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface
@Binds fun bindUploadQueueInterface(uploadQueue: UploadQueue): UploadQueueInterface
@Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolder): NotificationHolderInterface
}
}

View file

@ -2,7 +2,6 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.queue.CommandQueue
import info.nightscout.androidaps.queue.commands.*
@ -10,8 +9,6 @@ import info.nightscout.androidaps.queue.commands.*
@Suppress("unused")
abstract class CommandQueueModule {
@ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResult
@ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue
@ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus
@ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus

View file

@ -3,14 +3,10 @@ package info.nightscout.androidaps.dependencyInjection
import dagger.Module
import dagger.android.ContributesAndroidInjector
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.*
import info.nightscout.androidaps.interfaces.ProfileStore
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.CareportalEvent
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.ProfileSwitch
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.plugins.general.food.FoodService
import info.nightscout.androidaps.plugins.treatments.TreatmentService
import info.nightscout.androidaps.utils.wizard.BolusWizard
import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
@ -19,19 +15,11 @@ import info.nightscout.androidaps.utils.wizard.QuickWizardEntry
@Suppress("unused")
abstract class DataClassesModule {
@ContributesAndroidInjector abstract fun profileInjector(): Profile
@ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus
@ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore
// TODO move to Core
@ContributesAndroidInjector abstract fun bgReadingInjector(): BgReading
@ContributesAndroidInjector abstract fun treatmentInjector(): Treatment
@ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch
@ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal
@ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent
@ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus
@ContributesAndroidInjector abstract fun DatabaseHelperInjector(): DatabaseHelper
@ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService
@ContributesAndroidInjector abstract fun foodServiceInjector(): FoodService
@ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard
@ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog
import info.nightscout.androidaps.dialogs.NtpProgressDialog
import info.nightscout.androidaps.plugins.general.actions.ActionsFragment
import info.nightscout.androidaps.plugins.general.automation.AutomationFragment
import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseActionDialog
@ -18,8 +18,6 @@ import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTrigg
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditActionDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditTriggerDialog
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog
import info.nightscout.androidaps.plugins.general.food.FoodFragment
import info.nightscout.androidaps.plugins.general.maintenance.MaintenanceFragment
import info.nightscout.androidaps.plugins.general.nsclient.NSClientFragment
@ -34,7 +32,7 @@ import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment
import info.nightscout.androidaps.plugins.pump.combo.ComboFragment
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment
import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment
import info.nightscout.androidaps.danars.dialogs.PairingProgressDialog
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment
import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic
@ -54,13 +52,11 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment
@ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment
@ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment
@ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment
@ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment
@ContributesAndroidInjector
abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment
@ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment
@ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment
@ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment
@ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment
@ -89,7 +85,6 @@ abstract class FragmentsModule {
@ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment
@ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog
@ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog
@ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog
@ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog
@ -100,17 +95,13 @@ abstract class FragmentsModule {
@ContributesAndroidInjector
abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog
@ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog
@ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog
@ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog
@ContributesAndroidInjector abstract fun contributesChooseActionDialog(): ChooseActionDialog
@ContributesAndroidInjector abstract fun contributesChooseTriggerDialog(): ChooseTriggerDialog
@ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog
@ContributesAndroidInjector abstract fun contributesNewNSTreatmentDialog(): NewNSTreatmentDialog
@ContributesAndroidInjector abstract fun contributesNtpProgressDialog(): NtpProgressDialog
@ContributesAndroidInjector abstract fun contributesObjectivesExamDialog(): ObjectivesExamDialog
@ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog
@ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog
@ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog
@ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog
@ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog

View file

@ -4,6 +4,10 @@ import dagger.Binds
import dagger.Module
import dagger.multibindings.IntKey
import dagger.multibindings.IntoMap
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin
@ -17,7 +21,6 @@ import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintP
import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin
import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin
import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin
import info.nightscout.androidaps.plugins.general.food.FoodPlugin
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin
@ -34,14 +37,9 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
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.OmnipodPumpPlugin
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin
@ -161,12 +159,6 @@ abstract class PluginsModule {
@IntKey(170)
abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase
@Binds
@NSClient
@IntoMap
@IntKey(180)
abstract fun bindCareportalPlugin(plugin: CareportalPlugin): PluginBase
@Binds
@APS
@IntoMap
@ -227,7 +219,6 @@ abstract class PluginsModule {
@IntKey(280)
abstract fun bindSmsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase
@Binds
@APS
@IntoMap
@ -357,9 +348,6 @@ abstract class PluginsModule {
@Qualifier
annotation class NotNSClient
@Qualifier
annotation class NSClient
@Qualifier
annotation class APS

View file

@ -16,7 +16,6 @@ abstract class ReceiversModule {
@ContributesAndroidInjector abstract fun contributesChargingStateReceiver(): ChargingStateReceiver
@ContributesAndroidInjector abstract fun contributesDataReceiver(): DataReceiver
@ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver
@ContributesAndroidInjector abstract fun contributesNetworkChangeReceiver(): NetworkChangeReceiver
@ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver
@ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver
@ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver

View file

@ -7,11 +7,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Dismiss
import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService
import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService
import info.nightscout.androidaps.plugins.pump.danaR.services.AbstractDanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService
import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService
import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService
import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2ExecutionService
import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService
import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService
import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService
@ -24,17 +19,12 @@ import info.nightscout.androidaps.services.LocationService
@Suppress("unused")
abstract class ServicesModule {
@ContributesAndroidInjector abstract fun contributesAbstractDanaRExecutionService(): AbstractDanaRExecutionService
@ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService
@ContributesAndroidInjector abstract fun contributesDataService(): DataService
@ContributesAndroidInjector abstract fun contributesDismissNotificationService(): DismissNotificationService
@ContributesAndroidInjector abstract fun contributesDummyService(): DummyService
@ContributesAndroidInjector abstract fun contributesLocationService(): LocationService
@ContributesAndroidInjector abstract fun contributesNSClientService(): NSClientService
@ContributesAndroidInjector abstract fun contributesDanaRSService(): DanaRSService
@ContributesAndroidInjector abstract fun contributesDanaRv2ExecutionService(): DanaRv2ExecutionService
@ContributesAndroidInjector abstract fun contributesDanaRExecutionService(): DanaRExecutionService
@ContributesAndroidInjector abstract fun contributesDanaRKoreanExecutionService(): DanaRKoreanExecutionService
@ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService
@ContributesAndroidInjector abstract fun contributesInsightAlertService(): InsightAlertService
@ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService

View file

@ -1,16 +0,0 @@
PreferenceActivity is an Example how to make an Activity injectable.
We might undo that as we don't actually have us inject things.
MyPreferencesFragment is an injectable Fragment. Here we actually have Dagger2 provide us an InsulinOrefFreePeakPlugin instance.
If we use multiple Fragments, we should generate a base-class. Then we only have to add a "provides***Fragment" to the FragmentsModule and derive from that class.
InsulinOrefFreePeakPlugin is an example how to get things injected via the constructor.
You could call "new InsulinOrefFreePeakPlugin(new SPImpl(SPImpl(PreferenceManager.getDefaultSharedPreferences(context))), new ResourceHelper())"... but Dagger will resolve that for you in MainApp. :)
SPImpl is an example how to bind an implementation to an Interface via Dagger.
ResourceHelper is an example how to generate simple classes that Dagger can auto-resolve how to inject them. No need for a provider here.
ResourceHelper might have a weak reference at some point and not a static dependency on MainApp... but at least we reduced the static dependencies within a plugin.
In order to Test: Any dependency of InsulinOrefFreePeakPlugin is passed via the constructor. Instead of static mocking MainApp you now can Mock ResourceHelper with a very small interface.

View file

@ -40,6 +40,7 @@ class CarbsDialog : DialogFragmentWithDate() {
@Inject lateinit var treatmentsPlugin: TreatmentsPlugin
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var carbsGenerator: CarbsGenerator
companion object {
@ -233,7 +234,7 @@ class CarbsDialog : DialogFragmentWithDate() {
} else {
aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration")
carbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes)
NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset))
nsUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset))
}
}
}, null)

View file

@ -20,8 +20,8 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.Translator
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.dialog_care.*
import kotlinx.android.synthetic.main.notes.*
@ -36,6 +36,7 @@ class CareDialog : DialogFragmentWithDate() {
@Inject lateinit var mainApp: MainApp
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var translator: Translator
enum class EventType {
@ -43,10 +44,13 @@ class CareDialog : DialogFragmentWithDate() {
SENSOR_INSERT,
BATTERY_CHANGE,
NOTE,
EXERCISE
EXERCISE,
QUESTION,
ANNOUNCEMENT
}
private var options: EventType = EventType.BGCHECK
@StringRes
private var event: Int = R.string.none
@ -84,6 +88,8 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> R.drawable.icon_cp_pump_battery
EventType.NOTE -> R.drawable.icon_cp_note
EventType.EXERCISE -> R.drawable.icon_cp_exercise
EventType.QUESTION -> R.drawable.icon_cp_question
EventType.ANNOUNCEMENT -> R.drawable.icon_cp_announcement
})
actions_care_title.text = resourceHelper.gs(when (options) {
EventType.BGCHECK -> R.string.careportal_bgcheck
@ -91,9 +97,13 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange
EventType.NOTE -> R.string.careportal_note
EventType.EXERCISE -> R.string.careportal_exercise
EventType.QUESTION -> R.string.careportal_question
EventType.ANNOUNCEMENT -> R.string.careportal_announcement
})
when (options) {
EventType.QUESTION,
EventType.ANNOUNCEMENT,
EventType.BGCHECK -> {
action_care_duration_layout.visibility = View.GONE
}
@ -133,7 +143,7 @@ class CareDialog : DialogFragmentWithDate() {
}
actions_care_duration.setParams(savedInstanceState?.getDouble("actions_care_duration")
?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok)
if (options == EventType.NOTE)
if (options == EventType.NOTE || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT)
notes_layout?.visibility = View.VISIBLE // independent to preferences
}
@ -143,7 +153,7 @@ class CareDialog : DialogFragmentWithDate() {
val json = JSONObject()
val actions: LinkedList<String> = LinkedList()
if (options == EventType.BGCHECK) {
if (options == EventType.BGCHECK || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT) {
val type =
when {
actions_care_meter.isChecked -> "Finger"
@ -177,6 +187,8 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE
EventType.NOTE -> CareportalEvent.NOTE
EventType.EXERCISE -> CareportalEvent.EXERCISE
EventType.QUESTION -> CareportalEvent.QUESTION
EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT
})
json.put("units", profileFunction.getUnits())
if (enteredBy.isNotEmpty())
@ -193,11 +205,13 @@ class CareDialog : DialogFragmentWithDate() {
EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE
EventType.NOTE -> CareportalEvent.NOTE
EventType.EXERCISE -> CareportalEvent.EXERCISE
EventType.QUESTION -> CareportalEvent.QUESTION
EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT
}
careportalEvent.json = json.toString()
aapsLogger.debug("USER ENTRY: CAREPORTAL ${careportalEvent.eventType} json: ${careportalEvent.json}")
MainApp.getDbHelper().createOrUpdate(careportalEvent)
NSUpload.uploadCareportalEntryToNS(json)
nsUpload.uploadCareportalEntryToNS(json)
}, null)
}
return true

View file

@ -23,9 +23,10 @@ import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.SafeParse
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import kotlinx.android.synthetic.main.dialog_fill.*
import kotlinx.android.synthetic.main.notes.*
import kotlinx.android.synthetic.main.okcancel.*
@ -39,9 +40,9 @@ class FillDialog : DialogFragmentWithDate() {
@Inject lateinit var constraintChecker: ConstraintChecker
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var ctx: Context
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var commandQueue: CommandQueueProvider
@Inject lateinit var activePlugin: ActivePluginProvider
@Inject lateinit var injector: HasAndroidInjector
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
@ -123,12 +124,12 @@ class FillDialog : DialogFragmentWithDate() {
}
if (siteChange) {
aapsLogger.debug("USER ENTRY: SITE CHANGE")
generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes)
nsUpload.generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes)
}
if (insulinChange) {
// add a second for case of both checked
aapsLogger.debug("USER ENTRY: INSULIN CHANGE")
generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes)
nsUpload.generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes)
}
}, null)
}
@ -161,28 +162,4 @@ class FillDialog : DialogFragmentWithDate() {
}
})
}
private fun generateCareportalEvent(eventType: String, time: Long, notes: String) {
val careportalEvent = CareportalEvent(injector)
careportalEvent.source = Source.USER
careportalEvent.date = time
careportalEvent.json = generateJson(eventType, time, notes).toString()
careportalEvent.eventType = eventType
MainApp.getDbHelper().createOrUpdate(careportalEvent)
NSUpload.uploadEvent(eventType, time, notes)
}
private fun generateJson(careportalEvent: String, time: Long, notes: String): JSONObject {
val data = JSONObject()
try {
data.put("eventType", careportalEvent)
data.put("created_at", DateUtil.toISOString(time))
data.put("mills", time)
data.put("enteredBy", sp.getString("careportal_enteredby", resourceHelper.gs(R.string.app_name)))
if (notes.isNotEmpty()) data.put("notes", notes)
} catch (ignored: JSONException) {
}
return data
}
}

View file

@ -89,19 +89,19 @@ class TempBasalDialog : DialogFragmentWithDate() {
if (isPercentPump) {
val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text)
percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value()
actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": $percent%")
actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": $percent%")
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes))
if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied))
} else {
val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text)
absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value()
actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute))
actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes))
if (abs(absolute - basalAbsoluteInput) > 0.01)
actions.add("<font color='" + resourceHelper.gc(R.color.warning) + "'>" + resourceHelper.gs(R.string.constraintapllied) + "</font>")
}
activity?.let { activity ->
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
val callback: Callback = object : Callback() {
override fun run() {
if (!result.success) {

View file

@ -16,7 +16,6 @@ import info.nightscout.androidaps.db.TempTarget
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
@ -123,7 +122,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
val duration = overview_temptarget_duration.value.toInt()
if (target != 0.0 && duration != 0) {
actions.add(resourceHelper.gs(R.string.reason) + ": " + reason)
actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId))
actions.add(resourceHelper.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId))
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration))
} else {
actions.add(resourceHelper.gs(R.string.stoptemptarget))

View file

@ -4,7 +4,7 @@ import org.mozilla.javascript.ScriptableObject;
import javax.inject.Inject;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.StaticInjector;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
@ -26,7 +26,7 @@ public class LoggerCallback extends ScriptableObject {
//empty constructor needed for Rhino
errorBuffer = new StringBuffer();
logBuffer = new StringBuffer();
MainApp.instance().androidInjector().inject(this);
StaticInjector.Companion.getInstance().androidInjector().inject(this);
}
@Override

View file

@ -21,6 +21,7 @@ import javax.inject.Singleton;
import dagger.Lazy;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
@ -40,9 +41,11 @@ import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.LoopInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
@ -52,7 +55,6 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@ -67,15 +69,15 @@ import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.receivers.ReceiverStatusStore;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import info.nightscout.androidaps.utils.HardLimits;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
@Singleton
public class LoopPlugin extends PluginBase {
public class LoopPlugin extends PluginBase implements LoopInterface {
private final HasAndroidInjector injector;
private final SP sp;
private final RxBusWrapper rxBus;
@ -91,6 +93,7 @@ public class LoopPlugin extends PluginBase {
private final IobCobCalculatorPlugin iobCobCalculatorPlugin;
private final ReceiverStatusStore receiverStatusStore;
private final FabricPrivacy fabricPrivacy;
private final NSUpload nsUpload;
private final HardLimits hardLimits;
private Notification notification;
@ -106,21 +109,15 @@ public class LoopPlugin extends PluginBase {
private long carbsSuggestionsSuspendedUntil = 0;
public class LastRun {
public APSResult request = null;
public APSResult constraintsProcessed = null;
public PumpEnactResult tbrSetByPump = null;
public PumpEnactResult smbSetByPump = null;
public String source = null;
public long lastAPSRun = DateUtil.now();
public long lastTBREnact = 0;
public long lastSMBEnact = 0;
public long lastTBRRequest = 0;
public long lastSMBRequest = 0;
public long lastOpenModeAccept;
@Nullable private LastRun lastRun = null;
@Nullable @Override public LastRun getLastRun() {
return lastRun;
}
@Nullable public LastRun lastRun = null;
@Override public void setLastRun(@Nullable LastRun lastRun) {
this.lastRun = lastRun;
}
@Inject
public LoopPlugin(
@ -140,6 +137,7 @@ public class LoopPlugin extends PluginBase {
IobCobCalculatorPlugin iobCobCalculatorPlugin,
ReceiverStatusStore receiverStatusStore,
FabricPrivacy fabricPrivacy,
NSUpload nsUpload,
HardLimits hardLimits
) {
super(new PluginDescription()
@ -166,6 +164,7 @@ public class LoopPlugin extends PluginBase {
this.iobCobCalculatorPlugin = iobCobCalculatorPlugin;
this.receiverStatusStore = receiverStatusStore;
this.fabricPrivacy = fabricPrivacy;
this.nsUpload = nsUpload;
this.hardLimits = hardLimits;
loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L);
@ -297,7 +296,7 @@ public class LoopPlugin extends PluginBase {
return true;
}
public boolean isLGS(){
public boolean isLGS() {
Constraint<Boolean> closedLoopEnabled = constraintChecker.isClosedLoopAllowed();
Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value();
String APSmode = sp.getString(R.string.key_aps_mode, "open");
@ -408,18 +407,18 @@ public class LoopPlugin extends PluginBase {
}
if (lastRun == null) lastRun = new LastRun();
lastRun.request = result;
lastRun.constraintsProcessed = resultAfterConstraints;
lastRun.lastAPSRun = DateUtil.now();
lastRun.source = ((PluginBase) usedAPS).getName();
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
lastRun.lastTBREnact = 0;
lastRun.lastTBRRequest = 0;
lastRun.lastSMBEnact = 0;
lastRun.lastSMBRequest = 0;
lastRun.setRequest(result);
lastRun.setConstraintsProcessed(resultAfterConstraints);
lastRun.setLastAPSRun(DateUtil.now());
lastRun.setSource(((PluginBase) usedAPS).getName());
lastRun.setTbrSetByPump(null);
lastRun.setSmbSetByPump(null);
lastRun.setLastTBREnact(0);
lastRun.setLastTBRRequest(0);
lastRun.setLastSMBEnact(0);
lastRun.setLastSMBRequest(0);
NSUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore);
nsUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
if (isSuspended()) {
getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended));
@ -503,27 +502,27 @@ public class LoopPlugin extends PluginBase {
final PumpEnactResult waiting = new PumpEnactResult(getInjector());
waiting.queued = true;
if (resultAfterConstraints.tempBasalRequested)
lastRun.tbrSetByPump = waiting;
lastRun.setTbrSetByPump(waiting);
if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting;
lastRun.setSmbSetByPump(waiting);
rxBus.send(new EventLoopUpdateGui());
fabricPrivacy.logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
public void run() {
if (result.enacted || result.success) {
lastRun.tbrSetByPump = result;
lastRun.lastTBRRequest = lastRun.lastAPSRun;
lastRun.lastTBREnact = DateUtil.now();
lastRun.setTbrSetByPump(result);
lastRun.setLastTBRRequest(lastRun.getLastAPSRun());
lastRun.setLastTBREnact(DateUtil.now());
rxBus.send(new EventLoopUpdateGui());
applySMBRequest(resultAfterConstraints, new Callback() {
@Override
public void run() {
//Callback is only called if a bolus was acutally requested
if (result.enacted || result.success) {
lastRun.smbSetByPump = result;
lastRun.lastSMBRequest = lastRun.lastAPSRun;
lastRun.lastSMBEnact = DateUtil.now();
lastRun.setTbrSetByPump(result);
lastRun.setLastTBRRequest(lastRun.getLastAPSRun());
lastRun.setLastTBREnact(DateUtil.now());
} else {
new Thread(() -> {
SystemClock.sleep(1000);
@ -538,8 +537,8 @@ public class LoopPlugin extends PluginBase {
}
});
} else {
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
lastRun.setTbrSetByPump(null);
lastRun.setSmbSetByPump(null);
}
} else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) {
@ -609,15 +608,15 @@ public class LoopPlugin extends PluginBase {
public void acceptChangeRequest() {
Profile profile = profileFunction.getProfile();
final LoopPlugin lp = this;
applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() {
applyTBRRequest(lastRun.getConstraintsProcessed(), profile, new Callback() {
@Override
public void run() {
if (result.enacted) {
lastRun.tbrSetByPump = result;
lastRun.lastTBRRequest = lastRun.lastAPSRun;
lastRun.lastTBREnact = DateUtil.now();
lastRun.lastOpenModeAccept = DateUtil.now();
NSUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore);
lastRun.setTbrSetByPump(result);
lastRun.setLastTBRRequest(lastRun.getLastAPSRun());
lastRun.setLastTBREnact(DateUtil.now());
lastRun.setLastOpenModeAccept(DateUtil.now());
nsUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
sp.incInt(R.string.key_ObjectivesmanualEnacts);
}
rxBus.send(new EventAcceptOpenLoopChange());
@ -851,6 +850,7 @@ public class LoopPlugin extends PluginBase {
event.eventType = CareportalEvent.OPENAPSOFFLINE;
event.json = data.toString();
MainApp.getDbHelper().createOrUpdate(event);
NSUpload.uploadOpenAPSOffline(event);
nsUpload.uploadOpenAPSOffline(event);
}
}

View file

@ -36,7 +36,7 @@ class ConfigBuilderPlugin @Inject constructor(
.shortName(R.string.configbuilder_shortname)
.description(R.string.description_config_builder),
aapsLogger, resourceHelper, injector
) {
), ConfigBuilderInterface {
fun initialize() {
(activePlugin as PluginStore).loadDefaults()
@ -52,7 +52,7 @@ class ConfigBuilderPlugin @Inject constructor(
storeSettings("setAlwaysEnabledPluginsEnabled")
}
fun storeSettings(from: String) {
override fun storeSettings(from: String) {
activePlugin.pluginsList
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from")
activePlugin.verifySelectionInCategories()

View file

@ -22,8 +22,8 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog
import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus
import info.nightscout.androidaps.dialogs.NtpProgressDialog
import info.nightscout.androidaps.events.EventNtpStatus
import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui
import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask
import info.nightscout.androidaps.receivers.ReceiverStatusStore

View file

@ -144,6 +144,12 @@ class ActionsFragment : DaggerFragment() {
actions_exercise.setOnClickListener {
CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions")
}
actions_question.setOnClickListener {
CareDialog().setOptions(CareDialog.EventType.QUESTION, R.string.careportal_question).show(childFragmentManager, "Actions")
}
actions_announcement.setOnClickListener {
CareDialog().setOptions(CareDialog.EventType.ANNOUNCEMENT, R.string.careportal_announcement).show(childFragmentManager, "Actions")
}
sp.putBoolean(R.string.key_objectiveuseactions, true)
}
@ -192,13 +198,7 @@ class ActionsFragment : DaggerFragment() {
val pump = activePlugin.activePump
actions_temptarget?.visibility = (profile != null).toVisibility()
actions_canceltempbasal.visibility = (profile == null).toVisibility()
actions_settempbasal.visibility = (profile == null).toVisibility()
actions_fill.visibility = (profile == null).toVisibility()
actions_extendedbolus.visibility = (profile == null).toVisibility()
actions_extendedbolus_cancel.visibility = (profile == null).toVisibility()
actions_historybrowser.visibility = (profile == null).toVisibility()
actions_tddstats.visibility = (profile == null).toVisibility()
actions_historybrowser.visibility = (profile != null).toVisibility()
val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable

View file

@ -22,6 +22,7 @@ import javax.inject.Inject
class ActionNotification(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var nsUpload: NSUpload
var text = InputString(injector)
@ -32,7 +33,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) {
override fun doAction(callback: Callback) {
val notification = NotificationUserMessage(text.value)
rxBus.send(EventNewNotification(notification))
NSUpload.uploadError(text.value)
nsUpload.uploadError(text.value)
rxBus.send(EventRefreshOverview("ActionNotification"))
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
}

View file

@ -26,7 +26,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) {
override fun doAction(callback: Callback) {
val result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.value)
callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.danar_error))?.run()
callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.error))?.run()
}
override fun toJSON(): String {

View file

@ -1,134 +0,0 @@
package info.nightscout.androidaps.plugins.general.careportal
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventCareportalEventChange
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog
import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.careportal_fragment.*
import kotlinx.android.synthetic.main.careportal_stats_fragment.*
import javax.inject.Inject
class CareportalFragment : DaggerFragment(), View.OnClickListener {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var statusLightHandler: StatusLightHandler
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var activePlugin: ActivePluginProvider
private val disposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.careportal_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
careportal_bgcheck.setOnClickListener(this)
careportal_announcement.setOnClickListener(this)
careportal_cgmsensorinsert.setOnClickListener(this)
careportal_cgmsensorstart.setOnClickListener(this)
careportal_combobolus.setOnClickListener(this)
careportal_correctionbolus.setOnClickListener(this)
careportal_carbscorrection.setOnClickListener(this)
careportal_exercise.setOnClickListener(this)
careportal_insulincartridgechange.setOnClickListener(this)
careportal_pumpbatterychange.setOnClickListener(this)
careportal_mealbolus.setOnClickListener(this)
careportal_note.setOnClickListener(this)
careportal_profileswitch.setOnClickListener(this)
careportal_pumpsitechange.setOnClickListener(this)
careportal_question.setOnClickListener(this)
careportal_snackbolus.setOnClickListener(this)
careportal_tempbasalend.setOnClickListener(this)
careportal_tempbasalstart.setOnClickListener(this)
careportal_openapsoffline.setOnClickListener(this)
careportal_temporarytarget.setOnClickListener(this)
val profileStore = activePlugin.activeProfileInterface.profile
if (profileStore == null) {
profileview_noprofile.visibility = View.VISIBLE
careportal_buttons.visibility = View.GONE
} else {
profileview_noprofile.visibility = View.GONE
careportal_buttons.visibility = View.VISIBLE
}
}
@Synchronized override fun onResume() {
super.onResume()
disposable.add(rxBus
.toObservable(EventCareportalEventChange::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }) { fabricPrivacy.logException(it) }
)
updateGUI()
}
@Synchronized override fun onPause() {
super.onPause()
disposable.clear()
}
override fun onClick(view: View) {
val BGCHECK = OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck).date().bg()
val SNACKBOLUS = OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus).date().bg().insulin().carbs().prebolus()
val MEALBOLUS = OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus).date().bg().insulin().carbs().prebolus()
val CORRECTIONBOLUS = OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus).date().bg().insulin().carbs().prebolus()
val CARBCORRECTION = OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection).date().bg().carbs()
val COMBOBOLUS = OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus).date().bg().insulin().carbs().prebolus().duration().split()
val ANNOUNCEMENT = OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement).date().bg()
val NOTE = OptionsToShow(R.id.careportal_note, R.string.careportal_note).date().bg().duration()
val QUESTION = OptionsToShow(R.id.careportal_question, R.string.careportal_question).date().bg()
val EXERCISE = OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise).date().duration()
val SITECHANGE = OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange).date().bg()
val SENSORSTART = OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart).date().bg()
val SENSORCHANGE = OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert).date().bg()
val INSULINCHANGE = OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange).date().bg()
val PUMPBATTERYCHANGE = OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange).date().bg()
val TEMPBASALSTART = OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart).date().bg().duration().percent().absolute()
val TEMPBASALEND = OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend).date().bg()
val PROFILESWITCH = OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch).date().duration().profile()
val OPENAPSOFFLINE = OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline).date().duration()
val TEMPTARGET = OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget).date().duration().tempTarget()
val newDialog = NewNSTreatmentDialog()
when (view.id) {
R.id.careportal_bgcheck -> newDialog.setOptions(BGCHECK, R.string.careportal_bgcheck)
R.id.careportal_announcement -> newDialog.setOptions(ANNOUNCEMENT, R.string.careportal_announcement)
R.id.careportal_cgmsensorinsert -> newDialog.setOptions(SENSORCHANGE, R.string.careportal_cgmsensorinsert)
R.id.careportal_cgmsensorstart -> newDialog.setOptions(SENSORSTART, R.string.careportal_cgmsensorstart)
R.id.careportal_combobolus -> newDialog.setOptions(COMBOBOLUS, R.string.careportal_combobolus)
R.id.careportal_correctionbolus -> newDialog.setOptions(CORRECTIONBOLUS, R.string.careportal_correctionbolus)
R.id.careportal_carbscorrection -> newDialog.setOptions(CARBCORRECTION, R.string.careportal_carbscorrection)
R.id.careportal_exercise -> newDialog.setOptions(EXERCISE, R.string.careportal_exercise)
R.id.careportal_insulincartridgechange -> newDialog.setOptions(INSULINCHANGE, R.string.careportal_insulincartridgechange)
R.id.careportal_pumpbatterychange -> newDialog.setOptions(PUMPBATTERYCHANGE, R.string.careportal_pumpbatterychange)
R.id.careportal_mealbolus -> newDialog.setOptions(MEALBOLUS, R.string.careportal_mealbolus)
R.id.careportal_note -> newDialog.setOptions(NOTE, R.string.careportal_note)
R.id.careportal_profileswitch -> newDialog.setOptions(PROFILESWITCH, R.string.careportal_profileswitch)
R.id.careportal_pumpsitechange -> newDialog.setOptions(SITECHANGE, R.string.careportal_pumpsitechange)
R.id.careportal_question -> newDialog.setOptions(QUESTION, R.string.careportal_question)
R.id.careportal_snackbolus -> newDialog.setOptions(SNACKBOLUS, R.string.careportal_snackbolus)
R.id.careportal_tempbasalstart -> newDialog.setOptions(TEMPBASALSTART, R.string.careportal_tempbasalstart)
R.id.careportal_tempbasalend -> newDialog.setOptions(TEMPBASALEND, R.string.careportal_tempbasalend)
R.id.careportal_openapsoffline -> newDialog.setOptions(OPENAPSOFFLINE, R.string.careportal_openapsoffline)
R.id.careportal_temporarytarget -> newDialog.setOptions(TEMPTARGET, R.string.careportal_temporarytarget)
}
NewNSTreatmentDialog().show(childFragmentManager, "CareportalFragment")
}
private fun updateGUI() {
statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, null, careportal_sensorage, careportal_pbage, null)
}
}

View file

@ -1,29 +0,0 @@
package info.nightscout.androidaps.plugins.general.careportal
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.utils.resources.ResourceHelper
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class CareportalPlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
config: Config
) : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(CareportalFragment::class.java.name)
.pluginName(R.string.careportal)
.shortName(R.string.careportal_shortname)
.visibleByDefault(config.NSCLIENT)
.enableByDefault(config.NSCLIENT)
.description(R.string.description_careportal),
aapsLogger, resourceHelper, injector
)

View file

@ -1,739 +0,0 @@
package info.nightscout.androidaps.plugins.general.careportal.Dialogs;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.StringRes;
import androidx.fragment.app.DialogFragment;
import com.google.common.collect.Lists;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import dagger.android.support.DaggerDialogFragment;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.NumberPicker;
import info.nightscout.androidaps.utils.SafeParse;
import info.nightscout.androidaps.utils.Translator;
import info.nightscout.androidaps.utils.alertDialogs.OKDialog;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
@Inject HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject DefaultValueHelper defaultValueHelper;
@Inject ProfileFunction profileFunction;
@Inject ResourceHelper resourceHelper;
@Inject ConstraintChecker constraintChecker;
@Inject SP sp;
@Inject ActivePluginProvider activePlugin;
@Inject TreatmentsPlugin treatmentsPlugin;
@Inject HardLimits hardLimits;
@Inject Translator translator;
@Inject DateUtil dateUtil;
private static OptionsToShow options;
private static @StringRes int event;
private Profile profile;
public ProfileStore profileStore;
TextView eventTypeText;
LinearLayout layoutPercent;
LinearLayout layoutAbsolute;
LinearLayout layoutReuse;
TextView dateButton;
TextView timeButton;
TextView bgUnitsView;
RadioButton meterRadioButton;
RadioButton sensorRadioButton;
RadioButton otherRadioButton;
EditText notesEdit;
Spinner profileSpinner;
Spinner reasonSpinner;
Button reuseButton;
NumberPicker editBg;
NumberPicker editCarbs;
NumberPicker editInsulin;
NumberPicker editSplit;
NumberPicker editDuration;
NumberPicker editPercent;
NumberPicker editAbsolute;
NumberPicker editCarbTime;
NumberPicker editTemptarget;
NumberPicker editPercentage;
NumberPicker editTimeshift;
Date eventTime;
private static Integer seconds = null;
public NewNSTreatmentDialog setOptions(OptionsToShow options, int event) {
this.options = options;
this.event = event;
return this;
}
public NewNSTreatmentDialog() {
super();
if (seconds == null) {
seconds = Double.valueOf(Math.random() * 59).intValue();
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (options == null) return null;
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setCancelable(true);
getDialog().setCanceledOnTouchOutside(false);
setStyle(DialogFragment.STYLE_NORMAL, getTheme());
View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false);
layoutPercent = view.findViewById(R.id.careportal_newnstreatment_percent_layout);
layoutAbsolute = view.findViewById(R.id.careportal_newnstreatment_absolute_layout);
layoutReuse = view.findViewById(R.id.careportal_newnstreatment_reuse_layout);
eventTypeText = view.findViewById(R.id.careportal_newnstreatment_eventtype);
eventTypeText.setText(event);
bgUnitsView = view.findViewById(R.id.careportal_newnstreatment_bgunits);
meterRadioButton = view.findViewById(R.id.careportal_newnstreatment_meter);
sensorRadioButton = view.findViewById(R.id.careportal_newnstreatment_sensor);
otherRadioButton = view.findViewById(R.id.careportal_newnstreatment_other);
profileSpinner = view.findViewById(R.id.careportal_newnstreatment_profile);
reuseButton = view.findViewById(R.id.careportal_newnstreatment_reusebutton);
notesEdit = view.findViewById(R.id.careportal_newnstreatment_notes);
reasonSpinner = view.findViewById(R.id.careportal_newnstreatment_temptarget_reason);
eventTime = new Date();
dateButton = view.findViewById(R.id.careportal_newnstreatment_eventdate);
timeButton = view.findViewById(R.id.careportal_newnstreatment_eventtime);
dateButton.setText(DateUtil.dateString(eventTime));
timeButton.setText(dateUtil.timeString(eventTime));
dateButton.setOnClickListener(this);
timeButton.setOnClickListener(this);
view.findViewById(R.id.ok).setOnClickListener(this);
view.findViewById(R.id.cancel).setOnClickListener(this);
// profile
profile = profileFunction.getProfile();
profileStore = activePlugin.getActiveProfileInterface().getProfile();
if (profileStore == null) {
if (options.eventType == R.id.careportal_profileswitch) {
aapsLogger.error("Profile switch called but plugin doesn't contain valid profile");
}
} else {
ArrayList<CharSequence> profileList;
profileList = profileStore.getProfileList();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, profileList);
profileSpinner.setAdapter(adapter);
// set selected to actual profile
for (int p = 0; p < profileList.size(); p++) {
if (profileList.get(p).equals(profileFunction.getProfileName(false)))
profileSpinner.setSelection(p);
}
}
final Double bg = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits());
// temp target
final List<String> reasonList = Lists.newArrayList(
resourceHelper.gs(R.string.manual),
resourceHelper.gs(R.string.eatingsoon),
resourceHelper.gs(R.string.activity),
resourceHelper.gs(R.string.hypo));
ArrayAdapter<String> adapterReason = new ArrayAdapter<>(getContext(),
R.layout.spinner_centered, reasonList);
reasonSpinner.setAdapter(adapterReason);
reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
double defaultDuration;
double defaultTarget;
if (profile != null && editTemptarget.getValue().equals(bg)) {
defaultTarget = bg;
} else {
//prevent changes on screen rotate
defaultTarget = editTemptarget.getValue();
}
boolean erase = false;
if (resourceHelper.gs(R.string.eatingsoon).equals(reasonList.get(position))) {
defaultDuration = defaultValueHelper.determineEatingSoonTTDuration();
defaultTarget = defaultValueHelper.determineEatingSoonTT();
} else if (resourceHelper.gs(R.string.activity).equals(reasonList.get(position))) {
defaultDuration = defaultValueHelper.determineActivityTTDuration();
defaultTarget = defaultValueHelper.determineActivityTT();
} else if (resourceHelper.gs(R.string.hypo).equals(reasonList.get(position))) {
defaultDuration = defaultValueHelper.determineHypoTTDuration();
defaultTarget = defaultValueHelper.determineHypoTT();
} else if (editDuration.getValue() != 0) {
defaultDuration = editDuration.getValue();
} else {
defaultDuration = 0;
erase = true;
}
if (defaultTarget != 0 || erase) {
editTemptarget.setValue(defaultTarget);
}
if (defaultDuration != 0) {
editDuration.setValue(defaultDuration);
} else if (erase) {
editDuration.setValue(0d);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// bg
bgUnitsView.setText(profileFunction.getUnits());
TextWatcher bgTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true);
}
};
editBg = view.findViewById(R.id.careportal_newnstreatment_bginput);
editTemptarget = view.findViewById(R.id.careportal_newnstreatment_temptarget);
if (profile == null) {
editBg.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok), bgTextWatcher);
editTemptarget.setParams(Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok));
} else if (profileFunction.getUnits().equals(Constants.MMOL)) {
editBg.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok), bgTextWatcher);
editTemptarget.setParams(Constants.MIN_TT_MMOL, Constants.MIN_TT_MMOL, Constants.MAX_TT_MMOL, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok));
} else {
editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok), bgTextWatcher);
editTemptarget.setParams(Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
}
sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
double bg1 = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits());
if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) {
editBg.setValue(savedInstanceState.getDouble("editBg"));
} else {
editBg.setValue(bg1);
}
});
Integer maxCarbs = constraintChecker.getMaxCarbsAllowed().value();
editCarbs = view.findViewById(R.id.careportal_newnstreatment_carbsinput);
editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
Double maxInsulin = constraintChecker.getMaxBolusAllowed().value();
editInsulin = view.findViewById(R.id.careportal_newnstreatment_insulininput);
editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false, view.findViewById(R.id.ok));
editSplit = view.findViewById(R.id.careportal_newnstreatment_splitinput);
editSplit.setParams(100d, 0d, 100d, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok));
editDuration = view.findViewById(R.id.careportal_newnstreatment_durationinput);
editDuration.setParams(0d, 0d, Constants.MAX_PROFILE_SWITCH_DURATION, 10d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
TextWatcher percentTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
layoutPercent.setVisibility(View.VISIBLE);
layoutAbsolute.setVisibility(View.GONE);
}
};
Integer maxPercent = 200;
if (profile != null)
maxPercent = constraintChecker.getMaxBasalPercentAllowed(profile).value();
editPercent = view.findViewById(R.id.careportal_newnstreatment_percentinput);
editPercent.setParams(0d, -100d, (double) maxPercent, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok), percentTextWatcher);
TextWatcher absoluteTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
layoutPercent.setVisibility(View.GONE);
layoutAbsolute.setVisibility(View.VISIBLE);
}
};
Double maxAbsolute = hardLimits.maxBasal();
if (profile != null)
maxAbsolute = constraintChecker.getMaxBasalAllowed(profile).value();
editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput);
editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, view.findViewById(R.id.ok), absoluteTextWatcher);
editCarbTime = view.findViewById(R.id.careportal_newnstreatment_carbtimeinput);
editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
editPercentage = view.findViewById(R.id.careportal_newnstreatment_percentage);
editPercentage.setParams(100d, (double) Constants.CPP_MIN_PERCENTAGE, (double) Constants.CPP_MAX_PERCENTAGE, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
editTimeshift = view.findViewById(R.id.careportal_newnstreatment_timeshift);
editTimeshift.setParams(0d, (double) Constants.CPP_MIN_TIMESHIFT, (double) Constants.CPP_MAX_TIMESHIFT, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok));
ProfileSwitch ps = treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now());
if (ps != null && ps.isCPP) {
final int percentage = ps.percentage;
final int timeshift = ps.timeshift;
reuseButton.setText(reuseButton.getText() + " " + percentage + "% " + timeshift + "h");
reuseButton.setOnClickListener(v -> {
editPercentage.setValue((double) percentage);
editTimeshift.setValue((double) timeshift);
});
}
if (ps == null) {
options.duration = false;
}
showOrHide(view.findViewById(R.id.careportal_newnstreatment_eventtime_layout), options.date);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_bg_layout), options.bg);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_bgsource_layout), options.bg);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_insulin_layout), options.insulin);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_carbs_layout), options.carbs);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_split_layout), options.split);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_duration_layout), options.duration);
showOrHide(layoutPercent, options.percent);
showOrHide(layoutAbsolute, options.absolute);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_carbtime_layout), options.prebolus);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_profile_layout), options.profile);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_percentage_layout), options.profile);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_timeshift_layout), options.profile);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_reuse_layout), options.profile && ps != null && ps.isCPP);
showOrHide(view.findViewById(R.id.careportal_newnstreatment_temptarget_layout), options.tempTarget);
setCancelable(true);
getDialog().setCanceledOnTouchOutside(false);
//recovering state if there is something
// only numberPickers and editTexts
if (savedInstanceState != null) {
editBg.setValue(savedInstanceState.getDouble("editBg"));
editTemptarget.setValue(savedInstanceState.getDouble("editTemptarget"));
notesEdit.setText(savedInstanceState.getString("notesEdit"));
editCarbs.setValue(savedInstanceState.getDouble("editCarbs"));
editCarbs.setValue(savedInstanceState.getDouble("editCarbs"));
editInsulin.setValue(savedInstanceState.getDouble("editInsulin"));
editDuration.setValue(savedInstanceState.getDouble("editDuration"));
editPercent.setValue(savedInstanceState.getDouble("editPercent"));
editAbsolute.setValue(savedInstanceState.getDouble("editAbsolute"));
editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime"));
editPercentage.setValue(savedInstanceState.getDouble("editPercentage"));
editTimeshift.setValue(savedInstanceState.getDouble("editTimeshift"));
// time and date
dateButton.setText(savedInstanceState.getString("dateButton"));
timeButton.setText(savedInstanceState.getString("timeButton"));
}
return view;
}
@Override
public void onResume() {
super.onResume();
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(eventTime);
switch (view.getId()) {
case R.id.careportal_newnstreatment_eventdate:
DatePickerDialog dpd = DatePickerDialog.newInstance(
this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
dpd.setThemeDark(true);
dpd.dismissOnPause(true);
dpd.show(getActivity().getSupportFragmentManager(), "Datepickerdialog");
break;
case R.id.careportal_newnstreatment_eventtime:
TimePickerDialog tpd = TimePickerDialog.newInstance(
this,
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
DateFormat.is24HourFormat(getContext())
);
tpd.setThemeDark(true);
tpd.dismissOnPause(true);
tpd.show(getActivity().getSupportFragmentManager(), "Timepickerdialog");
break;
case R.id.ok:
confirmNSTreatmentCreation();
dismiss();
break;
case R.id.cancel:
dismiss();
break;
}
}
private void showOrHide(ViewGroup layout, boolean visible) {
if (visible) layout.setVisibility(View.VISIBLE);
else layout.setVisibility(View.GONE);
}
private void updateBGforDateTime() {
long millis = eventTime.getTime() - (150 * 1000L); // 2,5 * 60 * 1000
List<BgReading> data = MainApp.getDbHelper().getBgreadingsDataFromTime(millis, true);
if ((data.size() > 0) &&
(data.get(0).date > millis - 7 * 60 * 1000L) &&
(data.get(0).date < millis + 7 * 60 * 1000L)) {
editBg.setValue(Profile.fromMgdlToUnits(data.get(0).value, profileFunction.getUnits()));
}
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
eventTime.setYear(year - 1900);
eventTime.setMonth(monthOfYear);
eventTime.setDate(dayOfMonth);
dateButton.setText(DateUtil.dateString(eventTime));
updateBGforDateTime();
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
eventTime.setHours(hourOfDay);
eventTime.setMinutes(minute);
eventTime.setSeconds(this.seconds++); // randomize seconds to prevent creating record of the same time, if user choose time manually
timeButton.setText(dateUtil.timeString(eventTime));
updateBGforDateTime();
}
private JSONObject gatherData() {
String enteredBy = sp.getString("careportal_enteredby", "");
JSONObject data = new JSONObject();
try {
boolean allowZeroDuration = false;
data.put("created_at", DateUtil.toISOString(eventTime));
switch (options.eventType) {
case R.id.careportal_bgcheck:
data.put("eventType", CareportalEvent.BGCHECK);
break;
case R.id.careportal_announcement:
data.put("eventType", CareportalEvent.ANNOUNCEMENT);
data.put("isAnnouncement", true);
break;
case R.id.careportal_cgmsensorinsert:
data.put("eventType", CareportalEvent.SENSORCHANGE);
break;
case R.id.careportal_cgmsensorstart:
data.put("eventType", "Sensor Start");
break;
case R.id.careportal_combobolus:
data.put("splitNow", SafeParse.stringToDouble(editSplit.getText()));
data.put("splitExt", 100 - SafeParse.stringToDouble(editSplit.getText()));
data.put("eventType", CareportalEvent.COMBOBOLUS);
break;
case R.id.careportal_correctionbolus:
data.put("eventType", "Correction Bolus");
break;
case R.id.careportal_carbscorrection:
data.put("eventType", "Carb Correction");
break;
case R.id.careportal_exercise:
data.put("eventType", CareportalEvent.EXERCISE);
break;
case R.id.careportal_insulincartridgechange:
data.put("eventType", CareportalEvent.INSULINCHANGE);
break;
case R.id.careportal_pumpbatterychange:
data.put("eventType", CareportalEvent.PUMPBATTERYCHANGE);
break;
case R.id.careportal_mealbolus:
data.put("eventType", "Meal Bolus");
break;
case R.id.careportal_note:
data.put("eventType", CareportalEvent.NOTE);
break;
case R.id.careportal_profileswitch:
data.put("eventType", CareportalEvent.PROFILESWITCH);
allowZeroDuration = true;
break;
case R.id.careportal_pumpsitechange:
data.put("eventType", CareportalEvent.SITECHANGE);
break;
case R.id.careportal_question:
data.put("eventType", CareportalEvent.QUESTION);
break;
case R.id.careportal_snackbolus:
data.put("eventType", "Snack Bolus");
break;
case R.id.careportal_tempbasalstart:
data.put("eventType", CareportalEvent.TEMPBASAL);
break;
case R.id.careportal_tempbasalend:
data.put("eventType", CareportalEvent.TEMPBASAL);
break;
case R.id.careportal_openapsoffline:
data.put("eventType", CareportalEvent.OPENAPSOFFLINE);
break;
case R.id.careportal_temporarytarget:
data.put("eventType", CareportalEvent.TEMPORARYTARGET);
if (!reasonSpinner.getSelectedItem().toString().equals(""))
data.put("reason", reasonSpinner.getSelectedItem().toString());
if (SafeParse.stringToDouble(editTemptarget.getText()) != 0d) {
data.put("targetBottom", SafeParse.stringToDouble(editTemptarget.getText()));
data.put("targetTop", SafeParse.stringToDouble(editTemptarget.getText()));
}
allowZeroDuration = true;
break;
}
if (options.bg && SafeParse.stringToDouble(editBg.getText()) != 0d) {
data.put("glucose", SafeParse.stringToDouble(editBg.getText()));
if (meterRadioButton.isChecked()) data.put("glucoseType", "Finger");
if (sensorRadioButton.isChecked()) data.put("glucoseType", "Sensor");
if (otherRadioButton.isChecked()) data.put("glucoseType", "Manual");
}
if (SafeParse.stringToDouble(editCarbs.getText()) != 0d)
data.put("carbs", SafeParse.stringToDouble(editCarbs.getText()));
if (SafeParse.stringToDouble(editInsulin.getText()) != 0d)
data.put("insulin", SafeParse.stringToDouble(editInsulin.getText()));
if (allowZeroDuration || SafeParse.stringToDouble(editDuration.getText()) != 0d)
data.put("duration", SafeParse.stringToDouble(editDuration.getText()));
if (layoutPercent.getVisibility() != View.GONE)
data.put("percent", SafeParse.stringToDouble(editPercent.getText()));
if (layoutAbsolute.getVisibility() != View.GONE)
data.put("absolute", SafeParse.stringToDouble(editAbsolute.getText()));
if (options.profile && profileSpinner.getSelectedItem() != null)
data.put("profile", profileSpinner.getSelectedItem().toString());
if (options.profile)
data.put("percentage", SafeParse.stringToInt(editPercentage.getText()));
if (options.profile)
data.put("timeshift", SafeParse.stringToInt(editTimeshift.getText()));
if (SafeParse.stringToDouble(editCarbTime.getText()) != 0d)
data.put("preBolus", SafeParse.stringToDouble(editCarbTime.getText()));
if (!notesEdit.getText().toString().equals(""))
data.put("notes", notesEdit.getText().toString());
data.put("units", profileFunction.getUnits());
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
if (options.eventType == R.id.careportal_combobolus) {
Double enteredInsulin = SafeParse.stringToDouble(editInsulin.getText());
data.put("enteredinsulin", enteredInsulin);
data.put("insulin", enteredInsulin * SafeParse.stringToDouble(editSplit.getText()) / 100);
data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(editSplit.getText())) / 100 / SafeParse.stringToDouble(editDuration.getText()) * 60);
}
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
return data;
}
private String buildConfirmText(JSONObject data) {
String ret = "";
// if (data.has("eventType")) {
// ret += resourceHelper.gs(R.string.careportal_newnstreatment_eventtype);
// ret += ": ";
// ret += Translator.translate(JsonHelper.safeGetString(data, "eventType", ""));
// ret += "\n";
// }
if (data.has("glucose")) {
ret += resourceHelper.gs(R.string.treatments_wizard_bg_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "glucose", "");
ret += " " + profileFunction.getUnits() + "\n";
}
if (data.has("glucoseType")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype);
ret += ": ";
ret += translator.translate(JsonHelper.safeGetString(data, "glucoseType", ""));
ret += "\n";
}
if (data.has("carbs")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_carbs_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "carbs", "");
ret += " g\n";
}
if (data.has("insulin")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_insulin_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "insulin", "");
ret += " U\n";
}
if (data.has("duration")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_duration_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "duration", "");
ret += " min\n";
}
if (data.has("percent")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_percent_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "percent", "");
ret += " %\n";
}
if (data.has("absolute")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_absolute_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "absolute", "");
ret += " U/h\n";
}
if (data.has("preBolus")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_carbtime_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "preBolus", "");
ret += " min\n";
}
if (data.has("notes")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_notes_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "notes", "");
ret += "\n";
}
if (data.has("profile")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_profile_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "profile", "");
ret += "\n";
}
if (data.has("percentage")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_percentage_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "percentage", "");
ret += " %\n";
}
if (data.has("timeshift")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "timeshift", "");
ret += " h\n";
}
if (data.has("targetBottom") && data.has("targetTop")) {
ret += resourceHelper.gs(R.string.target_range);
ret += " ";
ret += JsonHelper.safeGetObject(data, "targetBottom", "");
ret += " - ";
ret += JsonHelper.safeGetObject(data, "targetTop", "");
ret += "\n";
}
if (data.has("created_at")) {
ret += resourceHelper.gs(R.string.event_time_label);
ret += ": ";
ret += dateUtil.dateAndTimeString(eventTime);
ret += "\n";
}
if (data.has("enteredBy")) {
ret += resourceHelper.gs(R.string.careportal_newnstreatment_enteredby_title);
ret += ": ";
ret += JsonHelper.safeGetObject(data, "enteredBy", "");
ret += "\n";
}
return ret;
}
private void confirmNSTreatmentCreation() {
final JSONObject data = gatherData();
OKDialog.showConfirmation(getContext(), translator.translate(JsonHelper.safeGetString(data, "eventType", resourceHelper.gs(R.string.overview_treatment_label))), buildConfirmText(data), () -> NSUpload.createNSTreatment(data, profileStore, profileFunction, eventTime.getTime()));
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("notesEdit", notesEdit.getText().toString());
savedInstanceState.putString("dateButton", dateButton.getText().toString());
savedInstanceState.putString("timeButton", timeButton.getText().toString());
savedInstanceState.putDouble("editBg", editBg.getValue());
savedInstanceState.putDouble("editCarbs", editCarbs.getValue());
savedInstanceState.putDouble("editInsulin", editInsulin.getValue());
savedInstanceState.putDouble("editDuration", editDuration.getValue());
savedInstanceState.putDouble("editPercent", editPercent.getValue());
savedInstanceState.putDouble("editAbsolute", editAbsolute.getValue());
savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue());
savedInstanceState.putDouble("editTemptarget", editTemptarget.getValue());
savedInstanceState.putDouble("editPercentage", editPercentage.getValue());
savedInstanceState.putDouble("editTimeshift", editTimeshift.getValue());
super.onSaveInstanceState(savedInstanceState);
}
}

View file

@ -1,81 +0,0 @@
package info.nightscout.androidaps.plugins.general.careportal;
/**
* Created by mike on 05.11.2016.
*/
public class OptionsToShow {
public int eventType;
public int eventName;
public boolean date;
public boolean bg;
public boolean insulin;
public boolean carbs;
public boolean prebolus;
public boolean duration;
public boolean percent;
public boolean absolute;
public boolean profile;
public boolean split;
public boolean tempTarget;
public OptionsToShow(int eventType, int eventName) {
this.eventType = eventType;
this.eventName = eventName;
}
public OptionsToShow date() {
date = true;
return this;
}
public OptionsToShow bg() {
bg = true;
return this;
}
public OptionsToShow insulin() {
insulin = true;
return this;
}
public OptionsToShow carbs() {
carbs = true;
return this;
}
public OptionsToShow prebolus() {
prebolus = true;
return this;
}
public OptionsToShow duration() {
duration = true;
return this;
}
public OptionsToShow percent() {
percent = true;
return this;
}
public OptionsToShow absolute() {
absolute = true;
return this;
}
public OptionsToShow profile() {
profile = true;
return this;
}
public OptionsToShow split() {
split = true;
return this;
}
public OptionsToShow tempTarget() {
tempTarget = true;
return this;
}
}

View file

@ -35,6 +35,7 @@ class FoodFragment : DaggerFragment() {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var foodPlugin: FoodPlugin
@Inject lateinit var nsUpload: NSUpload
private val disposable = CompositeDisposable()
private lateinit var unfiltered: List<Food>
@ -200,7 +201,7 @@ class FoodFragment : DaggerFragment() {
activity?.let { activity ->
showConfirmation(activity, resourceHelper.gs(R.string.confirmation), resourceHelper.gs(R.string.removerecord) + "\n" + food.name, DialogInterface.OnClickListener { _: DialogInterface?, _: Int ->
if (food._id != null && food._id != "") {
NSUpload.removeFoodFromNS(food._id)
nsUpload.removeFoodFromNS(food._id)
}
foodPlugin.service?.delete(food)
}, null)

View file

@ -28,6 +28,6 @@ class FoodPlugin @Inject constructor(
override fun onStart() {
super.onStart()
service = FoodService()
service = FoodService(injector)
}
}

View file

@ -15,7 +15,6 @@ import com.j256.ormlite.table.TableUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.sql.SQLException;
import java.util.ArrayList;
@ -25,15 +24,17 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ICallback;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.utils.FabricPrivacy;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
@ -43,16 +44,20 @@ import io.reactivex.schedulers.Schedulers;
*/
public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
private Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATAFOOD);
@Inject AAPSLogger aapsLogger;
@Inject RxBusWrapper rxBus;
@Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledFoodEventPost = null;
public FoodService() {
public FoodService(HasAndroidInjector injector) {
injector.androidInjector().inject(this);
onCreate();
dbInitialize();
disposable.add(RxBus.Companion.getINSTANCE()
disposable.add(rxBus
.toObservable(EventNsFood.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
@ -62,7 +67,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
this.createFoodFromJsonIfNotExists(array);
else
this.deleteNS(array);
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
}
@ -88,7 +93,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
try {
return DaoManager.createDao(this.getConnectionSource(), Food.class);
} catch (SQLException e) {
log.error("Cannot create Dao for Food.class");
aapsLogger.error("Cannot create Dao for Food.class");
}
return null;
@ -98,18 +103,16 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void onCreate() {
super.onCreate();
try {
if (L.isEnabled(LTag.DATAFOOD))
log.info("onCreate");
aapsLogger.info(LTag.DATAFOOD, "onCreate");
TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class);
} catch (SQLException e) {
log.error("Can't create database", e);
aapsLogger.error("Can't create database", e);
throw new RuntimeException(e);
}
}
public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) {
if (L.isEnabled(LTag.DATAFOOD))
log.info("onUpgrade");
aapsLogger.info(LTag.DATAFOOD, "onUpgrade");
// this.resetFood();
}
@ -122,7 +125,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
TableUtils.dropTable(this.getConnectionSource(), Food.class, true);
TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class);
} catch (SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
scheduleFoodChange();
}
@ -147,9 +150,8 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(LTag.DATAFOOD))
log.debug("Firing EventFoodChange");
RxBus.Companion.getINSTANCE().send(event);
aapsLogger.debug(LTag.DATAFOOD, "Firing EventFoodChange");
rxBus.send(event);
callback.setPost(null);
}
}
@ -183,7 +185,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
try {
return this.getDao().queryForAll();
} catch (SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return new ArrayList<>();
@ -208,7 +210,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
Food food = Food.createFromJson(json);
this.createFoodFromJsonIfNotExists(food);
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -220,7 +222,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
this.createFoodFromJsonIfNotExists(food);
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -233,7 +235,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
String _id = json.getString("_id");
this.deleteByNSId(_id);
} catch (JSONException | SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -244,7 +246,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
this.deleteNS(json);
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -258,8 +260,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void deleteByNSId(String _id) throws SQLException {
Food stored = this.findByNSId(_id);
if (stored != null) {
if (L.isEnabled(LTag.DATAFOOD))
log.debug("Removing Food record from database: " + stored.toString());
aapsLogger.debug(LTag.DATAFOOD, "Removing Food record from database: " + stored.toString());
this.delete(stored);
}
}
@ -276,7 +277,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
this.getDao().delete(food);
this.scheduleFoodChange();
} catch (SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -312,10 +313,9 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void createOrUpdate(Food food) {
try {
this.getDao().createOrUpdate(food);
if (L.isEnabled(LTag.DATAFOOD))
log.debug("Created or Updated: " + food.toString());
aapsLogger.debug(LTag.DATAFOOD, "Created or Updated: " + food.toString());
} catch (SQLException e) {
log.error("Unable to createOrUpdate Food", e);
aapsLogger.error("Unable to createOrUpdate Food", e);
}
this.scheduleFoodChange();
}
@ -323,10 +323,9 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
public void create(Food food) {
try {
this.getDao().create(food);
if (L.isEnabled(LTag.DATAFOOD))
log.debug("New record: " + food.toString());
aapsLogger.debug(LTag.DATAFOOD, "New record: " + food.toString());
} catch (SQLException e) {
log.error("Unable to create Food", e);
aapsLogger.error("Unable to create Food", e);
}
this.scheduleFoodChange();
}
@ -346,7 +345,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
return list.get(0);
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return null;
}

View file

@ -20,7 +20,6 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.maintenance.formats.*
import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePassword
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog

View file

@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.general.maintenance.formats
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.CryptoUtil
import info.nightscout.androidaps.utils.hexStringToByteArray
import info.nightscout.androidaps.utils.extensions.hexStringToByteArray
import info.nightscout.androidaps.utils.extensions.toHex
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.storage.Storage
import info.nightscout.androidaps.utils.toHex
import org.json.JSONException
import org.json.JSONObject
import java.io.File
@ -55,13 +55,13 @@ class EncryptedPrefsFormat @Inject constructor(
for ((metaKey, metaEntry) in prefs.metadata) {
if (metaKey == PrefsMetadataKey.FILE_FORMAT)
continue;
continue
if (metaKey == PrefsMetadataKey.ENCRYPTION)
continue;
continue
meta.put(metaKey.key, metaEntry.value)
}
container.put(PrefsMetadataKey.FILE_FORMAT.key, if (encrypted) FORMAT_KEY_ENC else FORMAT_KEY_NOENC);
container.put(PrefsMetadataKey.FILE_FORMAT.key, if (encrypted) FORMAT_KEY_ENC else FORMAT_KEY_NOENC)
container.put("metadata", meta)
val security = JSONObject()

View file

@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientN
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HtmlHelper;
import info.nightscout.androidaps.utils.alertDialogs.OKDialog;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -33,6 +34,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
@Inject SP sp;
@Inject ResourceHelper resourceHelper;
@Inject RxBusWrapper rxBus;
@Inject UploadQueue uploadQueue;
@Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable();
@ -119,13 +121,13 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
break;
case R.id.nsclientinternal_clearqueue:
OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.nsclientinternal), resourceHelper.gs(R.string.clearqueueconfirm), () -> {
UploadQueue.clearQueue();
uploadQueue.clearQueue();
updateGui();
fabricPrivacy.logCustom("NSClientClearQueue");
});
break;
case R.id.nsclientinternal_showqueue:
rxBus.send(new EventNSClientNewLog("QUEUE", nsClientPlugin.queue().textList()));
rxBus.send(new EventNSClientNewLog("QUEUE", uploadQueue.textList()));
break;
}
}
@ -154,7 +156,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
}
urlTextView.setText(nsClientPlugin.url());
Spanned queuetext = Html.fromHtml(resourceHelper.gs(R.string.queue) + " <b>" + UploadQueue.size() + "</b>");
Spanned queuetext = HtmlHelper.INSTANCE.fromHtml(resourceHelper.gs(R.string.queue) + " <b>" + uploadQueue.size() + "</b>");
queueTextView.setText(queuetext);
statusTextView.setText(nsClientPlugin.status);
}

View file

@ -7,7 +7,6 @@ import android.content.ServiceConnection;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.text.Html;
import android.text.Spanned;
import androidx.preference.PreferenceFragmentCompat;
@ -42,6 +41,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientS
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.HtmlHelper;
import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -56,13 +56,14 @@ public class NSClientPlugin extends PluginBase {
private final RxBusWrapper rxBus;
private final ResourceHelper resourceHelper;
private final Context context;
private final FabricPrivacy fabricPrivacy;
private final SP sp;
private final Config config;
public Handler handler;
private final List<EventNSClientNewLog> listLog = new ArrayList<>();
Spanned textLog = Html.fromHtml("");
Spanned textLog = HtmlHelper.INSTANCE.fromHtml("");
public boolean paused;
boolean autoscroll;
@ -80,6 +81,7 @@ public class NSClientPlugin extends PluginBase {
RxBusWrapper rxBus,
ResourceHelper resourceHelper,
Context context,
FabricPrivacy fabricPrivacy,
SP sp,
NsClientReceiverDelegate nsClientReceiverDelegate,
Config config
@ -98,6 +100,7 @@ public class NSClientPlugin extends PluginBase {
this.rxBus = rxBus;
this.resourceHelper = resourceHelper;
this.context = context;
this.fabricPrivacy = fabricPrivacy;
this.sp = sp;
this.nsClientReceiverDelegate = nsClientReceiverDelegate;
this.config = config;
@ -134,17 +137,17 @@ public class NSClientPlugin extends PluginBase {
.subscribe(event -> {
status = event.getStatus(resourceHelper);
rxBus.send(new EventNSClientUpdateGUI());
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventNetworkChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventPreferenceChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventAppExit.class)
@ -153,7 +156,7 @@ public class NSClientPlugin extends PluginBase {
if (nsClientService != null) {
context.unbindService(mConnection);
}
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventNSClientNewLog.class)
@ -161,17 +164,17 @@ public class NSClientPlugin extends PluginBase {
.subscribe(event -> {
addToLog(event);
aapsLogger.debug(LTag.NSCLIENT, event.getAction() + " " + event.getLogText());
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventChargingState.class)
.observeOn(Schedulers.io())
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventNSClientResend.class)
.observeOn(Schedulers.io())
.subscribe(event -> resend(event.getReason()), exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(event -> resend(event.getReason()), fabricPrivacy::logException)
);
}
@ -236,7 +239,7 @@ public class NSClientPlugin extends PluginBase {
newTextLog.append(log.toPreparedHtml());
}
}
textLog = Html.fromHtml(newTextLog.toString());
textLog = HtmlHelper.INSTANCE.fromHtml(newTextLog.toString());
} catch (OutOfMemoryError e) {
ToastUtils.showToastInUiThread(context, rxBus, "Out of memory!\nStop using this phone !!!", R.raw.error);
}
@ -253,10 +256,6 @@ public class NSClientPlugin extends PluginBase {
rxBus.send(new EventPreferenceChange(resourceHelper, R.string.key_nsclientinternal_paused));
}
public UploadQueue queue() {
return NSClientService.uploadQueue;
}
public String url() {
return NSClientService.nsURL;
}

View file

@ -8,70 +8,86 @@ import com.j256.ormlite.dao.CloseableIterator;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.sql.SQLException;
import info.nightscout.androidaps.MainApp;
import javax.inject.Inject;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.UploadQueueInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend;
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
/**
* Created by mike on 21.02.2016.
*/
public class UploadQueue {
private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT);
public class UploadQueue implements UploadQueueInterface {
private final AAPSLogger aapsLogger;
private final DatabaseHelperInterface databaseHelper;
private final Context context;
private final SP sp;
private final RxBusWrapper rxBus;
public static String status() {
return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS);
@Inject
public UploadQueue(
AAPSLogger aapsLogger,
DatabaseHelperInterface databaseHelper,
Context context,
SP sp,
RxBusWrapper rxBus
) {
this.aapsLogger = aapsLogger;
this.databaseHelper = databaseHelper;
this.context = context;
this.sp = sp;
this.rxBus = rxBus;
}
public static long size() {
return MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS);
public String status() {
return "QUEUE: " + databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS);
}
private static void startService() {
public long size() {
return databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS);
}
private void startService() {
if (NSClientService.handler == null) {
Context context = MainApp.instance();
context.startService(new Intent(context, NSClientService.class));
SystemClock.sleep(2000);
}
}
public static void add(final DbRequest dbr) {
if (SP.getBoolean(R.string.key_ns_noupload, false)) return;
if (L.isEnabled(LTag.NSCLIENT))
log.debug("Adding to queue: " + dbr.log());
public void add(final DbRequest dbr) {
if (sp.getBoolean(R.string.key_ns_noupload, false)) return;
aapsLogger.debug(LTag.NSCLIENT, "Adding to queue: " + dbr.log());
try {
MainApp.getDbHelper().create(dbr);
databaseHelper.create(dbr);
} catch (Exception e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
RxBus.getINSTANCE().send(new EventNSClientResend("newdata"));
rxBus.send(new EventNSClientResend("newdata"));
}
static void clearQueue() {
void clearQueue() {
startService();
if (NSClientService.handler != null) {
NSClientService.handler.post(() -> {
if (L.isEnabled(LTag.NSCLIENT))
log.debug("ClearQueue");
MainApp.getDbHelper().deleteAllDbRequests();
if (L.isEnabled(LTag.NSCLIENT))
log.debug(status());
aapsLogger.debug(LTag.NSCLIENT, "ClearQueue");
databaseHelper.deleteAllDbRequests();
aapsLogger.debug(LTag.NSCLIENT, status());
});
}
}
public static void removeID(final JSONObject record) {
public void removeID(final JSONObject record) {
startService();
if (NSClientService.handler != null) {
NSClientService.handler.post(() -> {
@ -82,26 +98,24 @@ public class UploadQueue {
} else {
return;
}
if (MainApp.getDbHelper().deleteDbRequest(id) == 1) {
if (L.isEnabled(LTag.NSCLIENT))
log.debug("Removed item from UploadQueue. " + UploadQueue.status());
if (databaseHelper.deleteDbRequest(id) == 1) {
aapsLogger.debug(LTag.NSCLIENT, "Removed item from UploadQueue. " + status());
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
});
}
}
public static void removeID(final String action, final String _id) {
public void removeID(final String action, final String _id) {
if (_id == null || _id.equals(""))
return;
startService();
if (NSClientService.handler != null) {
NSClientService.handler.post(() -> {
MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id);
if (L.isEnabled(LTag.NSCLIENT))
log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status());
databaseHelper.deleteDbRequestbyMongoId(action, _id);
aapsLogger.debug(LTag.NSCLIENT, "Removing " + _id + " from UploadQueue. " + status());
});
}
}
@ -110,7 +124,7 @@ public class UploadQueue {
String result = "";
CloseableIterator<DbRequest> iterator;
try {
iterator = MainApp.getDbHelper().getDbRequestInterator();
iterator = databaseHelper.getDbRequestInterator();
try {
while (iterator.hasNext()) {
DbRequest dbr = iterator.next();
@ -123,7 +137,7 @@ public class UploadQueue {
iterator.close();
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
return result;
}

View file

@ -2,13 +2,11 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
import io.socket.client.Ack;
@ -16,16 +14,23 @@ import io.socket.client.Ack;
* Created by mike on 29.12.2015.
*/
public class NSAddAck extends Event implements Ack {
private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT);
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
public String _id = null;
public String nsClientID = null;
public JSONObject json = null;
public NSAddAck(AAPSLogger aapsLogger, RxBusWrapper rxBus) {
this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
}
public void call(Object... args) {
// Regular response
try {
JSONArray responsearray = (JSONArray) (args[0]);
JSONObject response = null;
JSONObject response;
if (responsearray.length() > 0) {
response = responsearray.getJSONObject(0);
_id = response.getString("_id");
@ -34,10 +39,10 @@ public class NSAddAck extends Event implements Ack {
nsClientID = response.getString("NSCLIENT_ID");
}
}
RxBus.Companion.getINSTANCE().send(this);
rxBus.send(this);
return;
} catch (Exception e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
// Check for not authorized
try {
@ -45,15 +50,13 @@ public class NSAddAck extends Event implements Ack {
if (response.has("result")) {
_id = null;
if (response.getString("result").contains("Not")) {
RxBus.Companion.getINSTANCE().send(new EventNSClientRestart());
rxBus.send(new EventNSClientRestart());
return;
}
if (L.isEnabled(LTag.NSCLIENT))
log.debug("DBACCESS " + response.getString("result"));
aapsLogger.debug(LTag.NSCLIENT, "DBACCESS " + response.getString("result"));
}
return;
} catch (Exception e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
}

View file

@ -3,19 +3,26 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONObject;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import io.socket.client.Ack;
public class NSAuthAck extends Event implements Ack{
public class NSAuthAck extends Event implements Ack {
private final RxBusWrapper rxBus;
public boolean read = false;
public boolean write = false;
public boolean write_treatment = false;
public void call(Object...args) {
JSONObject response = (JSONObject)args[0];
public NSAuthAck(RxBusWrapper rxBus) {
this.rxBus = rxBus;
}
public void call(Object... args) {
JSONObject response = (JSONObject) args[0];
read = response.optBoolean("read");
write = response.optBoolean("write");
write_treatment = response.optBoolean("write_treatment");
RxBus.Companion.getINSTANCE().send(this);
rxBus.send(this);
}
}

View file

@ -2,19 +2,20 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import io.socket.client.Ack;
/**
* Created by mike on 21.02.2016.
*/
public class NSUpdateAck extends Event implements Ack {
private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT);
private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus;
public boolean result = false;
public String _id;
public String action;
@ -27,17 +28,19 @@ public class NSUpdateAck extends Event implements Ack {
result = true;
else if (response.getString("result").equals("Missing _id")) {
result = true;
log.debug("Internal error: Missing _id returned on dbUpdate ack");
aapsLogger.debug(LTag.NSCLIENT, "Internal error: Missing _id returned on dbUpdate ack");
}
RxBus.Companion.getINSTANCE().send(this);
rxBus.send(this);
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
public NSUpdateAck(String action, String _id) {
public NSUpdateAck(String action, String _id, AAPSLogger aapsLogger, RxBusWrapper rxBus) {
super();
this.action = action;
this._id = _id;
this.aapsLogger = aapsLogger;
this.rxBus = rxBus;
}
}

View file

@ -20,6 +20,7 @@ import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.HtmlHelper;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -158,7 +159,7 @@ public class NSDeviceStatus {
public Spanned getExtendedPumpStatus() {
if (deviceStatusPumpData != null && deviceStatusPumpData.extended != null)
return deviceStatusPumpData.extended;
return Html.fromHtml("");
return HtmlHelper.INSTANCE.fromHtml("");
}
public Spanned getPumpStatus() {
@ -170,7 +171,7 @@ public class NSDeviceStatus {
string.append(": </span>");
if (deviceStatusPumpData == null)
return Html.fromHtml("");
return HtmlHelper.INSTANCE.fromHtml("");
// test warning level
int level = Levels.INFO;
@ -225,7 +226,7 @@ public class NSDeviceStatus {
string.append("</span>"); // color
return Html.fromHtml(string.toString());
return HtmlHelper.INSTANCE.fromHtml(string.toString());
}
static class DeviceStatusPumpData {
@ -273,7 +274,7 @@ public class NSDeviceStatus {
String value = extendedJson.getString(key);
exteneded.append("<b>").append(key).append(":</b> ").append(value).append("<br>");
}
deviceStatusPumpData.extended = Html.fromHtml(exteneded.toString());
deviceStatusPumpData.extended = HtmlHelper.INSTANCE.fromHtml(exteneded.toString());
}
} catch (Exception e) {
aapsLogger.error("Unhandled exception", e);
@ -345,7 +346,7 @@ public class NSDeviceStatus {
}
string.append("</span>"); // color
return Html.fromHtml(string.toString());
return HtmlHelper.INSTANCE.fromHtml(string.toString());
}
public static long getOpenApsTimestamp() {
@ -365,11 +366,11 @@ public class NSDeviceStatus {
string.append("<b>").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append("</b> ").append(deviceStatusOpenAPSData.enacted.getString("reason")).append("<br>");
if (deviceStatusOpenAPSData.suggested != null)
string.append("<b>").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append("</b> ").append(deviceStatusOpenAPSData.suggested.getString("reason")).append("<br>");
return Html.fromHtml(string.toString());
return HtmlHelper.INSTANCE.fromHtml(string.toString());
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
return Html.fromHtml("");
return HtmlHelper.INSTANCE.fromHtml("");
}
// ********* Uploader data ***********
@ -441,7 +442,7 @@ public class NSDeviceStatus {
string.append(minBattery);
string.append("%");
return Html.fromHtml(string.toString());
return HtmlHelper.INSTANCE.fromHtml(string.toString());
}
public Spanned getExtendedUploaderStatus() {
@ -455,7 +456,7 @@ public class NSDeviceStatus {
string.append("<b>").append(device).append(":</b> ").append(uploader.battery).append("%<br>");
}
return Html.fromHtml(string.toString());
return HtmlHelper.INSTANCE.fromHtml(string.toString());
}
public static APSResult getAPSResult(HasAndroidInjector injector) {

View file

@ -19,7 +19,6 @@ import com.j256.ormlite.dao.CloseableIterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.net.URISyntaxException;
import java.sql.SQLException;
@ -31,19 +30,17 @@ import javax.inject.Inject;
import dagger.android.DaggerService;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.db.DbRequest;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
@ -83,16 +80,17 @@ public class NSClientService extends DaggerService {
@Inject AAPSLogger aapsLogger;
@Inject NSSettingsStatus nsSettingsStatus;
@Inject NSDeviceStatus nsDeviceStatus;
@Inject MainApp mainApp;
@Inject DatabaseHelperInterface databaseHelper;
@Inject RxBusWrapper rxBus;
@Inject ResourceHelper resourceHelper;
@Inject SP sp;
@Inject FabricPrivacy fabricPrivacy;
@Inject NSClientPlugin nsClientPlugin;
@Inject BuildHelper buildHelper;
@Inject Config config;
@Inject DateUtil dateUtil;
@Inject UploadQueue uploadQueue;
private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT);
private CompositeDisposable disposable = new CompositeDisposable();
static public PowerManager.WakeLock mWakeLock;
@ -124,8 +122,6 @@ public class NSClientService extends DaggerService {
private String nsAPIhashCode = "";
public static UploadQueue uploadQueue = new UploadQueue();
private final ArrayList<Long> reconnections = new ArrayList<>();
private int WATCHDOG_INTERVAL_MINUTES = 2;
private int WATCHDOG_RECONNECT_IN = 15;
@ -143,7 +139,7 @@ public class NSClientService extends DaggerService {
@Override
public void onCreate() {
super.onCreate();
PowerManager powerManager = (PowerManager) mainApp.getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService");
mWakeLock.acquire();
@ -158,7 +154,7 @@ public class NSClientService extends DaggerService {
destroy();
initialize();
}
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventPreferenceChange.class)
@ -172,17 +168,16 @@ public class NSClientService extends DaggerService {
destroy();
initialize();
}
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventAppExit.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
if (L.isEnabled(LTag.NSCLIENT))
log.debug("EventAppExit received");
aapsLogger.debug(LTag.NSCLIENT, "EventAppExit received");
destroy();
stopSelf();
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(EventNSClientRestart.class)
@ -190,22 +185,22 @@ public class NSClientService extends DaggerService {
.subscribe(event -> {
latestDateInReceivedData = 0;
restart();
}, exception -> FabricPrivacy.getInstance().logException(exception))
}, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(NSAuthAck.class)
.observeOn(Schedulers.io())
.subscribe(this::processAuthAck, exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(this::processAuthAck, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(NSUpdateAck.class)
.observeOn(Schedulers.io())
.subscribe(this::processUpdateAck, exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(this::processUpdateAck, fabricPrivacy::logException)
);
disposable.add(rxBus
.toObservable(NSAddAck.class)
.observeOn(Schedulers.io())
.subscribe(this::processAddAck, exception -> FabricPrivacy.getInstance().logException(exception))
.subscribe(this::processAddAck, fabricPrivacy::logException)
);
}
@ -275,6 +270,7 @@ public class NSClientService extends DaggerService {
return START_STICKY;
}
@SuppressWarnings("deprecation")
public void initialize() {
dataCounter = 0;
@ -333,7 +329,7 @@ public class NSClientService extends DaggerService {
String socketId = mSocket != null ? mSocket.id() : "NULL";
rxBus.send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId));
if (mSocket != null)
sendAuthMessage(new NSAuthAck());
sendAuthMessage(new NSAuthAck(rxBus));
watchdog();
}
};
@ -367,8 +363,7 @@ public class NSClientService extends DaggerService {
private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
if (L.isEnabled(LTag.NSCLIENT))
log.debug("disconnect reason: {}", args);
aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: {}", args);
rxBus.send(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
}
};
@ -402,7 +397,7 @@ public class NSClientService extends DaggerService {
authMessage.put("from", latestDateInReceivedData); // send data newer than
authMessage.put("secret", nsAPIhashCode);
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
return;
}
rxBus.send(new EventNSClientNewLog("AUTH", "requesting auth"));
@ -456,8 +451,7 @@ public class NSClientService extends DaggerService {
data = (JSONObject) args[0];
handleAnnouncement(data);
} catch (Exception e) {
log.error("Unhandled exception", e);
return;
aapsLogger.error("Unhandled exception", e);
}
}
};
@ -483,8 +477,7 @@ public class NSClientService extends DaggerService {
data = (JSONObject) args[0];
handleAlarm(data);
} catch (Exception e) {
log.error("Unhandled exception", e);
return;
aapsLogger.error("Unhandled exception", e);
}
}
};
@ -495,7 +488,7 @@ public class NSClientService extends DaggerService {
data = (JSONObject) args[0];
handleUrgentAlarm(data);
} catch (Exception e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
};
@ -518,8 +511,7 @@ public class NSClientService extends DaggerService {
rxBus.send(new EventDismissNotification(Notification.NSURGENTALARM));
aapsLogger.debug(LTag.NSCLIENT, data.toString());
} catch (Exception e) {
log.error("Unhandled exception", e);
return;
aapsLogger.error("Unhandled exception", e);
}
}
};
@ -528,7 +520,7 @@ public class NSClientService extends DaggerService {
@Override
public void call(final Object... args) {
NSClientService.handler.post(() -> {
PowerManager powerManager = (PowerManager) mainApp.getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"AndroidAPS:NSClientService_onDataUpdate");
wakeLock.acquire();
@ -604,7 +596,7 @@ public class NSClientService extends DaggerService {
NSTreatment treatment = new NSTreatment(jsonTreatment);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonTreatment);
uploadQueue.removeID(jsonTreatment);
//Find latest date in treatment
if (treatment.getMills() != null && treatment.getMills() < System.currentTimeMillis())
if (treatment.getMills() > latestDateInReceivedData)
@ -636,7 +628,7 @@ public class NSClientService extends DaggerService {
for (Integer index = 0; index < devicestatuses.length(); index++) {
JSONObject jsonStatus = devicestatuses.getJSONObject(index);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonStatus);
uploadQueue.removeID(jsonStatus);
}
nsDeviceStatus.handleNewData(devicestatuses);
}
@ -652,7 +644,7 @@ public class NSClientService extends DaggerService {
JSONObject jsonFood = foods.getJSONObject(index);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonFood);
uploadQueue.removeID(jsonFood);
String action = JsonHelper.safeGetString(jsonFood, "action");
@ -684,7 +676,7 @@ public class NSClientService extends DaggerService {
for (Integer index = 0; index < mbgs.length(); index++) {
JSONObject jsonMbg = mbgs.getJSONObject(index);
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonMbg);
uploadQueue.removeID(jsonMbg);
}
handleNewMbg(mbgs, isDelta);
}
@ -695,7 +687,7 @@ public class NSClientService extends DaggerService {
// Retreive actual calibration
for (Integer index = 0; index < cals.length(); index++) {
// remove from upload queue if Ack is failing
UploadQueue.removeID(cals.optJSONObject(index));
uploadQueue.removeID(cals.optJSONObject(index));
}
handleNewCal(cals, isDelta);
}
@ -709,7 +701,7 @@ public class NSClientService extends DaggerService {
NSSgv sgv = new NSSgv(jsonSgv);
// Handle new sgv here
// remove from upload queue if Ack is failing
UploadQueue.removeID(jsonSgv);
uploadQueue.removeID(jsonSgv);
//Find latest date in sgv
if (sgv.getMills() != null && sgv.getMills() < System.currentTimeMillis())
if (sgv.getMills() > latestDateInReceivedData)
@ -724,7 +716,7 @@ public class NSClientService extends DaggerService {
}
rxBus.send(new EventNSClientNewLog("LAST", dateUtil.dateAndTimeString(latestDateInReceivedData)));
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
//rxBus.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
} finally {
@ -744,7 +736,7 @@ public class NSClientService extends DaggerService {
mSocket.emit("dbUpdate", message, ack);
rxBus.send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -758,7 +750,7 @@ public class NSClientService extends DaggerService {
mSocket.emit("dbUpdateUnset", message, ack);
rxBus.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -771,7 +763,7 @@ public class NSClientService extends DaggerService {
mSocket.emit("dbRemove", message, ack);
rxBus.send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -784,7 +776,7 @@ public class NSClientService extends DaggerService {
mSocket.emit("dbAdd", message, ack);
rxBus.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID));
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
}
@ -795,7 +787,7 @@ public class NSClientService extends DaggerService {
}
public void resend(final String reason) {
if (UploadQueue.size() == 0)
if (uploadQueue.size() == 0)
return;
if (!isConnected || !hasWriteAuth) return;
@ -804,8 +796,7 @@ public class NSClientService extends DaggerService {
if (mSocket == null || !mSocket.connected()) return;
if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) {
if (L.isEnabled(LTag.NSCLIENT))
log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec");
aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec");
return;
}
lastResendTime = System.currentTimeMillis();
@ -815,21 +806,21 @@ public class NSClientService extends DaggerService {
CloseableIterator<DbRequest> iterator;
int maxcount = 30;
try {
iterator = mainApp.getDbHelper().getDbRequestInterator();
iterator = databaseHelper.getDbRequestInterator();
try {
while (iterator.hasNext() && maxcount > 0) {
DbRequest dbr = iterator.next();
if (dbr.action.equals("dbAdd")) {
NSAddAck addAck = new NSAddAck();
NSAddAck addAck = new NSAddAck(aapsLogger, rxBus);
dbAdd(dbr, addAck);
} else if (dbr.action.equals("dbRemove")) {
NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id);
NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus);
dbRemove(dbr, removeAck);
} else if (dbr.action.equals("dbUpdate")) {
NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id);
NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus);
dbUpdate(dbr, updateAck);
} else if (dbr.action.equals("dbUpdateUnset")) {
NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id);
NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus);
dbUpdateUnset(dbr, updateUnsetAck);
}
maxcount--;
@ -838,7 +829,7 @@ public class NSClientService extends DaggerService {
iterator.close();
}
} catch (SQLException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
}
rxBus.send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason));
@ -852,7 +843,7 @@ public class NSClientService extends DaggerService {
private void handleAnnouncement(JSONObject announcement) {
NSAlarm nsAlarm = new NSAlarm(announcement);
Notification notification = new NotificationWithAction(mainApp, nsAlarm);
Notification notification = new NotificationWithAction(injector, nsAlarm);
rxBus.send(new EventNewNotification(notification));
rxBus.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(announcement, "message", "received")));
aapsLogger.debug(LTag.NSCLIENT, announcement.toString());
@ -862,7 +853,7 @@ public class NSClientService extends DaggerService {
long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L);
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
NSAlarm nsAlarm = new NSAlarm(alarm);
Notification notification = new NotificationWithAction(mainApp, nsAlarm);
Notification notification = new NotificationWithAction(injector, nsAlarm);
rxBus.send(new EventNewNotification(notification));
}
rxBus.send(new EventNSClientNewLog("ALARM", JsonHelper.safeGetString(alarm, "message", "received")));
@ -873,7 +864,7 @@ public class NSClientService extends DaggerService {
long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L);
if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) {
NSAlarm nsAlarm = new NSAlarm(alarm);
Notification notification = new NotificationWithAction(mainApp, nsAlarm);
Notification notification = new NotificationWithAction(injector, nsAlarm);
rxBus.send(new EventNewNotification(notification));
}
rxBus.send(new EventNSClientNewLog("URGENTALARM", JsonHelper.safeGetString(alarm, "message", "received")));
@ -887,7 +878,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_CAL);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
public void handleNewMbg(JSONArray mbgs, boolean isDelta) {
@ -897,7 +888,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_MBG);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
public void handleNewProfile(ProfileStore profile, boolean isDelta) {
@ -907,7 +898,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_PROFILE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
bundle = new Bundle();
@ -916,7 +907,7 @@ public class NSClientService extends DaggerService {
intent = new Intent(Intents.ACTION_NEW_PROFILE);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
mainApp.sendBroadcast(intent);
this.sendBroadcast(intent);
}
}
@ -929,7 +920,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
@ -940,7 +931,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_SGV);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
mainApp.sendBroadcast(intent);
this.sendBroadcast(intent);
}
}
}
@ -954,7 +945,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
@ -966,7 +957,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
mainApp.getApplicationContext().sendBroadcast(intent);
this.getApplicationContext().sendBroadcast(intent);
}
}
}
@ -980,7 +971,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
@ -992,7 +983,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
mainApp.getApplicationContext().sendBroadcast(intent);
this.getApplicationContext().sendBroadcast(intent);
}
}
}
@ -1004,7 +995,7 @@ public class NSClientService extends DaggerService {
Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) {
@ -1014,7 +1005,7 @@ public class NSClientService extends DaggerService {
intent = new Intent(Intents.ACTION_REMOVED_TREATMENT);
intent.putExtras(bundle);
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
mainApp.getApplicationContext().sendBroadcast(intent);
this.getApplicationContext().sendBroadcast(intent);
}
}
@ -1040,7 +1031,7 @@ public class NSClientService extends DaggerService {
ret.add(newarr);
}
} catch (JSONException e) {
log.error("Unhandled exception", e);
aapsLogger.error("Unhandled exception", e);
ret = new ArrayList<>();
ret.add(array);
}

View file

@ -21,6 +21,7 @@ import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.text.toSpanned
import androidx.recyclerview.widget.LinearLayoutManager
import com.jjoe64.graphview.GraphView
import dagger.android.HasAndroidInjector
@ -351,8 +352,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
if (loopPlugin.isEnabled(PluginType.LOOP)) {
val lastRun = loopPlugin.lastRun
loopPlugin.invoke("Accept temp button", false)
if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed.isChangeRequested) {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), lastRun.constraintsProcessed.toSpanned(), Runnable {
if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) {
OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned()
?: "".toSpanned(), Runnable {
aapsLogger.debug("USER ENTRY: ACCEPT TEMP BASAL")
overview_accepttempbutton?.visibility = View.GONE
(context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID)
@ -449,7 +451,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
val showAcceptButton = !closedLoopEnabled.value() && // Open mode needed
lastRun != null &&
(lastRun.lastOpenModeAccept == 0L || lastRun.lastOpenModeAccept < lastRun.lastAPSRun) &&// never accepted or before last result
lastRun.constraintsProcessed.isChangeRequested // change is requested
lastRun.constraintsProcessed?.isChangeRequested == true // change is requested
if (showAcceptButton && pump.isInitialized && !pump.isSuspended && loopPlugin.isEnabled(PluginType.LOOP)) {
overview_accepttempbutton?.visibility = View.VISIBLE
@ -669,9 +671,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
overview_basebasal?.text = activeTemp?.let { if (resourceHelper.shortTextMode()) "T:" + activeTemp.toStringVeryShort() else activeTemp.toStringFull() }
?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)
overview_basal_llayout?.setOnClickListener {
var fullText = "${resourceHelper.gs(R.string.pump_basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}"
var fullText = "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}"
if (activeTemp != null)
fullText += "\n" + resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull()
fullText += "\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + activeTemp.toStringFull()
activity?.let {
OKDialog.show(it, resourceHelper.gs(R.string.basal), fullText)
}

View file

@ -206,7 +206,7 @@ class OverviewMenus @Inject constructor(
R.id.overview_activeprofile -> {
menu.setHeaderTitle(resourceHelper.gs(R.string.profile))
menu.add(resourceHelper.gs(R.string.danar_viewprofile))
menu.add(resourceHelper.gs(R.string.viewprofile))
if (activePlugin.activeProfileInterface.profile != null) {
menu.add(resourceHelper.gs(R.string.careportal_profileswitch))
}
@ -352,7 +352,7 @@ class OverviewMenus @Inject constructor(
ProfileSwitchDialog().show(manager, "Overview")
}
resourceHelper.gs(R.string.danar_viewprofile) -> {
resourceHelper.gs(R.string.viewprofile) -> {
val args = Bundle()
args.putLong("time", DateUtil.now())
args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal)

View file

@ -16,10 +16,10 @@ import info.nightscout.androidaps.data.IobTotal
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.LoopInterface
import info.nightscout.androidaps.interfaces.TreatmentsInterface
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin.LastRun
import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.overview.graphExtensions.*
@ -197,7 +197,7 @@ class GraphData(injector: HasAndroidInjector, private val graph: GraphView, priv
basalScale.setMultiplier(maxY * scale / maxBasalValueFound)
}
fun addTargetLine(fromTime: Long, toTimeParam: Long, profile: Profile, lastRun: LastRun?) {
fun addTargetLine(fromTime: Long, toTimeParam: Long, profile: Profile, lastRun: LoopInterface.LastRun?) {
var toTime = toTimeParam
val targetsSeriesArray: MutableList<DataPoint> = ArrayList()
var lastTarget = -1.0

View file

@ -50,7 +50,7 @@ class DummyService : DaggerService() {
stopForeground(true)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
startForeground(notificationHolder.notificationID, notificationHolder.notification)
return Service.START_STICKY

View file

@ -14,7 +14,6 @@ import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainActivity
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.DatabaseHelper
import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger

View file

@ -7,6 +7,7 @@ import info.nightscout.androidaps.Config
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.CareportalEvent
@ -23,11 +24,10 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.danar.DanaRPlugin
import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.danars.DanaRSPlugin
import info.nightscout.androidaps.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin
import info.nightscout.androidaps.plugins.treatments.CarbsGenerator
import info.nightscout.androidaps.queue.Callback
@ -65,7 +65,7 @@ class ActionStringHandler @Inject constructor(
private val danaRKoreanPlugin: DanaRKoreanPlugin,
private val danaRv2Plugin: DanaRv2Plugin,
private val danaRSPlugin: DanaRSPlugin,
private val danaRPump: DanaRPump,
private val danaPump: DanaPump,
private val hardLimits: HardLimits,
private val carbsGenerator: CarbsGenerator,
private val dateUtil: DateUtil,
@ -326,7 +326,7 @@ class ActionStringHandler @Inject constructor(
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n"
message += "\n"
} else if (pump is DanaRPlugin) {
val tdd = danaRPump.dailyTotalUnits
val tdd = danaPump.dailyTotalUnits
message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n"
message += "\n"
}

View file

@ -104,7 +104,7 @@ class WearPlugin @Inject constructor(
.observeOn(Schedulers.io())
.subscribe({ event: EventDismissBolusProgressIfRunning ->
if (event.result == null) return@subscribe
val status: String = if (event.result.success) {
val status: String = if (event.result!!.success) {
resourceHelper.gs(R.string.success)
} else {
resourceHelper.gs(R.string.nosuccess)

View file

@ -531,9 +531,9 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
}
final LoopPlugin.LastRun finalLastRun = loopPlugin.lastRun;
if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.request.hasPredictions && finalLastRun.constraintsProcessed != null) {
List<BgReading> predArray = finalLastRun.constraintsProcessed.getPredictions();
final LoopPlugin.LastRun finalLastRun = loopPlugin.getLastRun();
if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().hasPredictions && finalLastRun.getConstraintsProcessed() != null) {
List<BgReading> predArray = finalLastRun.getConstraintsProcessed().getPredictions();
if (!predArray.isEmpty()) {
for (BgReading bg : predArray) {
@ -715,7 +715,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
//OpenAPS status
if (config.getAPS()) {
//we are AndroidAPS
openApsStatus = loopPlugin.lastRun != null && loopPlugin.lastRun.lastTBREnact != 0 ? loopPlugin.lastRun.lastTBREnact : -1;
openApsStatus = loopPlugin.getLastRun() != null && loopPlugin.getLastRun().getLastTBREnact() != 0 ? loopPlugin.getLastRun().getLastTBREnact() : -1;
} else {
//NSClient or remote
openApsStatus = NSDeviceStatus.getOpenApsTimestamp();

View file

@ -45,7 +45,7 @@ class LocalProfileFragment : DaggerFragment() {
private val save = Runnable {
doEdit()
basalView?.updateLabel(resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel())
basalView?.updateLabel(resourceHelper.gs(R.string.basal_label) + ": " + sumLabel())
}
private val textWatch = object : TextWatcher {
@ -106,14 +106,14 @@ class LocalProfileFragment : DaggerFragment() {
localprofile_name.addTextChangedListener(textWatch)
localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, hardLimits.MINDIA, hardLimits.MAXDIA, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch)
localprofile_dia.tag = "LP_DIA"
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label), localProfilePlugin.currentProfile().ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save)
basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.ic_label), localProfilePlugin.currentProfile().ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save)
basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save)
if (units == Constants.MGDL) {
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label), localProfilePlugin.currentProfile().isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save)
} else {
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save)
}
// Spinner
@ -190,10 +190,10 @@ class LocalProfileFragment : DaggerFragment() {
localprofile_units.text = resourceHelper.gs(R.string.units_colon) + " " + (if (localProfilePlugin.currentProfile().mgdl) resourceHelper.gs(R.string.mgdl) else resourceHelper.gs(R.string.mmol))
localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, MIN_DIA, 12.0, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch)
localprofile_dia.tag = "LP_DIA"
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label) + ":", localProfilePlugin.currentProfile().ic, null, 0.5, 50.0, 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label) + ":", localProfilePlugin.currentProfile().isf, null, 0.5, 500.0, 0.1, DecimalFormat("0.0"), save)
basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label) + ":", localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, 3.0, 200.0, 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.ic_label) + ":", localProfilePlugin.currentProfile().ic, null, 0.5, 50.0, 0.1, DecimalFormat("0.0"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label) + ":", localProfilePlugin.currentProfile().isf, null, 0.5, 500.0, 0.1, DecimalFormat("0.0"), save)
basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save)
TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label) + ":", localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, 3.0, 200.0, 0.1, DecimalFormat("0.0"), save)
updateGUI()
}

View file

@ -37,7 +37,8 @@ class LocalProfilePlugin @Inject constructor(
private val rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
private val sp: SP,
private val profileFunction: ProfileFunction
private val profileFunction: ProfileFunction,
private val nsUpload: NSUpload
) : PluginBase(PluginDescription()
.mainType(PluginType.PROFILE)
.fragmentClass(LocalProfileFragment::class.java.name)
@ -140,7 +141,7 @@ class LocalProfilePlugin @Inject constructor(
if (name.contains(".")) namesOK = false
}
if (namesOK)
rawProfile?.let { NSUpload.uploadProfileStore(it.data) }
rawProfile?.let { nsUpload.uploadProfileStore(it.data) }
else
activity?.let {
OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot))

View file

@ -485,7 +485,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
getAapsLogger().error("deliverTreatment: Invalid input");
return new PumpEnactResult(getInjector()).success(false).enacted(false)
.bolusDelivered(0d).carbsDelivered(0d)
.comment(getResourceHelper().gs(R.string.danar_invalidinput));
.comment(getResourceHelper().gs(R.string.invalidinput));
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo);
@ -1259,7 +1259,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
}
@NonNull @Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
public JSONObject getJSONStatus(Profile profile, String profileName, String version) {
if (!pump.initialized) {
return null;
}
@ -1281,7 +1281,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
pumpJson.put("status", statusJson);
JSONObject extendedJson = new JSONObject();
extendedJson.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extendedJson.put("Version", version);
extendedJson.put("ActiveProfile", profileFunction.getProfileName());
PumpState ps = pump.state;
if (ps.tbrActive) {

View file

@ -324,7 +324,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
@NonNull @Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
public JSONObject getJSONStatus(Profile profile, String profileName, String version) {
if ((getPumpStatusData().lastConnection + 5 * 60 * 1000L) < System.currentTimeMillis()) {
return new JSONObject();
@ -337,7 +337,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
try {
battery.put("percent", getPumpStatusData().batteryRemaining);
status.put("status", getPumpStatusData().pumpStatusType != null ? getPumpStatusData().pumpStatusType.getStatus() : "normal");
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extended.put("Version", version);
try {
extended.put("ActiveProfile", profileName);
} catch (Exception ignored) {
@ -413,7 +413,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI
// neither carbs nor bolus requested
aapsLogger.error("deliverTreatment: Invalid input");
return new PumpEnactResult(getInjector()).success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d)
.comment(getResourceHelper().gs(R.string.danar_invalidinput));
.comment(getResourceHelper().gs(R.string.invalidinput));
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo);

View file

@ -3,8 +3,8 @@ package info.nightscout.androidaps.plugins.pump.common.defs;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
/**
@ -16,58 +16,49 @@ import info.nightscout.androidaps.R;
public enum PumpHistoryEntryGroup {
All(R.string.medtronic_history_group_all), //
Bolus(R.string.danar_history_bolus), //
Basal(R.string.medtronic_history_group_basal), //
Prime(R.string.danar_history_prime), //
Configuration(R.string.medtronic_history_group_configuration), //
Alarm(R.string.danar_history_alarm), //
Glucose(R.string.danar_history_glucose), //
Notification(R.string.medtronic_history_group_notification), //
All(R.string.medtronic_history_group_all),
Bolus(R.string.danar_history_bolus),
Basal(R.string.medtronic_history_group_basal),
Prime(R.string.danar_history_prime),
Configuration(R.string.medtronic_history_group_configuration),
Alarm(R.string.danar_history_alarm),
Glucose(R.string.danar_history_glucose),
Notification(R.string.medtronic_history_group_notification),
Statistic(R.string.medtronic_history_group_statistic),
Unknown(R.string.medtronic_history_group_unknown), //
Unknown(R.string.medtronic_history_group_unknown),
;
private int resourceId;
private String translated;
public static boolean doNotTranslate = false;
private static List<PumpHistoryEntryGroup> list;
static {
list = new ArrayList<>();
for (PumpHistoryEntryGroup pumpHistoryEntryGroup : values()) {
//if (doNotTranslate) {
pumpHistoryEntryGroup.translated = MainApp.gs(pumpHistoryEntryGroup.resourceId);
//}
list.add(pumpHistoryEntryGroup);
}
}
private static List<PumpHistoryEntryGroup> translatedList;
PumpHistoryEntryGroup(int resourceId) {
this.resourceId = resourceId;
// this.translated = MainApp.gs(resourceId);
}
private static void doTranslation(ResourceHelper resourceHelper) {
translatedList = new ArrayList<>();
public static List<PumpHistoryEntryGroup> getList() {
return list;
for (PumpHistoryEntryGroup pumpHistoryEntryGroup : values()) {
pumpHistoryEntryGroup.translated = resourceHelper.gs(pumpHistoryEntryGroup.resourceId);
translatedList.add(pumpHistoryEntryGroup);
}
}
public static List<PumpHistoryEntryGroup> getTranslatedList(ResourceHelper resourceHelper) {
if (translatedList == null) doTranslation(resourceHelper);
return translatedList;
}
public int getResourceId() {
return resourceId;
}
public String getTranslated() {
return translated;
}
public String toString() {
return this.translated;
}

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.pump.common.dialog;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
@ -9,8 +8,6 @@ import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
@ -26,13 +23,11 @@ import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -46,13 +41,12 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.GattAttributes;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice;
import info.nightscout.androidaps.plugins.pump.common.utils.LocationHelper;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventMedtronicPumpConfigurationChanged;
import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodPumpValuesChanged;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
@ -65,6 +59,7 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
@Inject SP sp;
@Inject RxBusWrapper rxBus;
@Inject ResourceHelper resourceHelper;
@Inject BlePreCheck blePrecheck;
@Inject RileyLinkUtil rileyLinkUtil;
@Inject ActivePluginProvider activePlugin;
@ -117,17 +112,17 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
PumpInterface activePump = activePlugin.getActivePump();
if (activePump.manufacturer()== ManufacturerType.Medtronic) {
RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice)activePump;
if (activePump.manufacturer() == ManufacturerType.Medtronic) {
RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice) activePump;
rileyLinkPump.getRileyLinkService().verifyConfiguration(); // force reloading of address
rxBus.send(new EventMedtronicPumpConfigurationChanged());
} else if (activePlugin.getActivePump().manufacturer()== ManufacturerType.Insulet) {
if (activePump.model()== PumpType.Insulet_Omnipod_Dash) {
} else if (activePlugin.getActivePump().manufacturer() == ManufacturerType.Insulet) {
if (activePump.model() == PumpType.Insulet_Omnipod_Dash) {
aapsLogger.error("Omnipod Dash not yet implemented.");
} else {
RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice)activePump;
RileyLinkPumpDevice rileyLinkPump = (RileyLinkPumpDevice) activePump;
rileyLinkPump.getRileyLinkService().verifyConfiguration(); // force reloading of address
rxBus.send(new EventOmnipodPumpValuesChanged());
@ -175,36 +170,13 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
public void prepareForScanning() {
// https://developer.android.com/training/permissions/requesting.html
// http://developer.radiusnetworks.com/2015/09/29/is-your-beacon-app-ready-for-android-6.html
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.rileylink_scanner_ble_not_supported, Toast.LENGTH_SHORT).show();
} else {
// Use this check to determine whether BLE is supported on the device. Then
// you can selectively disable BLE-related features.
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// your code that requires permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_COARSE_LOCATION);
}
// Ensures Bluetooth is available on the device and it is enabled. If not,
// displays a dialog requesting user permission to enable Bluetooth.
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, R.string.rileylink_scanner_ble_not_enabled, Toast.LENGTH_SHORT).show();
} else {
// Will request that GPS be enabled for devices running Marshmallow or newer.
if (!LocationHelper.isLocationEnabled(this)) {
LocationHelper.requestLocationForBluetooth(this);
}
boolean checkOK = blePrecheck.prerequisitesCheck(this);
if (checkOK) {
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
filters = Arrays.asList(new ScanFilter.Builder().setServiceUuid(
filters = Collections.singletonList(new ScanFilter.Builder().setServiceUuid(
ParcelUuid.fromString(GattAttributes.SERVICE_RADIO)).build());
}
}
// disable currently selected RL, so that we can discover it
@ -212,19 +184,6 @@ public class RileyLinkBLEScanActivity extends NoSplashAppCompatActivity {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == RESULT_OK) {
// User allowed Bluetooth to turn on
} else if (resultCode == RESULT_CANCELED) {
// Error, or user said "NO"
finish();
}
}
}
private ScanCallback mScanCallback2 = new ScanCallback() {
@Override

View file

@ -59,23 +59,23 @@ public abstract class RileyLinkCommunicationManager {
// All pump communications go through this function.
protected <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, Class<E> clazz)
protected RLMessage sendAndListen(RLMessage msg, int timeout_ms)
throws RileyLinkCommunicationException {
return sendAndListen(msg, timeout_ms, null, clazz);
return sendAndListen(msg, timeout_ms, null);
}
private <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, Integer extendPreamble_ms, Class<E> clazz)
private RLMessage sendAndListen(RLMessage msg, int timeout_ms, Integer extendPreamble_ms)
throws RileyLinkCommunicationException {
return sendAndListen(msg, timeout_ms, 0, extendPreamble_ms, clazz);
return sendAndListen(msg, timeout_ms, 0, extendPreamble_ms);
}
// For backward compatibility
private <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, Integer extendPreamble_ms, Class<E> clazz)
private RLMessage sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, Integer extendPreamble_ms)
throws RileyLinkCommunicationException {
return sendAndListen(msg, timeout_ms, repeatCount, 0, extendPreamble_ms, clazz);
return sendAndListen(msg, timeout_ms, repeatCount, 0, extendPreamble_ms);
}
protected <E extends RLMessage> E sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms, Class<E> clazz)
protected RLMessage sendAndListen(RLMessage msg, int timeout_ms, int repeatCount, int retryCount, Integer extendPreamble_ms)
throws RileyLinkCommunicationException {
// internal flag
@ -88,7 +88,7 @@ public abstract class RileyLinkCommunicationManager {
(byte) 0, (byte) repeatCount, (byte) 0, (byte) 0, timeout_ms, (byte) retryCount, extendPreamble_ms);
RadioResponse radioResponse = rfSpyResponse.getRadioResponse(injector);
E response = createResponseMessage(radioResponse.getPayload(), clazz);
RLMessage response = createResponseMessage(radioResponse.getPayload());
if (response.isValid()) {
// Mark this as the last time we heard from the pump.
@ -124,7 +124,7 @@ public abstract class RileyLinkCommunicationManager {
}
public abstract <E extends RLMessage> E createResponseMessage(byte[] payload, Class<E> clazz);
public abstract RLMessage createResponseMessage(byte[] payload);
public abstract void setPumpDeviceState(PumpDeviceState pumpDeviceState);

View file

@ -5,6 +5,7 @@ import java.util.Map;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
public enum RileyLinkEncodingType {
@ -20,33 +21,31 @@ public enum RileyLinkEncodingType {
private static Map<String, RileyLinkEncodingType> encodingTypeMap;
static {
encodingTypeMap = new HashMap<>();
for (RileyLinkEncodingType encType : values()) {
if (encType.resourceId!=null) {
encodingTypeMap.put(MainApp.gs(encType.resourceId), encType);
}
}
}
RileyLinkEncodingType(int value) {
this.value = (byte)value;
}
RileyLinkEncodingType(int value, Integer resourceId) {
this.value = (byte)value;
this.resourceId = resourceId;
}
public static RileyLinkEncodingType getByDescription(String description) {
private static void doTranslation(ResourceHelper resourceHelper) {
encodingTypeMap = new HashMap<>();
for (RileyLinkEncodingType encType : values()) {
if (encType.resourceId!=null) {
encodingTypeMap.put(resourceHelper.gs(encType.resourceId), encType);
}
}
}
public static RileyLinkEncodingType getByDescription(String description, ResourceHelper resourceHelper) {
if (encodingTypeMap == null) doTranslation(resourceHelper);
if (encodingTypeMap.containsKey(description)) {
return encodingTypeMap.get(description);
}
return RileyLinkEncodingType.FourByteSixByteLocal;
}
}

View file

@ -4,15 +4,10 @@ import javax.inject.Inject;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.data.ServiceTransport;
import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButtonState;
import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService;
/**
* Created by geoff on 7/16/16.
@ -34,7 +29,7 @@ public class ResetRileyLinkConfigurationTask extends PumpTask {
@Override
public void run() {
RileyLinkPumpDevice pumpAbstract = (RileyLinkPumpDevice)activePlugin.getActivePump();
RileyLinkPumpDevice pumpAbstract = (RileyLinkPumpDevice) activePlugin.getActivePump();
rxBus.send(new EventRefreshButtonState(false));

View file

@ -1,69 +0,0 @@
package info.nightscout.androidaps.plugins.pump.common.utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.alertDialogs.OKDialog;
/**
* Helper for checking if location services are enabled on the device.
*/
public class LocationHelper {
/**
* Determine if GPS is currently enabled.
* <p>
* On Android 6 (Marshmallow), location needs to be enabled for Bluetooth discovery to work.
*
* @param context The current app context.
* @return true if location is enabled, false otherwise.
*/
public static boolean isLocationEnabled(Context context) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return (locationManager != null && //
(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || //
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)));
// return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
/**
* Prompt the user to enable GPS location if it isn't already on.
*
* @param parent The currently visible activity.
*/
public static void requestLocation(final Activity parent) {
if (LocationHelper.isLocationEnabled(parent)) {
return;
}
// Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533
OKDialog.showConfirmation(parent, parent.getString(R.string.location_not_found_title), parent.getString(R.string.location_not_found_message), () -> {
parent.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
});
}
/**
* Prompt the user to enable GPS location on devices that need it for Bluetooth discovery.
* <p>
* Android 6 (Marshmallow) needs GPS enabled for Bluetooth discovery to work.
*
* @param activity The currently visible activity.
*/
public static void requestLocationForBluetooth(Activity activity) {
// Location needs to be enabled for Bluetooth discovery on Marshmallow.
LocationHelper.requestLocation(activity);
}
// public static Boolean locationPermission(ActivityWithMenu act) {
// return ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) ==
// PackageManager.PERMISSION_GRANTED;
// }
}

View file

@ -1,102 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MessageHashTableR @Inject constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
constraintChecker: ConstraintChecker,
danaRPump: DanaRPump,
danaRPlugin: DanaRPlugin,
danaRKoreanPlugin: DanaRKoreanPlugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider,
injector: HasAndroidInjector,
dateUtil: DateUtil
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
init {
put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP
put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA
put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED
put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS
// 0x0301 CMD_PUMPINIT_TIME_INFO
put(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil))
put(MsgInitConnStatusBolus(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO
put(MsgInitConnStatusBasic(aapsLogger, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO
put(MsgInitConnStatusOption(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0304 CMD_PUMPINIT_OPTION
put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S
put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S
put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP
put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP
put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S
put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS
put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT
put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT
put(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS
put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS
put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE
put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM
put(MsgHistoryError(aapsLogger, rxBus, dateUtil)) // 0x3106 CMD_HISTORY_ERROR
put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY
put(MsgHistoryRefill(aapsLogger, rxBus, dateUtil)) // 0x3108 CMD_HISTORY_REFILL
put(MsgHistorySuspend(aapsLogger, rxBus, dateUtil)) // 0x3109 CMD_HISTORY_SUSPEND
put(MsgHistoryBasalHour(aapsLogger, rxBus, dateUtil)) // 0x310A CMD_HISTORY_BASAL_HOUR
put(MsgHistoryDone(aapsLogger, danaRPump)) // 0x31F1 CMD_HISTORY_DONT_USED
// 0x3202 CMD_SETTING_V_BASAL_INS_I
put(MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin))
// 0x3203 CMD_SETTING_V_MEAL_SETTING_I
put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin))
put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I
put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I
put(MsgSettingBasalProfileAll(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL
put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I
put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY
put(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 0x320A CMD_SETTING_V_TIME_I
put(MsgSettingUserOptions(aapsLogger, danaRPump)) // 0x320B CMD_SETTING_V_USER_OPTIONS
put(MsgSettingActiveProfile(aapsLogger, danaRPump)) // 0x320C CMD_SETTING_V_PROFILE_NUMBER
put(MsgSettingProfileRatiosAll(aapsLogger, danaRPump)) // 0x320D CMD_SETTING_V_CIR_CF_VALUE
put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S
put(MsgSetBasalProfile(aapsLogger, rxBus, resourceHelper, 0.toByte(), Array(24) { 0.0 })) // 0x3306 CMD_SETTING_BASAL_PROFILE_S
put(MsgSetUserOptions(aapsLogger, danaRPump)) // 0x330B CMD_SETTING_USER_OPTIONS_S
put(MsgSetActivateBasalProfile(aapsLogger, 0.toByte())) // 0x330C CMD_SETTING_PROFILE_NUMBER_S
put(MsgHistoryAllDone(aapsLogger, danaRPump)) // 0x41F1 CMD_HISTORY_ALL_DONE
put(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL
put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE
put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW
// 0xF0F1 CMD_PUMP_CHECK_VALUE
put(MsgCheckValue(aapsLogger, danaRPump, danaRPlugin))
}
override fun put(message: MessageBase) {
messages[message.command] = message
}
override fun findMessage(command: Int): MessageBase {
return messages[command] ?: MessageBase()
}
}

View file

@ -1,43 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class MsgSetUserOptions(
private val aapsLogger: AAPSLogger,
danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x330B)
if (danaRPump.userOptionsFrompump == null) {
// No options set -> Exiting
aapsLogger.debug(LTag.PUMPCOMM, "NO USER OPTIONS LOADED EXITING!")
} else {
danaRPump.userOptionsFrompump!![0] = (if (danaRPump.timeDisplayType == 1) 0 else 1).toByte()
danaRPump.userOptionsFrompump!![1] = danaRPump.buttonScrollOnOff.toByte()
danaRPump.userOptionsFrompump!![2] = danaRPump.beepAndAlarm.toByte()
danaRPump.userOptionsFrompump!![3] = danaRPump.lcdOnTimeSec.toByte()
danaRPump.userOptionsFrompump!![4] = danaRPump.backlightOnTimeSec.toByte()
danaRPump.userOptionsFrompump!![5] = danaRPump.selectedLanguage.toByte()
danaRPump.userOptionsFrompump!![8] = danaRPump.units.toByte()
danaRPump.userOptionsFrompump!![9] = danaRPump.shutdownHour.toByte()
danaRPump.userOptionsFrompump!![27] = danaRPump.lowReservoirRate.toByte()
for (element in danaRPump.userOptionsFrompump!!) {
AddParamByte(element)
}
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
}
override fun handleMessage(bytes: ByteArray) {
val result = intFromBuff(bytes, 0, 1)
if (result != 1) {
failed = true
aapsLogger.debug(LTag.PUMPCOMM, "Setting user options: $result FAILED!!!")
} else {
aapsLogger.debug(LTag.PUMPCOMM, "Setting user options: $result")
}
}
}

View file

@ -1,25 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class MsgSettingMaxValues(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x3205)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
danaRPump.maxBolus = intFromBuff(bytes, 0, 2) / 100.0
danaRPump.maxBasal = intFromBuff(bytes, 2, 2) / 100.0
danaRPump.maxDailyTotalUnits = intFromBuff(bytes, 4, 2) / 100
aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus)
aapsLogger.debug(LTag.PUMPCOMM, "Max basal: " + danaRPump.maxBasal)
aapsLogger.debug(LTag.PUMPCOMM, "Total daily max units: " + danaRPump.maxDailyTotalUnits)
}
}

View file

@ -1,38 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class MsgSettingProfileRatios(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x3204)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
if (danaRPump.units == DanaRPump.UNITS_MGDL) {
danaRPump.currentCIR = intFromBuff(bytes, 0, 2)
danaRPump.currentCF = intFromBuff(bytes, 2, 2).toDouble()
danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0
danaRPump.currentTarget = intFromBuff(bytes, 6, 2).toDouble()
danaRPump.currentAIDR = intFromBuff(bytes, 8, 1)
} else {
danaRPump.currentCIR = intFromBuff(bytes, 0, 2)
danaRPump.currentCF = intFromBuff(bytes, 2, 2) / 100.0
danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0
danaRPump.currentTarget = intFromBuff(bytes, 6, 2) / 100.0
danaRPump.currentAIDR = intFromBuff(bytes, 8, 1)
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump units (saved): " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL")
aapsLogger.debug(LTag.PUMPCOMM, "Current pump CIR: " + danaRPump.currentCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump CF: " + danaRPump.currentCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump AI: " + danaRPump.currentAI)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump target: " + danaRPump.currentTarget)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump AIDR: " + danaRPump.currentAIDR)
}
}

View file

@ -1,47 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class MsgSettingProfileRatiosAll(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x320D)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
if (danaRPump.units == DanaRPump.UNITS_MGDL) {
danaRPump.morningCIR = intFromBuff(bytes, 0, 2)
danaRPump.morningCF = intFromBuff(bytes, 2, 2).toDouble()
danaRPump.afternoonCIR = intFromBuff(bytes, 4, 2)
danaRPump.afternoonCF = intFromBuff(bytes, 6, 2).toDouble()
danaRPump.eveningCIR = intFromBuff(bytes, 8, 2)
danaRPump.eveningCF = intFromBuff(bytes, 10, 2).toDouble()
danaRPump.nightCIR = intFromBuff(bytes, 12, 2)
danaRPump.nightCF = intFromBuff(bytes, 14, 2).toDouble()
} else {
danaRPump.morningCIR = intFromBuff(bytes, 0, 2)
danaRPump.morningCF = intFromBuff(bytes, 2, 2) / 100.0
danaRPump.afternoonCIR = intFromBuff(bytes, 4, 2)
danaRPump.afternoonCF = intFromBuff(bytes, 6, 2) / 100.0
danaRPump.eveningCIR = intFromBuff(bytes, 8, 2)
danaRPump.eveningCF = intFromBuff(bytes, 10, 2) / 100.0
danaRPump.nightCIR = intFromBuff(bytes, 12, 2)
danaRPump.nightCF = intFromBuff(bytes, 14, 2) / 100.0
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL")
aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CIR: " + danaRPump.morningCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CF: " + danaRPump.morningCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CIR: " + danaRPump.afternoonCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CF: " + danaRPump.afternoonCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CIR: " + danaRPump.eveningCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CF: " + danaRPump.eveningCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CIR: " + danaRPump.nightCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CF: " + danaRPump.nightCF)
}
}

View file

@ -1,59 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import java.util.*
class MsgSettingUserOptions(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x320B)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(packet: ByteArray) {
val bytes = getDataBytes(packet, packet.size - 10)
danaRPump.userOptionsFrompump = Arrays.copyOf(bytes, bytes!!.size) // saving pumpDataBytes to use it in MsgSetUserOptions
for (pos in bytes.indices) {
aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos])
}
danaRPump.timeDisplayType = if (bytes[0] == 1.toByte()) 0 else 1 // 1 -> 24h 0 -> 12h
danaRPump.buttonScrollOnOff = if (bytes[1] == 1.toByte()) 1 else 0 // 1 -> ON, 0-> OFF
danaRPump.beepAndAlarm = bytes[2].toInt() // 1 -> Sound on alarm 2-> Vibrate on alarm 3-> Both on alarm 5-> Sound + beep 6-> vibrate + beep 7-> both + beep Beep adds 4
danaRPump.lcdOnTimeSec = bytes[3].toInt() and 255
danaRPump.backlightOnTimeSec = bytes[4].toInt() and 255
danaRPump.selectedLanguage = bytes[5].toInt() // on DanaRv2 is that needed ?
danaRPump.units = bytes[8].toInt()
danaRPump.shutdownHour = bytes[9].toInt()
danaRPump.lowReservoirRate = bytes[32].toInt() and 255
/* int selectableLanguage1 = bytes[10];
int selectableLanguage2 = bytes[11];
int selectableLanguage3 = bytes[12];
int selectableLanguage4 = bytes[13];
int selectableLanguage5 = bytes[14];
*/
aapsLogger.debug(LTag.PUMPCOMM, "timeDisplayType: " + danaRPump.timeDisplayType)
aapsLogger.debug(LTag.PUMPCOMM, "Button scroll: " + danaRPump.buttonScrollOnOff)
aapsLogger.debug(LTag.PUMPCOMM, "BeepAndAlarm: " + danaRPump.beepAndAlarm)
aapsLogger.debug(LTag.PUMPCOMM, "screen timeout: " + danaRPump.lcdOnTimeSec)
aapsLogger.debug(LTag.PUMPCOMM, "BackLight: " + danaRPump.backlightOnTimeSec)
aapsLogger.debug(LTag.PUMPCOMM, "Selected language: " + danaRPump.selectedLanguage)
aapsLogger.debug(LTag.PUMPCOMM, "Units: " + danaRPump.getUnits())
aapsLogger.debug(LTag.PUMPCOMM, "Shutdown: " + danaRPump.shutdownHour)
aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaRPump.lowReservoirRate)
}
private fun getDataBytes(bytes: ByteArray?, len: Int): ByteArray? {
if (bytes == null) {
return null
}
val ret = ByteArray(len)
System.arraycopy(bytes, 6, ret, 0, len)
return ret
}
}

View file

@ -1,37 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class MsgStatus(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x020B)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
danaRPump.dailyTotalUnits = intFromBuff(bytes, 0, 3) / 750.0
danaRPump.isExtendedInProgress = intFromBuff(bytes, 3, 1) == 1
danaRPump.extendedBolusMinutes = intFromBuff(bytes, 4, 2)
danaRPump.extendedBolusAmount = intFromBuff(bytes, 6, 2) / 100.0
val lastBolusAmount = intFromBuff(bytes, 13, 2) / 100.0
if (lastBolusAmount != 0.0) {
danaRPump.lastBolusTime = dateTimeFromBuff(bytes, 8)
danaRPump.lastBolusAmount = lastBolusAmount
}
danaRPump.iob = intFromBuff(bytes, 15, 2) / 100.0
aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits)
aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress)
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus min: " + danaRPump.extendedBolusMinutes)
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus amount: " + danaRPump.extendedBolusAmount)
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + danaRPump.lastBolusTime)
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount)
aapsLogger.debug(LTag.PUMPCOMM, "IOB: " + danaRPump.iob)
}
}

View file

@ -1,36 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class MsgStatusProfile(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : MessageBase() {
init {
SetCommand(0x0204)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
if (danaRPump.units == DanaRPump.UNITS_MGDL) {
danaRPump.currentCIR = intFromBuff(bytes, 0, 2)
danaRPump.currentCF = intFromBuff(bytes, 2, 2).toDouble()
danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0
danaRPump.currentTarget = intFromBuff(bytes, 6, 2).toDouble()
} else {
danaRPump.currentCIR = intFromBuff(bytes, 0, 2)
danaRPump.currentCF = intFromBuff(bytes, 2, 2) / 100.0
danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0
danaRPump.currentTarget = intFromBuff(bytes, 6, 2) / 100.0
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump units (saved): " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL")
aapsLogger.debug(LTag.PUMPCOMM, "Current pump CIR: " + danaRPump.currentCIR)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump CF: " + danaRPump.currentCF)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump AI: " + danaRPump.currentAI)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump target: " + danaRPump.currentTarget)
aapsLogger.debug(LTag.PUMPCOMM, "Current pump AIDR: " + danaRPump.currentAIDR)
}
}

View file

@ -1,13 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaR.services;
import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase;
/**
* Created by mike on 28.01.2018.
*/
public abstract class AbstractSerialIOThread extends Thread {
public abstract void sendMessage(MessageBase message);
public abstract void disconnect(String reason);
}

View file

@ -1,85 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRKorean.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.pump.danaR.comm.*
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MessageHashTableRKorean @Inject constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
constraintChecker: ConstraintChecker,
danaRPump: DanaRPump,
danaRPlugin: DanaRPlugin,
danaRKoreanPlugin: DanaRKoreanPlugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider,
dateUtil: DateUtil,
injector: HasAndroidInjector
) : MessageHashTableBase {
var messages: HashMap<Int, MessageBase> = HashMap()
init {
put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP
put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA
put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING
put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic_k(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus_k(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS
put(MsgInitConnStatusTime_k(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) // 0x0301 CMD_PUMPINIT_TIME_INFO
put(MsgInitConnStatusBolus_k(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO
put(MsgInitConnStatusBasic_k(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO
put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S
put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S
put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP
put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP
put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S
put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS
put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT
put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT
put(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS
put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS
put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE
put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM
put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY
put(MsgSettingBasal_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0x3202 CMD_SETTING_V_BASAL_INS_I
put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) // 0x3203 CMD_SETTING_V_MEAL_SETTING_I
put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I
put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I
put(MsgSettingBasalProfileAll_k(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL
put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I
put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY
put(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 0x320A CMD_SETTING_V_TIME_I
put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S
put(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL
put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE
put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW
put(MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0xF0F1 CMD_PUMP_CHECK_VALUE
}
override fun put(message: MessageBase) {
messages[message.command] = message
}
override fun findMessage(command: Int): MessageBase {
return messages[command] ?: MessageBase()
}
}

View file

@ -1,836 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import androidx.annotation.NonNull;
import androidx.preference.Preference;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.DanaRInterface;
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.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange;
import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.TimeChangeType;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
@Singleton
public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface {
private CompositeDisposable disposable = new CompositeDisposable();
private final Context context;
private final ResourceHelper resourceHelper;
private final ConstraintChecker constraintChecker;
private final ProfileFunction profileFunction;
private final TreatmentsPlugin treatmentsPlugin;
private final SP sp;
private final RxBusWrapper rxBus;
private final CommandQueueProvider commandQueue;
private final DanaRPump danaRPump;
private final DetailedBolusInfoStorage detailedBolusInfoStorage;
private final DateUtil dateUtil;
private static DanaRSService danaRSService;
private static String mDeviceAddress = "";
public static String mDeviceName = "";
public static PumpDescription pumpDescription = new PumpDescription();
// Bolus & history handling
public int bolusStartErrorCode; // from start message
public Treatment bolusingTreatment; // actually delivered treatment
public double bolusAmountToBeDelivered = 0.0; // amount to be delivered
public boolean bolusStopped = false; // bolus finished
public boolean bolusStopForced = false; // bolus forced to stop by user
public boolean bolusDone = false; // success end
public long bolusProgressLastTimeStamp = 0; // timestamp of last bolus progress message
public boolean apsHistoryDone = false; // true when last history message is received
public long lastEventTimeLoaded = 0; // timestamp of last received event
@Inject
public DanaRSPlugin(
HasAndroidInjector injector,
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
Context context,
ResourceHelper resourceHelper,
ConstraintChecker constraintChecker,
ProfileFunction profileFunction,
TreatmentsPlugin treatmentsPlugin,
SP sp,
CommandQueueProvider commandQueue,
DanaRPump danaRPump,
DetailedBolusInfoStorage detailedBolusInfoStorage,
DateUtil dateUtil
) {
super(new PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(DanaRFragment.class.getName())
.pluginName(R.string.danarspump)
.shortName(R.string.danarspump_shortname)
.preferencesId(R.xml.pref_danars)
.description(R.string.description_pump_dana_rs),
injector, aapsLogger, resourceHelper, commandQueue
);
this.context = context;
this.rxBus = rxBus;
this.resourceHelper = resourceHelper;
this.constraintChecker = constraintChecker;
this.profileFunction = profileFunction;
this.treatmentsPlugin = treatmentsPlugin;
this.sp = sp;
this.commandQueue = commandQueue;
this.danaRPump = danaRPump;
this.detailedBolusInfoStorage = detailedBolusInfoStorage;
this.dateUtil = dateUtil;
pumpDescription.setPumpDescription(PumpType.DanaRS);
}
@Override
public void updatePreferenceSummary(@NotNull Preference pref) {
super.updatePreferenceSummary(pref);
if (pref.getKey().equals(resourceHelper.gs(R.string.key_danars_name)))
pref.setSummary(sp.getString(R.string.key_danars_name, ""));
}
@Override
protected void onStart() {
Intent intent = new Intent(context, DanaRSService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
disposable.add(rxBus
.toObservable(EventAppExit.class)
.observeOn(Schedulers.io())
.subscribe(event -> context.unbindService(mConnection), exception -> FabricPrivacy.getInstance().logException(exception))
);
disposable.add(rxBus
.toObservable(EventDanaRSDeviceChange.class)
.observeOn(Schedulers.io())
.subscribe(event -> loadAddress(), exception -> FabricPrivacy.getInstance().logException(exception))
);
loadAddress(); // load device name
super.onStart();
}
@Override
protected void onStop() {
context.unbindService(mConnection);
disposable.clear();
super.onStop();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
getAapsLogger().debug(LTag.PUMP, "Service is disconnected");
danaRSService = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
getAapsLogger().debug(LTag.PUMP, "Service is connected");
DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder) service;
danaRSService = mLocalBinder.getServiceInstance();
}
};
private void loadAddress() {
mDeviceAddress = sp.getString(R.string.key_danars_address, "");
mDeviceName = sp.getString(R.string.key_danars_name, "");
}
@Override
public void connect(String from) {
getAapsLogger().debug(LTag.PUMP, "RS connect from: " + from);
if (danaRSService != null && !mDeviceAddress.equals("") && !mDeviceName.equals("")) {
final Object o = new Object();
danaRSService.connect(from, mDeviceAddress, o);
}
}
@Override
public boolean isConnected() {
return danaRSService != null && danaRSService.isConnected();
}
@Override
public boolean isConnecting() {
return danaRSService != null && danaRSService.isConnecting();
}
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override
public void disconnect(String from) {
getAapsLogger().debug(LTag.PUMP, "RS disconnect from: " + from);
if (danaRSService != null) danaRSService.disconnect(from);
}
@Override
public void stopConnecting() {
if (danaRSService != null) danaRSService.stopConnecting();
}
@Override
public void getPumpStatus() {
if (danaRSService != null) {
danaRSService.getPumpStatus();
pumpDescription.basalStep = danaRPump.getBasalStep();
pumpDescription.bolusStep = danaRPump.getBolusStep();
}
}
// DanaR interface
@Override
public PumpEnactResult loadHistory(byte type) {
return danaRSService.loadHistory(type);
}
@Override
public PumpEnactResult loadEvents() {
return danaRSService.loadEvents();
}
@Override
public PumpEnactResult setUserOptions() {
return danaRSService.setUserSettings();
}
// Constraints interface
@NonNull
@Override
public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, @NonNull Profile profile) {
absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), resourceHelper.gs(R.string.limitingbasalratio, danaRPump.getMaxBasal(), resourceHelper.gs(R.string.pumplimit)), this);
return absoluteRate;
}
@NonNull
@Override
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, @NonNull Profile profile) {
percentRate.setIfGreater(getAapsLogger(), 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this);
percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this);
return percentRate;
}
@NonNull
@Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) {
insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), resourceHelper.gs(R.string.limitingbolus, danaRPump.getMaxBolus(), resourceHelper.gs(R.string.pumplimit)), this);
return insulin;
}
@NonNull
@Override
public Constraint<Double> applyExtendedBolusConstraints(@NonNull Constraint<Double> insulin) {
return applyBolusConstraints(insulin);
}
// Pump interface
@Override
public boolean isInitialized() {
return danaRPump.getLastConnection() > 0 && danaRPump.getMaxBasal() > 0;
}
@Override
public boolean isSuspended() {
return danaRPump.getPumpSuspended();
}
@Override
public boolean isBusy() {
if (danaRSService == null) return false;
return danaRSService.isConnected() || danaRSService.isConnecting();
}
@NonNull @Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
PumpEnactResult result = new PumpEnactResult(getInjector());
if (danaRSService == null) {
getAapsLogger().error("setNewBasalProfile sExecutionService is null");
result.comment = "setNewBasalProfile sExecutionService is null";
return result;
}
if (!isInitialized()) {
getAapsLogger().error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet);
return result;
} else {
rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
}
if (!danaRSService.updateBasalsInPump(profile)) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
rxBus.send(new EventNewNotification(notification));
result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile);
return result;
} else {
rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60);
rxBus.send(new EventNewNotification(notification));
result.success = true;
result.enacted = true;
result.comment = "OK";
return result;
}
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized())
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
if (danaRPump.getPumpProfiles() == null)
return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS
int basalValues = danaRPump.getBasal48Enable() ? 48 : 24;
int basalIncrement = danaRPump.getBasal48Enable() ? 30 * 60 : 60 * 60;
for (int h = 0; h < basalValues; h++) {
Double pumpValue = danaRPump.getPumpProfiles()[danaRPump.getActiveProfile()][h];
Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement);
if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) {
getAapsLogger().debug(LTag.PUMP, "Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue);
return false;
}
}
return true;
}
@Override
public long lastDataTime() {
return danaRPump.getLastConnection();
}
@Override
public double getBaseBasalRate() {
return danaRPump.getCurrentBasal();
}
@Override
public double getReservoirLevel() {
return danaRPump.getReservoirRemainingUnits();
}
@Override
public int getBatteryLevel() {
return danaRPump.getBatteryRemaining();
}
@NonNull @Override
public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value();
if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) {
int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0);
int speed = 12;
switch (preferencesSpeed) {
case 0:
speed = 12;
break;
case 1:
speed = 30;
break;
case 2:
speed = 60;
break;
}
// RS stores end time for bolus, we need to adjust time
// default delivery speed is 12 sec/U
detailedBolusInfo.date = DateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000);
// clean carbs to prevent counting them as twice because they will picked up as another record
// I don't think it's necessary to copy DetailedBolusInfo right now for carbs records
double carbs = detailedBolusInfo.carbs;
detailedBolusInfo.carbs = 0;
int carbTime = detailedBolusInfo.carbTime;
if (carbTime == 0) carbTime--; // better set 1 min back to prevents clash with insulin
detailedBolusInfo.carbTime = 0;
detailedBolusInfoStorage.add(detailedBolusInfo); // will be picked up on reading history
Treatment t = new Treatment();
t.isSMB = detailedBolusInfo.isSMB;
boolean connectionOK = false;
if (detailedBolusInfo.insulin > 0 || carbs > 0)
connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t);
PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep;
result.bolusDelivered = t.insulin;
result.carbsDelivered = detailedBolusInfo.carbs;
if (!result.success) {
String error = "" + bolusStartErrorCode;
switch (bolusStartErrorCode) {
// 4 reported as max bolus violation. Check later
case 0x10:
error = resourceHelper.gs(R.string.maxbolusviolation);
break;
case 0x20:
error = resourceHelper.gs(R.string.commanderror);
break;
case 0x40:
error = resourceHelper.gs(R.string.speederror);
break;
case 0x80:
error = resourceHelper.gs(R.string.insulinlimitviolation);
break;
}
result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, error);
} else
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
getAapsLogger().debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered);
return result;
} else {
PumpEnactResult result = new PumpEnactResult(getInjector());
result.success = false;
result.bolusDelivered = 0d;
result.carbsDelivered = 0d;
result.comment = resourceHelper.gs(R.string.danar_invalidinput);
getAapsLogger().error("deliverTreatment: Invalid input");
return result;
}
}
@Override
public void stopBolusDelivering() {
if (danaRSService == null) {
getAapsLogger().error("stopBolusDelivering sExecutionService is null");
return;
}
danaRSService.bolusStop();
}
// This is called from APS
@NonNull @Override
public synchronized PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
// Recheck pump status if older than 30 min
//This should not be needed while using queue because connection should be done before calling this
//if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) {
// connect("setTempBasalAbsolute old data");
//}
PumpEnactResult result = new PumpEnactResult(getInjector());
absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value();
final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d;
final boolean doLowTemp = absoluteRate < getBaseBasalRate();
final boolean doHighTemp = absoluteRate > getBaseBasalRate();
if (doTempOff) {
// If temp in progress
if (treatmentsPlugin.isTempBasalInProgress()) {
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doTempOff)");
return cancelTempBasal(false);
}
result.success = true;
result.enacted = false;
result.percent = 100;
result.isPercent = true;
result.isTempCancel = true;
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: doTempOff OK");
return result;
}
if (doLowTemp || doHighTemp) {
Integer percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue();
if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue();
else percentRate = Round.floorTo((double) percentRate, 10d).intValue();
if (percentRate > 500) // Special high temp 500/15min
percentRate = 500;
// Check if some temp is already in progress
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: currently running: " + activeTemp.toString());
// Correct basal already set ?
if (activeTemp.percentRate == percentRate && activeTemp.getPlannedRemainingMinutes() > 4) {
if (!enforceNew) {
result.success = true;
result.percent = percentRate;
result.enacted = false;
result.duration = activeTemp.getPlannedRemainingMinutes();
result.isPercent = true;
result.isTempCancel = false;
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)");
return result;
}
}
}
// Convert duration from minutes to hours
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)");
if (percentRate == 0 && durationInMinutes > 30) {
result = setTempBasalPercent(percentRate, durationInMinutes, profile, enforceNew);
} else {
// use special APS temp basal call ... 100+/15min .... 100-/30min
result = setHighTempBasalPercent(percentRate);
}
if (!result.success) {
getAapsLogger().error("setTempBasalAbsolute: Failed to set hightemp basal");
return result;
}
getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: hightemp basal set ok");
return result;
}
// We should never end here
getAapsLogger().error("setTempBasalAbsolute: Internal error");
result.success = false;
result.comment = "Internal error";
return result;
}
@NonNull @Override
public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
DanaRPump pump = danaRPump;
PumpEnactResult result = new PumpEnactResult(getInjector());
percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value();
if (percent < 0) {
result.isTempCancel = false;
result.enacted = false;
result.success = false;
result.comment = resourceHelper.gs(R.string.danar_invalidinput);
getAapsLogger().error("setTempBasalPercent: Invalid input");
return result;
}
if (percent > getPumpDescription().maxTempPercent)
percent = getPumpDescription().maxTempPercent;
long now = System.currentTimeMillis();
TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now);
if (activeTemp != null && activeTemp.percentRate == percent && activeTemp.getPlannedRemainingMinutes() > 4 && !enforceNew) {
result.enacted = false;
result.success = true;
result.isTempCancel = false;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
result.duration = pump.getTempBasalRemainingMin();
result.percent = pump.getTempBasalPercent();
result.isPercent = true;
getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: Correct value already set");
return result;
}
boolean connectionOK;
if (durationInMinutes == 15 || durationInMinutes == 30) {
connectionOK = danaRSService.tempBasalShortDuration(percent, durationInMinutes);
} else {
int durationInHours = Math.max(durationInMinutes / 60, 1);
connectionOK = danaRSService.tempBasal(percent, durationInHours);
}
if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) {
result.enacted = true;
result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
result.isTempCancel = false;
result.duration = pump.getTempBasalRemainingMin();
result.percent = pump.getTempBasalPercent();
result.isPercent = true;
getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: OK");
return result;
}
result.enacted = false;
result.success = false;
result.comment = resourceHelper.gs(R.string.tempbasaldeliveryerror);
getAapsLogger().error("setTempBasalPercent: Failed to set temp basal");
return result;
}
private synchronized PumpEnactResult setHighTempBasalPercent(Integer percent) {
DanaRPump pump = danaRPump;
PumpEnactResult result = new PumpEnactResult(getInjector());
boolean connectionOK = danaRSService.highTempBasal(percent);
if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) {
result.enacted = true;
result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
result.isTempCancel = false;
result.duration = pump.getTempBasalRemainingMin();
result.percent = pump.getTempBasalPercent();
result.isPercent = true;
getAapsLogger().debug(LTag.PUMP, "setHighTempBasalPercent: OK");
return result;
}
result.enacted = false;
result.success = false;
result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly);
getAapsLogger().error("setHighTempBasalPercent: Failed to set temp basal");
return result;
}
@NonNull @Override
public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
DanaRPump pump = danaRPump;
insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value();
// needs to be rounded
int durationInHalfHours = Math.max(durationInMinutes / 30, 1);
insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep);
PumpEnactResult result = new PumpEnactResult(getInjector());
ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis());
if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = false;
result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
result.duration = pump.getExtendedBolusRemainingMinutes();
result.absolute = pump.getExtendedBolusAbsoluteRate();
result.isPercent = false;
result.isTempCancel = false;
getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: Correct extended bolus already set. Current: " + pump.getExtendedBolusAmount() + " Asked: " + insulin);
return result;
}
boolean connectionOK = danaRSService.extendedBolus(insulin, durationInHalfHours);
if (connectionOK && pump.isExtendedInProgress() && Math.abs(pump.getExtendedBolusAbsoluteRate() - insulin) < getPumpDescription().extendedBolusStep) {
result.enacted = true;
result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
result.isTempCancel = false;
result.duration = pump.getExtendedBolusRemainingMinutes();
result.absolute = pump.getExtendedBolusAbsoluteRate();
result.bolusDelivered = pump.getExtendedBolusAmount();
result.isPercent = false;
getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: OK");
return result;
}
result.enacted = false;
result.success = false;
result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly);
getAapsLogger().error("setExtendedBolus: Failed to extended bolus");
return result;
}
@NonNull @Override
public synchronized PumpEnactResult cancelTempBasal(boolean force) {
PumpEnactResult result = new PumpEnactResult(getInjector());
TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis());
if (runningTB != null) {
danaRSService.tempBasalStop();
result.enacted = true;
result.isTempCancel = true;
}
if (!danaRPump.isTempBasalInProgress()) {
result.success = true;
result.isTempCancel = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
getAapsLogger().debug(LTag.PUMP, "cancelRealTempBasal: OK");
return result;
} else {
result.success = false;
result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly);
result.isTempCancel = true;
getAapsLogger().error("cancelRealTempBasal: Failed to cancel temp basal");
return result;
}
}
@NonNull @Override
public synchronized PumpEnactResult cancelExtendedBolus() {
PumpEnactResult result = new PumpEnactResult(getInjector());
ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis());
if (runningEB != null) {
danaRSService.extendedBolusStop();
result.enacted = true;
result.isTempCancel = true;
}
if (!danaRPump.isExtendedInProgress()) {
result.success = true;
result.comment = resourceHelper.gs(R.string.virtualpump_resultok);
getAapsLogger().debug(LTag.PUMP, "cancelExtendedBolus: OK");
return result;
} else {
result.success = false;
result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly);
getAapsLogger().error("cancelExtendedBolus: Failed to cancel extended bolus");
return result;
}
}
@NonNull @Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
DanaRPump pump = danaRPump;
long now = System.currentTimeMillis();
if (pump.getLastConnection() + 5 * 60 * 1000L < System.currentTimeMillis()) {
return new JSONObject();
}
JSONObject pumpjson = new JSONObject();
JSONObject battery = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
try {
battery.put("percent", pump.getBatteryRemaining());
status.put("status", pump.getPumpSuspended() ? "suspended" : "normal");
status.put("timestamp", DateUtil.toISOString(pump.getLastConnection()));
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
if (pump.getLastBolusTime() != 0) {
extended.put("LastBolus", dateUtil.dateAndTimeString(pump.getLastBolusTime()));
extended.put("LastBolusAmount", pump.getLastBolusAmount());
}
TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now);
if (tb != null) {
extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile));
extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
}
ExtendedBolus eb = treatmentsPlugin.getExtendedBolusFromHistory(now);
if (eb != null) {
extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date));
extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
}
extended.put("BaseBasalRate", getBaseBasalRate());
try {
extended.put("ActiveProfile", profileFunction.getProfileName());
} catch (Exception e) {
getAapsLogger().error("Unhandled exception", e);
}
pumpjson.put("battery", battery);
pumpjson.put("status", status);
pumpjson.put("extended", extended);
pumpjson.put("reservoir", (int) pump.getReservoirRemainingUnits());
pumpjson.put("clock", DateUtil.toISOString(now));
} catch (JSONException e) {
getAapsLogger().error("Unhandled exception", e);
}
return pumpjson;
}
@NonNull @Override
public ManufacturerType manufacturer() {
return ManufacturerType.Sooil;
}
@NonNull @Override
public PumpType model() {
return PumpType.DanaRS;
}
@NonNull @Override
public String serialNumber() {
return danaRPump.getSerialNumber();
}
@NonNull @Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@NonNull @Override
public String shortStatus(boolean veryShort) {
DanaRPump pump = danaRPump;
String ret = "";
if (pump.getLastConnection() != 0) {
long agoMsec = System.currentTimeMillis() - pump.getLastConnection();
int agoMin = (int) (agoMsec / 60d / 1000d);
ret += "LastConn: " + agoMin + " minago\n";
}
if (pump.getLastBolusTime() != 0) {
ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.getLastBolusTime()) + "\n";
}
TemporaryBasal activeTemp = treatmentsPlugin.getRealTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
ret += "Temp: " + activeTemp.toStringFull() + "\n";
}
ExtendedBolus activeExtendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis());
if (activeExtendedBolus != null) {
ret += "Extended: " + activeExtendedBolus.toString() + "\n";
}
if (!veryShort) {
ret += "TDD: " + DecimalFormatter.to0Decimal(pump.getDailyTotalUnits()) + " / " + pump.getMaxDailyTotalUnits() + " U\n";
}
ret += "Reserv: " + DecimalFormatter.to0Decimal(pump.getReservoirRemainingUnits()) + "U\n";
ret += "Batt: " + pump.getBatteryRemaining() + "\n";
return ret;
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return false;
}
@NonNull @Override
public PumpEnactResult loadTDDs() {
return loadHistory(RecordTypes.RECORD_TYPE_DAILY);
}
@Override
public List<CustomAction> getCustomActions() {
return null;
}
@Override
public void executeCustomAction(CustomActionType customActionType) {
}
@Override
public boolean canHandleDST() {
return false;
}
@Override
public void timezoneOrDSTChanged(TimeChangeType changeType) {
}
}

View file

@ -1,217 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.activities;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange;
import info.nightscout.androidaps.utils.SP;
public class BLEScanActivity extends NoSplashAppCompatActivity {
private ListAdapter mListAdapter = null;
private ArrayList<BluetoothDeviceItem> mDevices = new ArrayList<>();
private BluetoothLeScanner mBluetoothLeScanner = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.danars_blescanner_activity);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mListAdapter = new ListAdapter();
ListView listView = findViewById(R.id.danars_blescanner_listview);
listView.setEmptyView(findViewById(R.id.danars_blescanner_nodevice));
listView.setAdapter(mListAdapter);
mListAdapter.notifyDataSetChanged();
}
@Override
protected void onResume() {
super.onResume();
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) mBluetoothAdapter.enable();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
if (mBluetoothLeScanner == null) {
mBluetoothAdapter.enable();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
}
startScan();
}
}
@Override
protected void onPause() {
super.onPause();
stopScan();
}
private void startScan() {
if (mBluetoothLeScanner != null)
mBluetoothLeScanner.startScan(mBleScanCallback);
}
private void stopScan() {
if (mBluetoothLeScanner != null)
mBluetoothLeScanner.stopScan(mBleScanCallback);
}
private void addBleDevice(BluetoothDevice device) {
if (device == null || device.getName() == null || device.getName().equals("")) {
return;
}
BluetoothDeviceItem item = new BluetoothDeviceItem(device);
if (!isSNCheck(device.getName()) || mDevices.contains(item)) {
return;
}
mDevices.add(item);
new Handler().post(() -> mListAdapter.notifyDataSetChanged());
}
private ScanCallback mBleScanCallback = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
addBleDevice(result.getDevice());
}
};
class ListAdapter extends BaseAdapter {
@Override
public int getCount() {
return mDevices.size();
}
@Override
public BluetoothDeviceItem getItem(int i) {
return mDevices.get(i);
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
v = View.inflate(getApplicationContext(), R.layout.danars_blescanner_item, null);
holder = new ViewHolder(v);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
BluetoothDeviceItem item = getItem(i);
holder.setData(item);
return v;
}
private class ViewHolder implements View.OnClickListener {
private BluetoothDeviceItem item = null;
private TextView mName;
private TextView mAddress;
ViewHolder(View v) {
mName = v.findViewById(R.id.ble_name);
mAddress = v.findViewById(R.id.ble_address);
v.setOnClickListener(ViewHolder.this);
}
@Override
public void onClick(View v) {
SP.putString(R.string.key_danars_address, item.device.getAddress());
SP.putString(R.string.key_danars_name, mName.getText().toString());
item.device.createBond();
RxBus.Companion.getINSTANCE().send(new EventDanaRSDeviceChange());
finish();
}
public void setData(BluetoothDeviceItem data) {
if (data != null) {
try {
String tTitle = data.device.getName();
if (tTitle == null || tTitle.equals("")) {
tTitle = "(unknown)";
} else if (tTitle.length() > 10) {
tTitle = tTitle.substring(0, 10);
}
mName.setText(tTitle);
mAddress.setText(data.device.getAddress());
item = data;
} catch (Exception ignored) {
}
}
}
}
}
//
private class BluetoothDeviceItem {
private BluetoothDevice device;
BluetoothDeviceItem(BluetoothDevice device) {
super();
this.device = device;
}
@Override
public boolean equals(Object o) {
if (device == null || !(o instanceof BluetoothDeviceItem)) {
return false;
}
BluetoothDeviceItem checkItem = (BluetoothDeviceItem) o;
if (checkItem.device == null) {
return false;
}
return stringEquals(device.getAddress(), checkItem.device.getAddress());
}
boolean stringEquals(String arg1, String arg2) {
try {
return arg1.equals(arg2);
} catch (Exception e) {
return false;
}
}
}
public static boolean isSNCheck(String sn) {
String regex = "^([a-zA-Z]{3})([0-9]{5})([a-zA-Z]{2})$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(sn);
return m.matches();
}
}

View file

@ -1,16 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.activities
import android.content.pm.ActivityInfo
import android.os.Bundle
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.plugins.pump.danaRS.dialogs.PairingProgressDialog
class PairingHelperActivity : NoSplashAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
PairingProgressDialog()
.setHelperActivity(this)
.show(supportFragmentManager, "PairingProgress")
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
}

View file

@ -1,109 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.ResourceHelper
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DanaRSMessageHashTable @Inject constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
danaRPump: DanaRPump,
danaRSPlugin: DanaRSPlugin,
activePlugin: ActivePluginProvider,
constraintChecker: ConstraintChecker,
detailedBolusInfoStorage: DetailedBolusInfoStorage,
injector: HasAndroidInjector,
dateUtil: DateUtil
) {
var messages: HashMap<Int, DanaRS_Packet> = HashMap()
fun put(message: DanaRS_Packet) {
messages[message.command] = message
}
fun findMessage(command: Int): DanaRS_Packet {
return messages[command] ?: DanaRS_Packet()
}
init {
put(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger))
put(DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump))
put(DanaRS_Packet_Basal_Get_Profile_Basal_Rate(aapsLogger, danaRPump))
put(DanaRS_Packet_Basal_Get_Profile_Number(aapsLogger, danaRPump))
put(DanaRS_Packet_Basal_Set_Basal_Rate(aapsLogger, arrayOf()))
put(DanaRS_Packet_Basal_Set_Profile_Basal_Rate(aapsLogger, 0, arrayOf()))
put(DanaRS_Packet_Basal_Set_Profile_Number(aapsLogger))
put(DanaRS_Packet_Basal_Set_Suspend_Off(aapsLogger))
put(DanaRS_Packet_Basal_Set_Suspend_On(aapsLogger))
put(DanaRS_Packet_Basal_Set_Temporary_Basal(aapsLogger))
put(DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil))
put(DanaRS_Packet_Bolus_Get_Bolus_Option(aapsLogger, rxBus, resourceHelper, danaRPump))
put(DanaRS_Packet_Bolus_Get_Initial_Bolus(aapsLogger))
put(DanaRS_Packet_Bolus_Get_Calculation_Information(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_CIR_CF_Array(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_Dual_Bolus(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_Extended_Bolus(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(aapsLogger, danaRPump))
put(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil))
put(DanaRS_Packet_Bolus_Set_Bolus_Option(aapsLogger))
put(DanaRS_Packet_Bolus_Set_Initial_Bolus(aapsLogger))
put(DanaRS_Packet_Bolus_Set_CIR_CF_Array(aapsLogger))
put(DanaRS_Packet_Bolus_Set_Dual_Bolus(aapsLogger))
put(DanaRS_Packet_Bolus_Set_Extended_Bolus(aapsLogger))
put(DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(aapsLogger))
put(DanaRS_Packet_Bolus_Set_Step_Bolus_Start(aapsLogger, danaRSPlugin, constraintChecker))
put(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin))
put(DanaRS_Packet_Etc_Keep_Connection(aapsLogger))
put(DanaRS_Packet_Etc_Set_History_Save(aapsLogger))
put(DanaRS_Packet_General_Delivery_Status(aapsLogger))
put(DanaRS_Packet_General_Get_Password(aapsLogger, danaRPump))
put(DanaRS_Packet_General_Initial_Screen_Information(aapsLogger, danaRPump))
put(DanaRS_Packet_Notify_Alarm(aapsLogger, resourceHelper))
put(DanaRS_Packet_Notify_Delivery_Complete(aapsLogger, rxBus, resourceHelper, danaRSPlugin))
put(DanaRS_Packet_Notify_Delivery_Rate_Display(aapsLogger, rxBus, resourceHelper, danaRSPlugin))
put(DanaRS_Packet_Notify_Missed_Bolus_Alarm(aapsLogger))
put(DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil))
put(DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump))
put(DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil))
put(DanaRS_Packet_Option_Set_User_Option(aapsLogger, danaRPump))
//put(new DanaRS_Packet_History_());
put(DanaRS_Packet_History_Alarm(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_All_History(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_Basal(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_Bolus(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_Review_Bolus_Avg(aapsLogger))
put(DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_Daily(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_General_Get_More_Information(aapsLogger, danaRPump, dateUtil))
put(DanaRS_Packet_General_Get_Pump_Check(aapsLogger, danaRPump, rxBus, resourceHelper))
put(DanaRS_Packet_General_Get_Shipping_Information(aapsLogger, danaRPump, dateUtil))
put(DanaRS_Packet_General_Get_Today_Delivery_Total(aapsLogger, danaRPump))
put(DanaRS_Packet_General_Get_User_Time_Change_Flag(aapsLogger))
put(DanaRS_Packet_History_Prime(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_Refill(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger))
put(DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(aapsLogger))
put(DanaRS_Packet_History_Suspend(aapsLogger, rxBus, dateUtil))
put(DanaRS_Packet_History_Temporary(aapsLogger, rxBus, dateUtil))
// APS
put(DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 0))
put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, 0))
put(DanaRS_Packet_APS_Set_Event_History(aapsLogger, dateUtil, 0, 0, 0, 0))
}
}

View file

@ -1,27 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class DanaRS_Packet_Basal_Get_Profile_Number(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER
aapsLogger.debug(LTag.PUMPCOMM, "Requesting active profile")
}
override fun handleMessage(data: ByteArray) {
danaRPump.activeProfile = byteArrayToInt(getBytes(data, DATA_START, 1))
aapsLogger.debug(LTag.PUMPCOMM, "Active profile: " + danaRPump.activeProfile)
}
override fun getFriendlyName(): String {
return "BASAL__GET_PROFILE_NUMBER"
}
}

View file

@ -1,35 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class DanaRS_Packet_Bolus_Get_Dual_Bolus(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
val error = byteArrayToInt(getBytes(data, DATA_START, 1))
danaRPump.bolusStep = byteArrayToInt(getBytes(data, DATA_START + 1, 2)) / 100.0
danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, DATA_START + 3, 2)) / 100.0
danaRPump.maxBolus = byteArrayToInt(getBytes(data, DATA_START + 5, 2)) / 100.0
val bolusIncrement = byteArrayToInt(getBytes(data, DATA_START + 7, 1)) / 100.0
failed = error != 0
aapsLogger.debug(LTag.PUMPCOMM, "Result: $error")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: ${danaRPump.bolusStep} U")
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: ${danaRPump.extendedBolusAbsoluteRate} U/h")
aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U")
aapsLogger.debug(LTag.PUMPCOMM, "bolusIncrement: $bolusIncrement U")
}
override fun getFriendlyName(): String {
return "BOLUS__GET_DUAL_BOLUS"
}
}

View file

@ -1,41 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class DanaRS_Packet_Bolus_Get_Extended_Bolus(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 1
val error = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 1
danaRPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
failed = error != 0
aapsLogger.debug(LTag.PUMPCOMM, "Result: $error")
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + danaRPump.extendedBolusAbsoluteRate + " U/h")
aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaRPump.bolusStep + " U")
}
override fun getFriendlyName(): String {
return "BOLUS__GET_EXTENDED_BOLUS"
}
}

View file

@ -1,49 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class DanaRS_Packet_Bolus_Get_Extended_Bolus_State(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 1
val error = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
danaRPump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01
dataIndex += dataSize
dataSize = 1
danaRPump.extendedBolusMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) * 30
dataIndex += dataSize
dataSize = 2
danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.extendedBolusSoFarInMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaRPump.extendedBolusDeliveredSoFar = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
failed = error != 0
aapsLogger.debug(LTag.PUMPCOMM, "Result: $error")
aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress)
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + danaRPump.extendedBolusAbsoluteRate + " U/h")
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus duration: " + danaRPump.extendedBolusMinutes + " min")
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far: " + danaRPump.extendedBolusSoFarInMinutes + " min")
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus delivered so far: " + danaRPump.extendedBolusDeliveredSoFar + " U")
}
override fun getFriendlyName(): String {
return "BOLUS__GET_EXTENDED_BOLUS_STATE"
}
}

View file

@ -1,61 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.DateUtil
import java.util.*
class DanaRS_Packet_Bolus_Get_Step_Bolus_Information(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump,
private val dateUtil: DateUtil
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
var dataIndex = DATA_START
var dataSize = 1
val error = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
val bolusType = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaRPump.initialBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
val lbt = Date() // it doesn't provide day only hour+min, workaround: expecting today
dataIndex += dataSize
dataSize = 1
lbt.hours = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
lbt.minutes = byteArrayToInt(getBytes(data, dataIndex, dataSize))
danaRPump.lastBolusTime = lbt.time
dataIndex += dataSize
dataSize = 2
danaRPump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 1
danaRPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
failed = error != 0
aapsLogger.debug(LTag.PUMPCOMM, "Result: $error")
aapsLogger.debug(LTag.PUMPCOMM, "BolusType: $bolusType")
aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount: " + danaRPump.initialBolusAmount + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + dateUtil.dateAndTimeString(danaRPump.lastBolusTime))
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount)
aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaRPump.bolusStep + " U")
}
override fun getFriendlyName(): String {
return "BOLUS__GET_STEP_BOLUS_INFORMATION"
}
}

View file

@ -1,63 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.DateUtil
import java.util.*
class DanaRS_Packet_General_Get_More_Information(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump,
private val dateUtil: DateUtil
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
if (data.size < 15) {
failed = true
return
}
var dataIndex = DATA_START
var dataSize = 2
danaRPump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
dataIndex += dataSize
dataSize = 2
danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 1
danaRPump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01
dataIndex += dataSize
dataSize = 2
danaRPump.extendedBolusRemainingMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
//val remainRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
val lastBolusTime = Date() // it doesn't provide day only hour+min, workaround: expecting today
dataIndex += dataSize
dataSize = 1
lastBolusTime.hours = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
lastBolusTime.minutes = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaRPump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble()
// On DanaRS DailyUnits can't be more than 160
if (danaRPump.dailyTotalUnits > 160) failed = true
aapsLogger.debug(LTag.PUMPCOMM, "Daily total units: " + danaRPump.dailyTotalUnits.toString() + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Is extended in progress: " + danaRPump.isExtendedInProgress)
aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus remaining minutes: " + danaRPump.extendedBolusRemainingMinutes)
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + dateUtil.dateAndTimeAndSecondsString(lastBolusTime.time))
aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount)
}
override fun getFriendlyName(): String {
return "REVIEW__GET_MORE_INFORMATION"
}
}

View file

@ -1,42 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_General_Get_Shipping_Information(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump,
private val dateUtil: DateUtil
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
if (data.size < 18) {
failed = true
return
} else failed = false
var dataIndex = DATA_START
var dataSize = 10
danaRPump.serialNumber = stringFromBuff(data, dataIndex, dataSize)
dataIndex += dataSize
dataSize = 3
danaRPump.shippingDate = dateFromBuff(data, dataIndex)
dataIndex += dataSize
dataSize = 3
danaRPump.shippingCountry = asciiStringFromBuff(data, dataIndex, dataSize)
aapsLogger.debug(LTag.PUMPCOMM, "Serial number: " + danaRPump.serialNumber)
aapsLogger.debug(LTag.PUMPCOMM, "Shipping date: " + dateUtil.dateAndTimeString(danaRPump.shippingDate))
aapsLogger.debug(LTag.PUMPCOMM, "Shipping country: " + danaRPump.shippingCountry)
}
override fun getFriendlyName(): String {
return "REVIEW__GET_SHIPPING_INFORMATION"
}
}

View file

@ -1,40 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class DanaRS_Packet_General_Get_Today_Delivery_Total(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
if (data.size < 8) {
failed = true
return
} else failed = false
var dataIndex = DATA_START
var dataSize = 2
danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Daily total bolus: " + danaRPump.dailyTotalBolusUnits + " U")
aapsLogger.debug(LTag.PUMPCOMM, "Daily total basal: " + danaRPump.dailyTotalBasalUnits + " U")
}
override fun getFriendlyName(): String {
return "REVIEW__GET_TODAY_DELIVERY_TOTAL"
}
}

View file

@ -1,71 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump
class DanaRS_Packet_General_Initial_Screen_Information(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
type = BleCommandUtil.DANAR_PACKET__TYPE_RESPONSE
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
if (data.size < 17) {
failed = true
return
} else failed = false
var dataIndex = DATA_START
var dataSize = 1
val status = byteArrayToInt(getBytes(data, dataIndex, dataSize))
danaRPump.pumpSuspended = status and 0x01 == 0x01
danaRPump.isTempBasalInProgress = status and 0x10 == 0x10
danaRPump.isExtendedInProgress = status and 0x04 == 0x04
danaRPump.isDualBolusInProgress = status and 0x08 == 0x08
dataIndex += dataSize
dataSize = 2
danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.maxDailyTotalUnits = (byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0).toInt()
dataIndex += dataSize
dataSize = 2
danaRPump.reservoirRemainingUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.currentBasal = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 1
danaRPump.tempBasalPercent = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 1
danaRPump.batteryRemaining = byteArrayToInt(getBytes(data, dataIndex, dataSize))
dataIndex += dataSize
dataSize = 2
danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
dataIndex += dataSize
dataSize = 2
danaRPump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0
aapsLogger.debug(LTag.PUMPCOMM, "Pump suspended: " + danaRPump.pumpSuspended)
aapsLogger.debug(LTag.PUMPCOMM, "Temp basal in progress: " + danaRPump.isTempBasalInProgress)
aapsLogger.debug(LTag.PUMPCOMM, "Extended in progress: " + danaRPump.isExtendedInProgress)
aapsLogger.debug(LTag.PUMPCOMM, "Dual in progress: " + danaRPump.isDualBolusInProgress)
aapsLogger.debug(LTag.PUMPCOMM, "Daily units: " + danaRPump.dailyTotalUnits)
aapsLogger.debug(LTag.PUMPCOMM, "Max daily units: " + danaRPump.maxDailyTotalUnits)
aapsLogger.debug(LTag.PUMPCOMM, "Reservoir remaining units: " + danaRPump.reservoirRemainingUnits)
aapsLogger.debug(LTag.PUMPCOMM, "Battery: " + danaRPump.batteryRemaining)
aapsLogger.debug(LTag.PUMPCOMM, "Current basal: " + danaRPump.currentBasal)
aapsLogger.debug(LTag.PUMPCOMM, "Temp basal percent: " + danaRPump.tempBasalPercent)
aapsLogger.debug(LTag.PUMPCOMM, "Extended absolute rate: " + danaRPump.extendedBolusAbsoluteRate)
}
override fun getFriendlyName(): String {
return "REVIEW__INITIAL_SCREEN_INFORMATION"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Alarm @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__ALARM"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_All_History(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__ALL_HISTORY"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Basal @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__BASAL"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Blood_Glucose @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__BLOOD_GLUCOSE"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Bolus @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__BOLUS"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Carbohydrate @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__CARBOHYDRATE"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Daily @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__DAILY"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Prime @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__PRIME"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Refill @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__REFILL"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Suspend @JvmOverloads constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__SUSPEND"
}
}

View file

@ -1,24 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.comm
import com.cozmo.danar.util.BleCommandUtil
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.utils.DateUtil
class DanaRS_Packet_History_Temporary(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
dateUtil: DateUtil,
from: Long = 0
) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun getFriendlyName(): String {
return "REVIEW__TEMPORARY"
}
}

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