Merge pull request #2638 from MilosKozak/danarefactor

Dana: refactor to modules
This commit is contained in:
Milos Kozak 2020-05-11 20:36:50 +02:00 committed by GitHub
commit b5770d8e1b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
683 changed files with 9401 additions and 8647 deletions

1
.gitignore vendored
View file

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

View file

@ -128,7 +128,7 @@ android {
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" />
@ -149,22 +132,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
@ -152,16 +147,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 +158,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

@ -31,9 +31,9 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.dana.comm.RecordTypes;
import info.nightscout.androidaps.data.NonOverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
@ -46,13 +46,13 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.ProfileStore;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset;
import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID;
@ -61,7 +61,6 @@ import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.PercentageSplitter;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils;
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
@ -483,7 +482,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
Dao<TDD, String> dao = getDaoTDD();
dao.createOrUpdate(tdd);
} catch (SQLException e) {
ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception");
log.error("Unhandled exception", e);
}
}
@ -1008,7 +1006,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void createTempBasalFromJsonIfNotExists(JSONObject trJson) {
try {
if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal
ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance())
ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance())
.source(Source.NIGHTSCOUT)
.date(trJson.getLong("mills"))
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0)
@ -1023,7 +1021,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
createOrUpdate(extendedBolus);
} else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end
ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance());
ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance());
extendedBolus.source = Source.NIGHTSCOUT;
extendedBolus.date = trJson.getLong("mills");
extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0;
@ -1038,7 +1036,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
createOrUpdate(extendedBolus);
} else {
TemporaryBasal tempBasal = new TemporaryBasal( MainApp.instance())
TemporaryBasal tempBasal = new TemporaryBasal(StaticInjector.Companion.getInstance())
.date(trJson.getLong("mills"))
.source(Source.NIGHTSCOUT)
.pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0);
@ -1313,7 +1311,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
*/
public void createExtendedBolusFromJsonIfNotExists(JSONObject json) {
ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(MainApp.instance(), json);
ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(StaticInjector.Companion.getInstance(), json);
if (extendedBolus != null)
createOrUpdate(extendedBolus);
}
@ -1505,7 +1503,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
List<CareportalEvent> list = getDaoCareportalEvents().query(preparedQuery);
CareportalEvent careportalEvent;
if (list.size() == 0) {
careportalEvent = new CareportalEvent(MainApp.instance());
careportalEvent = new CareportalEvent(StaticInjector.Companion.getInstance());
careportalEvent.source = Source.NIGHTSCOUT;
if (L.isEnabled(LTag.DATABASE))
log.debug("Adding CareportalEvent record to database: " + trJson.toString());
@ -1733,9 +1731,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
*/
public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, JSONObject trJson) {
public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, NSUpload nsUpload, JSONObject trJson) {
try {
ProfileSwitch profileSwitch = new ProfileSwitch(MainApp.instance());
ProfileSwitch profileSwitch = new ProfileSwitch(StaticInjector.Companion.getInstance());
profileSwitch.date = trJson.getLong("mills");
if (trJson.has("duration"))
profileSwitch.durationInMinutes = trJson.getInt("duration");
@ -1759,7 +1757,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
if (L.isEnabled(LTag.DATABASE))
log.debug("Profile switch prefilled with JSON from local store");
// Update data in NS
NSUpload.updateProfileSwitch(profileSwitch);
nsUpload.updateProfileSwitch(profileSwitch);
} else {
if (L.isEnabled(LTag.DATABASE))
log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString());

View file

@ -0,0 +1,68 @@
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();
}
}

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

@ -19,17 +19,7 @@ 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 treatmentServiceInjector(): TreatmentService

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

@ -14,7 +14,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

@ -22,6 +22,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;
@ -41,9 +42,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;
@ -53,7 +56,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.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
@ -65,15 +67,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;
@ -89,6 +91,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 CompositeDisposable disposable = new CompositeDisposable();
@ -101,21 +104,15 @@ public class LoopPlugin extends PluginBase {
private boolean isSuperBolus;
private boolean isDisconnected;
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(
@ -135,6 +132,7 @@ public class LoopPlugin extends PluginBase {
IobCobCalculatorPlugin iobCobCalculatorPlugin,
ReceiverStatusStore receiverStatusStore,
FabricPrivacy fabricPrivacy,
NSUpload nsUpload,
HardLimits hardLimits
) {
super(new PluginDescription()
@ -161,6 +159,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);
@ -292,7 +291,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");
@ -403,18 +402,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));
@ -437,27 +436,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);
@ -472,8 +471,8 @@ public class LoopPlugin extends PluginBase {
}
});
} else {
lastRun.tbrSetByPump = null;
lastRun.smbSetByPump = null;
lastRun.setTbrSetByPump(null);
lastRun.setSmbSetByPump(null);
}
} else {
if (resultAfterConstraints.isChangeRequested() && allowNotification) {
@ -531,15 +530,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());
@ -773,6 +772,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

@ -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

@ -33,6 +33,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 +120,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 +155,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 = Html.fromHtml(resourceHelper.gs(R.string.queue) + " <b>" + uploadQueue.size() + "</b>");
queueTextView.setText(queuetext);
statusTextView.setText(nsClientPlugin.status);
}

View file

@ -253,10 +253,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

@ -31,15 +31,15 @@ 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;
@ -83,7 +83,7 @@ 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;
@ -91,6 +91,7 @@ public class NSClientService extends DaggerService {
@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();
@ -124,8 +125,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 +142,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();
@ -528,7 +527,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 +603,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 +635,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 +651,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 +683,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 +694,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 +708,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)
@ -795,7 +794,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 +803,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,7 +813,7 @@ 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();
@ -852,7 +850,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 +860,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 +871,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 +885,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 +895,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 +905,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 +914,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 +927,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 +938,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 +952,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 +964,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 +978,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 +990,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 +1002,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 +1012,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);
}
}

View file

@ -20,6 +20,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
@ -344,8 +345,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)
@ -442,7 +444,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
@ -662,9 +664,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))
}
@ -341,18 +341,18 @@ class OverviewMenus @Inject constructor(
return true
}
resourceHelper.gs(R.string.disconnectpumpfor3h) -> {
resourceHelper.gs(R.string.disconnectpumpfor3h) -> {
aapsLogger.debug("USER ENTRY: DISCONNECT 3h")
loopPlugin.disconnectPump(180, profile)
rxBus.send(EventRefreshOverview("suspendmenu"))
return true
}
resourceHelper.gs(R.string.careportal_profileswitch) -> {
resourceHelper.gs(R.string.careportal_profileswitch) -> {
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)
@ -361,7 +361,7 @@ class OverviewMenus @Inject constructor(
pvd.show(manager, "ProfileViewDialog")
}
resourceHelper.gs(R.string.eatingsoon) -> {
resourceHelper.gs(R.string.eatingsoon) -> {
aapsLogger.debug("USER ENTRY: TEMP TARGET EATING SOON")
val target = Profile.toMgdl(defaultValueHelper.determineEatingSoonTT(), profileFunction.getUnits())
val tempTarget = TempTarget()

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

@ -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());
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);
}
boolean checkOK = blePrecheck.prerequisitesCheck(this);
// 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);
}
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
filters = Arrays.asList(new ScanFilter.Builder().setServiceUuid(
ParcelUuid.fromString(GattAttributes.SERVICE_RADIO)).build());
}
if (checkOK) {
mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
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

@ -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

@ -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"
}
}

View file

@ -1,60 +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_Option_Set_User_Option(
private val aapsLogger: AAPSLogger,
private val danaRPump: DanaRPump
) : DanaRS_Packet() {
init {
opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION
aapsLogger.debug(LTag.PUMPCOMM, "Setting user settings")
}
override fun getRequestParams(): ByteArray {
aapsLogger.debug(LTag.PUMPCOMM,
"UserOptions:" + (System.currentTimeMillis() - danaRPump.lastConnection) / 1000 + " s ago"
+ "\ntimeDisplayType:" + danaRPump.timeDisplayType
+ "\nbuttonScroll:" + danaRPump.buttonScrollOnOff
+ "\ntimeDisplayType:" + danaRPump.timeDisplayType
+ "\nlcdOnTimeSec:" + danaRPump.lcdOnTimeSec
+ "\nbacklight:" + danaRPump.backlightOnTimeSec
+ "\ndanaRPumpUnits:" + danaRPump.units
+ "\nlowReservoir:" + danaRPump.lowReservoirRate)
val request = ByteArray(13)
request[0] = (danaRPump.timeDisplayType and 0xff).toByte()
request[1] = (danaRPump.buttonScrollOnOff and 0xff).toByte()
request[2] = (danaRPump.beepAndAlarm and 0xff).toByte()
request[3] = (danaRPump.lcdOnTimeSec and 0xff).toByte()
request[4] = (danaRPump.backlightOnTimeSec and 0xff).toByte()
request[5] = (danaRPump.selectedLanguage and 0xff).toByte()
request[6] = (danaRPump.units and 0xff).toByte()
request[7] = (danaRPump.shutdownHour and 0xff).toByte()
request[8] = (danaRPump.lowReservoirRate and 0xff).toByte()
request[9] = (danaRPump.cannulaVolume and 0xff).toByte()
request[10] = (danaRPump.cannulaVolume ushr 8 and 0xff).toByte()
request[11] = (danaRPump.refillAmount and 0xff).toByte()
request[12] = (danaRPump.refillAmount ushr 8 and 0xff).toByte()
return request
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override fun getFriendlyName(): String {
return "OPTION__SET_USER_OPTION"
}
}

View file

@ -1,682 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.services;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import com.cozmo.danar.util.BleCommandUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess;
import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 23.09.2017.
*/
public class BLEComm {
private Logger log = StacktraceLoggerWrapper.getLogger(LTag.PUMPBTCOMM);
private final long WRITE_DELAY_MILLIS = 50;
private String UART_READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb";
private String UART_WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb";
private final byte PACKET_START_BYTE = (byte) 0xA5;
private final byte PACKET_END_BYTE = (byte) 0x5A;
private Context context;
private DanaRPump danaRPump;
private DanaRSMessageHashTable danaRSMessageHashTable;
public BLEComm(Context context, DanaRSMessageHashTable danaRSMessageHashTable, DanaRPump danaRPump) {
this.context = context;
this.danaRPump = danaRPump;
this.danaRSMessageHashTable = danaRSMessageHashTable;
initialize();
}
private ScheduledFuture<?> scheduledDisconnection = null;
private DanaRS_Packet processsedMessage = null;
private final ArrayList<byte[]> mSendQueue = new ArrayList<>();
private BluetoothManager mBluetoothManager = null;
private BluetoothAdapter mBluetoothAdapter = null;
private String mBluetoothDeviceName = null;
private BluetoothGatt mBluetoothGatt = null;
protected boolean isConnected = false;
protected boolean isConnecting = false;
private BluetoothGattCharacteristic UART_Read;
private BluetoothGattCharacteristic UART_Write;
private boolean initialize() {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Initializing BLEComm.");
if (mBluetoothManager == null) {
mBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE));
if (mBluetoothManager == null) {
log.error("Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
log.error("Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
public boolean isConnected() {
return isConnected;
}
public boolean isConnecting() {
return isConnecting;
}
public boolean connect(String from, String address, Object confirmConnect) {
BluetoothManager tBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE));
if (tBluetoothManager == null) {
return false;
}
BluetoothAdapter tBluetoothAdapter = tBluetoothManager.getAdapter();
if (tBluetoothAdapter == null) {
return false;
}
if (mBluetoothAdapter == null) {
if (!initialize()) {
return false;
}
}
if (address == null) {
log.error("unspecified address.");
return false;
}
isConnecting = true;
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
log.error("Device not found. Unable to connect from: " + from);
return false;
}
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Trying to create a new connection from: " + from);
mBluetoothDeviceName = device.getName();
mBluetoothGatt = device.connectGatt(context, false, mGattCallback);
setCharacteristicNotification(getUARTReadBTGattChar(), true);
return true;
}
public void stopConnecting() {
isConnecting = false;
}
public synchronized void disconnect(String from) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("disconnect from: " + from);
// cancel previous scheduled disconnection to prevent closing upcomming connection
if (scheduledDisconnection != null)
scheduledDisconnection.cancel(false);
scheduledDisconnection = null;
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.error("disconnect not possible: (mBluetoothAdapter == null) " + (mBluetoothAdapter == null));
log.error("disconnect not possible: (mBluetoothGatt == null) " + (mBluetoothGatt == null));
return;
}
setCharacteristicNotification(getUARTReadBTGattChar(), false);
mBluetoothGatt.disconnect();
isConnected = false;
SystemClock.sleep(2000);
}
public synchronized void close() {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("BluetoothAdapter close");
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
private String getConnectDeviceName() {
return mBluetoothDeviceName;
}
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
onConnectionStateChangeSynchronized(gatt, status, newState); // call it synchronized
}
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("onServicesDiscovered");
if (status == BluetoothGatt.GATT_SUCCESS) {
findCharacteristic();
}
SendPumpCheck();
// 1st message sent to pump after connect
}
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("onCharacteristicRead" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : ""));
addToReadBuffer(characteristic.getValue());
readDataParsing();
}
public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("onCharacteristicChanged" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : ""));
addToReadBuffer(characteristic.getValue());
new Thread(() -> readDataParsing()).start();
}
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : ""));
new Thread(() -> {
synchronized (mSendQueue) {
// after message sent, check if there is the rest of the message waiting and send it
if (mSendQueue.size() > 0) {
byte[] bytes = mSendQueue.get(0);
mSendQueue.remove(0);
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
}
}).start();
}
};
private synchronized void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("setCharacteristicNotification");
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.error("BluetoothAdapter not initialized_ERROR");
isConnecting = false;
isConnected = false;
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
public synchronized void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("readCharacteristic");
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.error("BluetoothAdapter not initialized_ERROR");
isConnecting = false;
isConnected = false;
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
private synchronized void writeCharacteristic_NO_RESPONSE(final BluetoothGattCharacteristic characteristic, final byte[] data) {
new Thread(() -> {
SystemClock.sleep(WRITE_DELAY_MILLIS);
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.error("BluetoothAdapter not initialized_ERROR");
isConnecting = false;
isConnected = false;
return;
}
characteristic.setValue(data);
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data));
mBluetoothGatt.writeCharacteristic(characteristic);
}).start();
}
private BluetoothGattCharacteristic getUARTReadBTGattChar() {
if (UART_Read == null) {
UART_Read = new BluetoothGattCharacteristic(UUID.fromString(UART_READ_UUID), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0);
}
return UART_Read;
}
private BluetoothGattCharacteristic getUARTWriteBTGattChar() {
if (UART_Write == null) {
UART_Write = new BluetoothGattCharacteristic(UUID.fromString(UART_WRITE_UUID), BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, 0);
}
return UART_Write;
}
private List<BluetoothGattService> getSupportedGattServices() {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("getSupportedGattServices");
if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) {
log.error("BluetoothAdapter not initialized_ERROR");
isConnecting = false;
isConnected = false;
return null;
}
return mBluetoothGatt.getServices();
}
private void findCharacteristic() {
List<BluetoothGattService> gattServices = getSupportedGattServices();
if (gattServices == null) {
return;
}
String uuid;
for (BluetoothGattService gattService : gattServices) {
List<BluetoothGattCharacteristic> gattCharacteristics = gattService.getCharacteristics();
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
uuid = gattCharacteristic.getUuid().toString();
if (UART_READ_UUID.equals(uuid)) {
UART_Read = gattCharacteristic;
setCharacteristicNotification(UART_Read, true);
}
if (UART_WRITE_UUID.equals(uuid)) {
UART_Write = gattCharacteristic;
}
}
}
}
private synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("onConnectionStateChange");
if (newState == BluetoothProfile.STATE_CONNECTED) {
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
close();
isConnected = false;
isConnecting = false;
RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED));
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected
}
}
private final byte[] readBuffer = new byte[1024];
private int bufferLength = 0;
private void addToReadBuffer(byte[] buffer) {
//log.debug("addToReadBuffer " + DanaRS_Packet.toHexString(buffer));
if (buffer == null || buffer.length == 0) {
return;
}
synchronized (readBuffer) {
// Append incomming data to input buffer
System.arraycopy(buffer, 0, readBuffer, bufferLength, buffer.length);
bufferLength += buffer.length;
}
}
private void readDataParsing() {
boolean startSignatureFound = false, packetIsValid = false;
boolean isProcessing;
isProcessing = true;
while (isProcessing) {
int length = 0;
byte[] inputBuffer = null;
synchronized (readBuffer) {
// Find packet start [A5 A5]
if (bufferLength >= 6) {
for (int idxStartByte = 0; idxStartByte < bufferLength - 2; idxStartByte++) {
if ((readBuffer[idxStartByte] == PACKET_START_BYTE) && (readBuffer[idxStartByte + 1] == PACKET_START_BYTE)) {
if (idxStartByte > 0) {
// if buffer doesn't start with signature remove the leading trash
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Shifting the input buffer by " + idxStartByte + " bytes");
System.arraycopy(readBuffer, idxStartByte, readBuffer, 0, bufferLength - idxStartByte);
bufferLength -= idxStartByte;
}
startSignatureFound = true;
break;
}
}
}
// A5 A5 LEN TYPE CODE PARAMS CHECKSUM1 CHECKSUM2 5A 5A
// ^---- LEN -----^
// total packet length 2 + 1 + readBuffer[2] + 2 + 2
if (startSignatureFound) {
length = readBuffer[2];
// test if there is enough data loaded
if (length + 7 > bufferLength)
return;
// Verify packed end [5A 5A]
if ((readBuffer[length + 5] == PACKET_END_BYTE) && (readBuffer[length + 6] == PACKET_END_BYTE)) {
packetIsValid = true;
}
}
if (packetIsValid) {
inputBuffer = new byte[length + 7];
// copy packet to input buffer
System.arraycopy(readBuffer, 0, inputBuffer, 0, length + 7);
// Cut off the message from readBuffer
try {
System.arraycopy(readBuffer, length + 7, readBuffer, 0, bufferLength - (length + 7));
} catch (Exception e) {
log.error("length: " + length + "bufferLength: " + bufferLength);
throw e;
}
bufferLength -= (length + 7);
// now we have encrypted packet in inputBuffer
}
}
if (packetIsValid) {
try {
// decrypt the packet
inputBuffer = BleCommandUtil.getInstance().getDecryptedPacket(inputBuffer);
if (inputBuffer == null) {
log.error("Null decryptedInputBuffer");
return;
}
switch (inputBuffer[0]) {
// initial handshake packet
case (byte) BleCommandUtil.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE:
switch (inputBuffer[1]) {
// 1st packet
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK:
if (inputBuffer.length == 4 && inputBuffer[2] == 'O' && inputBuffer[3] == 'K') {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(inputBuffer));
// Grab pairing key from preferences if exists
String pairingKey = SP.getString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, null);
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Using stored pairing key: " + pairingKey);
if (pairingKey != null) {
byte[] encodedPairingKey = DanaRS_Packet.hexToBytes(pairingKey);
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY, encodedPairingKey, null);
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
} else {
// Stored pairing key does not exists, request pairing
SendPairingRequest();
}
} else if (inputBuffer.length == 6 && inputBuffer[2] == 'P' && inputBuffer[3] == 'U' && inputBuffer[4] == 'M' && inputBuffer[5] == 'P') {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumperror)));
NSUpload.uploadError(MainApp.gs(R.string.pumperror));
Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
} else if (inputBuffer.length == 6 && inputBuffer[2] == 'B' && inputBuffer[3] == 'U' && inputBuffer[4] == 'S' && inputBuffer[5] == 'Y') {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumpbusy)));
} else {
// ERROR in response, wrong serial number
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.connectionerror)));
SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName);
Notification n = new Notification(Notification.WRONGSERIALNUMBER, MainApp.gs(R.string.wrongpassword), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
}
break;
// 2nd packet, pairing key
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY:
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(inputBuffer));
if (inputBuffer[2] == (byte) 0x00) {
// Paring is not requested, sending time info
SendTimeInfo();
} else {
// Pairing on pump is requested
SendPairingRequest();
}
break;
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST:
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer));
if (inputBuffer[2] != (byte) 0x00) {
disconnect("passkey request failed");
}
break;
// Paring response, OK button on pump pressed
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN:
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer));
// Paring is successfull, sending time info
RxBus.Companion.getINSTANCE().send(new EventDanaRSPairingSuccess());
SendTimeInfo();
byte[] pairingKey = {inputBuffer[2], inputBuffer[3]};
// store pairing key to preferences
SP.putString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, DanaRS_Packet.bytesToHex(pairingKey));
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey));
break;
// time and user password information. last packet in handshake
case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION:
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__TIME_INFORMATION " + /*message.getMessageName() + " " + */ DanaRS_Packet.toHexString(inputBuffer));
int size = inputBuffer.length;
int pass = ((inputBuffer[size - 1] & 0x000000FF) << 8) + ((inputBuffer[size - 2] & 0x000000FF));
pass = pass ^ 3463;
danaRPump.setRsPassword(Integer.toHexString(pass));
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("Pump user password: " + Integer.toHexString(pass));
RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED));
isConnected = true;
isConnecting = false;
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("RS connected and status read");
break;
}
break;
// common data packet
default:
DanaRS_Packet message;
// Retrieve message code from received buffer and last message sent
int originalCommand = processsedMessage != null ? processsedMessage.getCommand() : 0xFFFF;
int receivedCommand = DanaRS_Packet.getCommand(inputBuffer);
if (originalCommand == receivedCommand) {
// it's response to last message
message = processsedMessage;
} else {
// it's not response to last message, create new instance
message = danaRSMessageHashTable.findMessage(receivedCommand);
}
if (message != null) {
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer));
// process received data
message.handleMessage(inputBuffer);
message.setReceived();
synchronized (message) {
// notify to sendMessage
message.notify();
}
} else {
log.error("Unknown message received " + DanaRS_Packet.toHexString(inputBuffer));
}
break;
}
} catch (Exception e) {
log.error("Unhandled exception", e);
}
startSignatureFound = false;
packetIsValid = false;
if (bufferLength < 6) {
// stop the loop
isProcessing = false;
}
} else {
// stop the loop
isProcessing = false;
}
}
}
public void sendMessage(DanaRS_Packet message) {
processsedMessage = message;
if (message == null)
return;
byte[] command = {(byte) message.getType(), (byte) message.getOpCode()};
byte[] params = message.getRequestParams();
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug(">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params));
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(message.getOpCode(), params, null);
// If there is another message not completely sent, add to queue only
if (mSendQueue.size() > 0) {
// Split to parts per 20 bytes max
for (; ; ) {
if (bytes.length > 20) {
byte[] addBytes = new byte[20];
System.arraycopy(bytes, 0, addBytes, 0, addBytes.length);
byte[] reBytes = new byte[bytes.length - addBytes.length];
System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length);
bytes = reBytes;
synchronized (mSendQueue) {
mSendQueue.add(addBytes);
}
} else {
synchronized (mSendQueue) {
mSendQueue.add(bytes);
}
break;
}
}
} else {
if (bytes.length > 20) {
// Cut first 20 bytes
byte[] sendBytes = new byte[20];
System.arraycopy(bytes, 0, sendBytes, 0, sendBytes.length);
byte[] reBytes = new byte[bytes.length - sendBytes.length];
System.arraycopy(bytes, sendBytes.length, reBytes, 0, reBytes.length);
bytes = reBytes;
// and send
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), sendBytes);
// The rest split to parts per 20 bytes max
for (; ; ) {
if (bytes.length > 20) {
byte[] addBytes = new byte[20];
System.arraycopy(bytes, 0, addBytes, 0, addBytes.length);
reBytes = new byte[bytes.length - addBytes.length];
System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length);
bytes = reBytes;
synchronized (mSendQueue) {
mSendQueue.add(addBytes);
}
} else {
synchronized (mSendQueue) {
mSendQueue.add(bytes);
}
break;
}
}
} else {
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
}
// The rest from queue is send from onCharasteristicWrite (after sending 1st part)
synchronized (message) {
try {
message.wait(5000);
} catch (InterruptedException e) {
log.error("sendMessage InterruptedException", e);
log.error("Unhandled exception", e);
}
}
//SystemClock.sleep(200);
if (!message.isReceived()) {
log.warn("Reply not received " + message.getFriendlyName());
message.handleMessageNotReceived();
}
}
private void SendPairingRequest() {
// Start activity which is waiting 20sec
// On pump pairing request is displayed and is waiting for conformation
Intent i = new Intent();
i.setClass(MainApp.instance(), PairingHelperActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainApp.instance().startActivity(i);
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null);
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
private void SendPumpCheck() {
// 1st message sent to pump after connect
String devicename = getConnectDeviceName();
if (devicename == null || devicename.equals("")) {
Notification n = new Notification(Notification.DEVICENOTPAIRED, MainApp.gs(R.string.pairfirst), Notification.URGENT);
RxBus.Companion.getINSTANCE().send(new EventNewNotification(n));
return;
}
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, devicename);
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug(">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
private void SendTimeInfo() {
byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, null, null);
if (L.isEnabled(LTag.PUMPBTCOMM))
log.debug(">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes));
writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes);
}
}

View file

@ -1,566 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRS.services;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
import javax.inject.Inject;
import dagger.android.DaggerService;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.ErrorHelperActivity;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePluginProvider;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.interfaces.ProfileFunction;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRNewStatus;
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_Basal_Set_Temporary_Basal;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_History_Events;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_Set_Event_History;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Basal_Rate;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Profile_Number;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Temporary_Basal_State;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Profile_Basal_Rate;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Profile_Number;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Temporary_Basal;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Bolus_Option;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_CIR_CF_Array;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Calculation_Information;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Extended_Bolus_State;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Step_Bolus_Information;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Start;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Stop;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Get_Pump_Check;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Get_Shipping_Information;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Initial_Screen_Information;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Set_History_Upload_Mode;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Alarm;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Basal;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Blood_Glucose;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Bolus;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Carbohydrate;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Daily;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Prime;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Refill;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Suspend;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Get_Pump_Time;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Get_User_Option;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Set_Pump_Time;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
public class DanaRSService extends DaggerService {
@Inject HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger;
@Inject RxBusWrapper rxBus;
@Inject SP sp;
@Inject ResourceHelper resourceHelper;
@Inject ProfileFunction profileFunction;
@Inject CommandQueueProvider commandQueue;
@Inject Context context;
@Inject DanaRSPlugin danaRSPlugin;
@Inject DanaRPump danaRPump;
@Inject DanaRSMessageHashTable danaRSMessageHashTable;
@Inject ActivePluginProvider activePlugin;
@Inject ConstraintChecker constraintChecker;
@Inject DetailedBolusInfoStorage detailedBolusInfoStorage;
@Inject DateUtil dateUtil;
private CompositeDisposable disposable = new CompositeDisposable();
private BLEComm bleComm;
private IBinder mBinder = new LocalBinder();
private Treatment bolusingTreatment = null;
private long lastHistoryFetched = 0;
private long lastApproachingDailyLimit = 0;
@Override
public void onCreate() {
super.onCreate();
bleComm = new BLEComm(this, danaRSMessageHashTable, danaRPump);
disposable.add(rxBus
.toObservable(EventAppExit.class)
.observeOn(Schedulers.io())
.subscribe(event -> {
aapsLogger.debug(LTag.PUMPCOMM, "EventAppExit received");
stopSelf();
}, exception -> FabricPrivacy.getInstance().logException(exception))
);
}
@Override
public void onDestroy() {
disposable.clear();
super.onDestroy();
}
public boolean isConnected() {
return bleComm.isConnected;
}
public boolean isConnecting() {
return bleComm.isConnecting;
}
public boolean connect(String from, String address, Object confirmConnect) {
return bleComm.connect(from, address, confirmConnect);
}
public void stopConnecting() {
bleComm.stopConnecting();
}
public void disconnect(String from) {
bleComm.disconnect(from);
}
@SuppressWarnings("unused")
public void sendMessage(DanaRS_Packet message) {
bleComm.sendMessage(message);
}
public void getPumpStatus() {
try {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus)));
bleComm.sendMessage(new DanaRS_Packet_General_Initial_Screen_Information(aapsLogger, danaRPump));
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump));
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)); // last bolus, bolusStep, maxBolus
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil));
danaRPump.setLastConnection(System.currentTimeMillis());
Profile profile = profileFunction.getProfile();
PumpInterface pump = activePlugin.getActivePump();
if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal
if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) {
rxBus.send(new EventProfileNeedsUpdate());
}
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime)));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil));
long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L;
if (danaRPump.getPumpTime() == 0) {
// initial handshake was not successfull
// deinitialize pump
danaRPump.setLastConnection(0);
rxBus.send(new EventDanaRNewStatus());
rxBus.send(new EventInitializationChanged());
return;
}
long now = System.currentTimeMillis();
if (danaRPump.getLastSettingsRead() + 60 * 60 * 1000L < now || !pump.isInitialized()) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings)));
bleComm.sendMessage(new DanaRS_Packet_General_Get_Shipping_Information(aapsLogger, danaRPump, dateUtil)); // serial no
bleComm.sendMessage(new DanaRS_Packet_General_Get_Pump_Check(aapsLogger, danaRPump, rxBus, resourceHelper)); // firmware
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Profile_Number(aapsLogger, danaRPump));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Bolus_Option(aapsLogger, rxBus, resourceHelper, danaRPump)); // isExtendedEnabled
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Calculation_Information(aapsLogger, danaRPump)); // target
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_CIR_CF_Array(aapsLogger, danaRPump));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)); // Getting user options
danaRPump.setLastSettingsRead(now);
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds");
if (Math.abs(timeDiff) > 3) {
if (Math.abs(timeDiff) > 60 * 60 * 1.5) {
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds - large difference");
//If time-diff is very large, warn user until we can synchronize history readings properly
Intent i = new Intent(context, ErrorHelperActivity.class);
i.putExtra("soundid", R.raw.error);
i.putExtra("status", resourceHelper.gs(R.string.largetimediff));
i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
//deinitialize pump
danaRPump.setLastConnection(0);
rxBus.send(new EventDanaRNewStatus());
rxBus.send(new EventInitializationChanged());
return;
} else {
if (danaRPump.getProtocol() >= 6) {
bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil, DateUtil.now()));
} else {
waitForWholeMinute(); // Dana can set only whole minute
// add 10sec to be sure we are over minute (will be cutted off anyway)
bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil, DateUtil.now() + T.secs(10).msecs()));
}
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil));
timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L;
aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds");
}
}
loadEvents();
rxBus.send(new EventDanaRNewStatus());
rxBus.send(new EventInitializationChanged());
//NSUpload.uploadDeviceStatus();
if (danaRPump.getDailyTotalUnits() > danaRPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) {
aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits());
if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) {
Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT);
rxBus.send(new EventNewNotification(reportFail));
NSUpload.uploadError(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits() + "U");
lastApproachingDailyLimit = System.currentTimeMillis();
}
}
} catch (Exception e) {
aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e);
}
aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded");
}
public PumpEnactResult loadEvents() {
if (!danaRSPlugin.isInitialized()) {
PumpEnactResult result = new PumpEnactResult(injector).success(false);
result.comment = "pump not initialized";
return result;
}
SystemClock.sleep(1000);
DanaRS_Packet_APS_History_Events msg;
if (lastHistoryFetched == 0) {
msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, 0);
aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history");
} else {
msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, lastHistoryFetched);
aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(lastHistoryFetched));
}
bleComm.sendMessage(msg);
while (!danaRSPlugin.apsHistoryDone && bleComm.isConnected()) {
SystemClock.sleep(100);
}
if (danaRSPlugin.lastEventTimeLoaded != 0)
lastHistoryFetched = danaRSPlugin.lastEventTimeLoaded - T.mins(1).msecs();
else
lastHistoryFetched = 0;
aapsLogger.debug(LTag.PUMPCOMM, "Events loaded");
danaRPump.setLastConnection(System.currentTimeMillis());
return new PumpEnactResult(injector).success(true);
}
public PumpEnactResult setUserSettings() {
bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump));
return new PumpEnactResult(injector).success(true);
}
public boolean bolus(final double insulin, int carbs, long carbtime, Treatment t) {
if (!isConnected()) return false;
if (BolusProgressDialog.stopPressed) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus)));
bolusingTreatment = t;
final int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0);
danaRSPlugin.bolusingTreatment = t;
danaRSPlugin.bolusAmountToBeDelivered = insulin;
danaRSPlugin.bolusStopped = false;
danaRSPlugin.bolusStopForced = false;
danaRSPlugin.bolusProgressLastTimeStamp = DateUtil.now();
DanaRS_Packet_Bolus_Set_Step_Bolus_Start start = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(aapsLogger, danaRSPlugin, constraintChecker, insulin, preferencesSpeed);
if (carbs > 0) {
// MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbtime, carbs); ####
// bleComm.sendMessage(msg);
DanaRS_Packet_APS_Set_Event_History msgSetHistoryEntry_v2 = new DanaRS_Packet_APS_Set_Event_History(aapsLogger, dateUtil, DanaRPump.CARBS, carbtime, carbs, 0);
bleComm.sendMessage(msgSetHistoryEntry_v2);
lastHistoryFetched = Math.min(lastHistoryFetched, carbtime - T.mins(1).msecs());
}
final long bolusStart = System.currentTimeMillis();
if (insulin > 0) {
if (!danaRSPlugin.bolusStopped) {
bleComm.sendMessage(start);
} else {
t.insulin = 0d;
return false;
}
while (!danaRSPlugin.bolusStopped && !start.failed && !danaRSPlugin.bolusDone) {
SystemClock.sleep(100);
if ((System.currentTimeMillis() - danaRSPlugin.bolusProgressLastTimeStamp) > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm
danaRSPlugin.bolusStopped = true;
danaRSPlugin.bolusStopForced = true;
aapsLogger.debug(LTag.PUMPCOMM, "Communication stopped");
}
}
}
final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
bolusingEvent.setT(t);
bolusingEvent.setPercent(99);
bolusingTreatment = null;
int speed = 12;
switch (preferencesSpeed) {
case 0:
speed = 12;
break;
case 1:
speed = 30;
break;
case 2:
speed = 60;
break;
}
long bolusDurationInMSec = (long) (insulin * speed * 1000);
long expectedEnd = bolusStart + bolusDurationInMSec + 2000;
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
bolusingEvent.setStatus(String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000));
rxBus.send(bolusingEvent);
SystemClock.sleep(1000);
}
// do not call loadEvents() directly, reconnection may be needed
commandQueue.loadEvents(new Callback() {
@Override
public void run() {
// reread bolus status
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)); // last bolus
bolusingEvent.setPercent(100);
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting)));
}
});
return !start.failed;
}
public void bolusStop() {
aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin));
DanaRS_Packet_Bolus_Set_Step_Bolus_Stop stop = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin);
danaRSPlugin.bolusStopForced = true;
if (isConnected()) {
bleComm.sendMessage(stop);
while (!danaRSPlugin.bolusStopped) {
bleComm.sendMessage(stop);
SystemClock.sleep(200);
}
} else {
danaRSPlugin.bolusStopped = true;
}
}
public boolean tempBasal(Integer percent, int durationInHours) {
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress()) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger));
SystemClock.sleep(500);
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Temporary_Basal(aapsLogger, percent, durationInHours));
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil));
loadEvents();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean highTempBasal(Integer percent) {
if (danaRPump.isTempBasalInProgress()) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger));
SystemClock.sleep(500);
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, percent));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil));
loadEvents();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean tempBasalShortDuration(Integer percent, int durationInMinutes) {
if (durationInMinutes != 15 && durationInMinutes != 30) {
aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param");
return false;
}
if (danaRPump.isTempBasalInProgress()) {
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger));
SystemClock.sleep(500);
}
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, percent));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil));
loadEvents();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean tempBasalStop() {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil));
loadEvents();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolus(Double insulin, int durationInHalfHours) {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus(aapsLogger, insulin, durationInHalfHours));
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump));
loadEvents();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolusStop() {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(aapsLogger));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump));
loadEvents();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean updateBasalsInPump(Profile profile) {
if (!isConnected()) return false;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates)));
Double[] basal = danaRPump.buildDanaRProfileRecord(profile);
DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(aapsLogger, 0, basal);
bleComm.sendMessage(msgSet);
DanaRS_Packet_Basal_Set_Profile_Number msgActivate = new DanaRS_Packet_Basal_Set_Profile_Number(aapsLogger, 0);
bleComm.sendMessage(msgActivate);
danaRPump.setLastSettingsRead(0); // force read full settings
getPumpStatus();
rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public PumpEnactResult loadHistory(byte type) {
PumpEnactResult result = new PumpEnactResult(injector);
if (!isConnected()) return result;
DanaRS_Packet_History_ msg = null;
switch (type) {
case RecordTypes.RECORD_TYPE_ALARM:
msg = new DanaRS_Packet_History_Alarm(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_PRIME:
msg = new DanaRS_Packet_History_Prime(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_BASALHOUR:
msg = new DanaRS_Packet_History_Basal(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_BOLUS:
msg = new DanaRS_Packet_History_Bolus(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_CARBO:
msg = new DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_DAILY:
msg = new DanaRS_Packet_History_Daily(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_GLUCOSE:
msg = new DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_REFILL:
msg = new DanaRS_Packet_History_Refill(aapsLogger, rxBus, dateUtil);
break;
case RecordTypes.RECORD_TYPE_SUSPEND:
msg = new DanaRS_Packet_History_Suspend(aapsLogger, rxBus, dateUtil);
break;
}
if (msg != null) {
bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger, 1));
SystemClock.sleep(200);
bleComm.sendMessage(msg);
while (!msg.getDone() && isConnected()) {
SystemClock.sleep(100);
}
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger, 0));
}
result.success = true;
result.comment = "OK";
return result;
}
public class LocalBinder extends Binder {
public DanaRSService getServiceInstance() {
return DanaRSService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
void waitForWholeMinute() {
while (true) {
long time = DateUtil.now();
long timeToWholeMinute = (60000 - time % 60000);
if (timeToWholeMinute > 59800 || timeToWholeMinute < 300)
break;
rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000))));
SystemClock.sleep(Math.min(timeToWholeMinute, 100));
}
}
}

View file

@ -1,109 +0,0 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.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.common.bolusInfo.DetailedBolusInfoStorage
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.plugins.pump.danaRv2.DanaRv2Plugin
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
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 MessageHashTableRv2 @Inject constructor(
aapsLogger: AAPSLogger,
rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
constraintChecker: ConstraintChecker,
danaRPump: DanaRPump,
danaRPlugin: DanaRPlugin,
danaRKoreanPlugin: DanaRKoreanPlugin,
danaRv2Plugin: DanaRv2Plugin,
configBuilderPlugin: ConfigBuilderPlugin,
commandQueue: CommandQueueProvider,
activePlugin: ActivePluginProvider,
detailedBolusInfoStorage: DetailedBolusInfoStorage,
treatmentsPlugin: TreatmentsPlugin,
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_v2(aapsLogger, danaRPump, dateUtil)) // 0x0205 CMD_PUMP_EXERCISE_MODE
put(MsgStatusBolusExtended_v2(aapsLogger, danaRPump)) // 0x0207 CMD_PUMP_EXPANS_INS_I
put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I
put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS
put(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) // 0x0301 CMD_PUMPINIT_TIME_INFO
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
put(MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin)) // 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(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
put(MsgCheckValue_v2(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue)) // 0xF0F1 CMD_PUMP_CHECK_VALUE
put(MsgStatusAPS_v2(aapsLogger, danaRPump)) // 0xE001 CMD_PUMPSTATUS_APS
put(MsgSetAPSTempBasalStart_v2(aapsLogger, 0, false, false)) // 0xE002 CMD_PUMPSET_APSTEMP
put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, dateUtil)) // 0xE003 CMD_GET_HISTORY
put(MsgSetHistoryEntry_v2(aapsLogger, 0, 0, 0, 0)) // 0xE004 CMD_SET_HISTORY_ENTRY
}
override fun put(message: MessageBase) {
messages[message.command] = message
}
override fun findMessage(command: Int): MessageBase {
return messages[command] ?: MessageBase()
}
}

View file

@ -269,7 +269,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
private void getBatteryStatusItem(List<View> statusItems) {
if (localInsightPlugin.getBatteryStatus() == null) return;
statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_battery_label),
statusItems.add(getStatusItem(resourceHelper.gs(R.string.battery_label),
localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%"));
}
@ -280,7 +280,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
if (cartridgeStatus.isInserted())
status = DecimalFormatter.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U";
else status = resourceHelper.gs(R.string.not_inserted);
statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_reservoir_label), status));
statusItems.add(getStatusItem(resourceHelper.gs(R.string.reservoir_label), status));
}
private void getTDDItems(List<View> statusItems) {
@ -294,14 +294,14 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
private void getBaseBasalRateItem(List<View> statusItems) {
if (localInsightPlugin.getActiveBasalRate() == null) return;
ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate();
statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_basebasalrate_label),
statusItems.add(getStatusItem(resourceHelper.gs(R.string.basebasalrate_label),
DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")"));
}
private void getTBRItem(List<View> statusItems) {
if (localInsightPlugin.getActiveTBR() == null) return;
ActiveTBR activeTBR = localInsightPlugin.getActiveTBR();
statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_tempbasal_label),
statusItems.add(getStatusItem(resourceHelper.gs(R.string.tempbasal_label),
resourceHelper.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration())));
}

View file

@ -27,7 +27,6 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@ -39,6 +38,7 @@ import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.CommandQueueProvider;
@ -46,6 +46,7 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
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.interfaces.PumpPluginBase;
@ -53,7 +54,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.common.ManufacturerType;
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.nsclient.NSUpload;
@ -132,7 +132,6 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro
import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException;
import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator;
import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.TimeChangeType;
@ -149,7 +148,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
private final SP sp;
private final CommandQueueProvider commandQueue;
private final ProfileFunction profileFunction;
private final NSUpload nsUpload;
private final Context context;
private final UploadQueue uploadQueue;
private final DateUtil dateUtil;
public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert";
@ -209,7 +210,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
SP sp,
CommandQueueProvider commandQueue,
ProfileFunction profileFunction,
NSUpload nsUpload,
Context context,
UploadQueue uploadQueue,
Config config,
DateUtil dateUtil
) {
@ -230,7 +233,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
this.sp = sp;
this.commandQueue = commandQueue;
this.profileFunction = profileFunction;
this.nsUpload = nsUpload;
this.context = context;
this.uploadQueue = uploadQueue;
this.dateUtil = dateUtil;
pumpDescription = new PumpDescription();
@ -929,8 +934,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
if (extendedBolus.durationInMinutes <= 0) {
final String _id = extendedBolus._id;
if (NSUpload.isIdValid(_id))
NSUpload.removeCareportalEntryFromNS(_id);
else UploadQueue.removeID("dbAdd", _id);
nsUpload.removeCareportalEntryFromNS(_id);
else uploadQueue.removeID("dbAdd", _id);
MainApp.getDbHelper().delete(extendedBolus);
} else
treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus);
@ -978,7 +983,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
}
@NonNull @Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
public JSONObject getJSONStatus(Profile profile, String profileName, String version) {
long now = System.currentTimeMillis();
if (connectionService == null) return null;
if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) {
@ -991,7 +996,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
final JSONObject extended = new JSONObject();
try {
status.put("timestamp", DateUtil.toISOString(connectionService.getLastConnected()));
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extended.put("Version", version);
try {
extended.put("ActiveProfile", profileFunction.getProfileName());
} catch (Exception e) {
@ -1451,8 +1456,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
ExtendedBolus extendedBolus = MainApp.getDbHelper().getExtendedBolusByPumpId(bolusID.id);
if (extendedBolus != null) {
final String _id = extendedBolus._id;
if (NSUpload.isIdValid(_id)) NSUpload.removeCareportalEntryFromNS(_id);
else UploadQueue.removeID("dbAdd", _id);
if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id);
else uploadQueue.removeID("dbAdd", _id);
MainApp.getDbHelper().delete(extendedBolus);
}
} else {
@ -1583,7 +1588,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
careportalEvent.eventType = CareportalEvent.NOTE;
careportalEvent.json = data.toString();
MainApp.getDbHelper().createOrUpdate(careportalEvent);
NSUpload.uploadCareportalEntryToNS(data);
nsUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}
@ -1617,7 +1622,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
careportalEvent.eventType = event;
careportalEvent.json = data.toString();
MainApp.getDbHelper().createOrUpdate(careportalEvent);
NSUpload.uploadCareportalEntryToNS(data);
nsUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}

View file

@ -227,14 +227,14 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface {
}
@NonNull @Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
public JSONObject getJSONStatus(Profile profile, String profileName, String version) {
long now = System.currentTimeMillis();
JSONObject pump = new JSONObject();
JSONObject status = new JSONObject();
JSONObject extended = new JSONObject();
try {
status.put("status", "normal");
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
extended.put("Version", version);
try {
extended.put("ActiveProfile", profileName);
} catch (Exception e) {

View file

@ -201,7 +201,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
if (pref.getKey().equals(getResourceHelper().gs(R.string.key_rileylink_mac_address))) {
String value = sp.getStringOrNull(R.string.key_rileylink_mac_address, null);
pref.setSummary(value == null ? getResourceHelper().gs(R.string.rileylink_error_address_not_set_short) : value);
pref.setSummary(value == null ? getResourceHelper().gs(R.string.not_set_short) : value);
}
}

View file

@ -78,6 +78,7 @@ public class MedtronicHistoryData {
private final AAPSLogger aapsLogger;
private final SP sp;
private final ActivePluginProvider activePlugin;
private final NSUpload nsUpload;
private final MedtronicUtil medtronicUtil;
private final MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder;
@ -106,6 +107,7 @@ public class MedtronicHistoryData {
AAPSLogger aapsLogger,
SP sp,
ActivePluginProvider activePlugin,
NSUpload nsUpload,
MedtronicUtil medtronicUtil,
MedtronicPumpHistoryDecoder medtronicPumpHistoryDecoder
) {
@ -115,6 +117,7 @@ public class MedtronicHistoryData {
this.aapsLogger = aapsLogger;
this.sp = sp;
this.activePlugin = activePlugin;
this.nsUpload = nsUpload;
this.medtronicUtil = medtronicUtil;
this.medtronicPumpHistoryDecoder = medtronicPumpHistoryDecoder;
}
@ -543,7 +546,7 @@ public class MedtronicHistoryData {
careportalEvent.eventType = event;
careportalEvent.json = data.toString();
MainApp.getDbHelper().createOrUpdate(careportalEvent);
NSUpload.uploadCareportalEntryToNS(data);
nsUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
aapsLogger.error("Unhandled exception", e);
}

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