Merge pull request #1700 from schmitzn/automation

Automation
This commit is contained in:
Milos Kozak 2019-03-30 15:45:28 +01:00 committed by GitHub
commit 5e49fe1889
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1300 changed files with 43889 additions and 24479 deletions

View file

@ -1,6 +1,6 @@
Reporting bugs Reporting bugs
-------------- --------------
- Note the precise time the problem occurred and describe the circumstances and steps that caused - **Note the precise time the problem occurred** and describe the circumstances and steps that caused
the problem the problem
- Note the Build version (found in the About dialog in the app, when pressing the three dots in the - Note the Build version (found in the About dialog in the app, when pressing the three dots in the
upper-right corner). upper-right corner).

View file

@ -1,6 +1,6 @@
# AndroidAPS # AndroidAPS
* Check the wiki: https://github.com/MilosKozak/AndroidAPS/wiki * Check the wiki: http://wiki.androidaps.org
* Everyone whos been looping with AndroidAPS needs to fill out the form after 3 days of looping https://docs.google.com/forms/d/14KcMjlINPMJHVt28MDRupa4sz4DDIooI4SrW0P3HSN8/viewform?c=0&w=1 * Everyone whos been looping with AndroidAPS needs to fill out the form after 3 days of looping https://docs.google.com/forms/d/14KcMjlINPMJHVt28MDRupa4sz4DDIooI4SrW0P3HSN8/viewform?c=0&w=1
[![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

View file

@ -63,11 +63,12 @@ android {
targetSdkVersion 25 targetSdkVersion 25
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "2.0g-dev" version "2.1.3-dev"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"' buildConfigField "String", "HEAD", '"' + generateGitBuild() + '"'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
// if you change minSdkVersion to less than 11, you need to change executeTask for wear
ndk { ndk {
moduleName "BleCommandUtil" moduleName "BleCommandUtil"
@ -77,7 +78,7 @@ android {
// TODO remove once wear dependency com.google.android.gms:play-services-wearable:7.3.0 // TODO remove once wear dependency com.google.android.gms:play-services-wearable:7.3.0
// has been upgraded (requiring significant code changes), which currently fails release // has been upgraded (requiring significant code changes), which currently fails release
// build with a deprecation warning // build with a deprecation warning
abortOnError false // abortOnError false
// (disabled entirely to avoid reports on the error, which would still be displayed // (disabled entirely to avoid reports on the error, which would still be displayed
// and it's easy to overlook that it's ignored) // and it's easy to overlook that it's ignored)
checkReleaseBuilds false checkReleaseBuilds false
@ -106,12 +107,12 @@ android {
] ]
} }
pumpcontrol { pumpcontrol {
applicationId "info.nightscout.androidaps" applicationId "info.nightscout.aapspumpcontrol"
dimension "standard" dimension "standard"
resValue "string", "app_name", "AndroidAPS" resValue "string", "app_name", "Pumpcontrol"
versionName version versionName version + "-pumpcontrol"
manifestPlaceholders = [ manifestPlaceholders = [
appIcon: "@mipmap/blueowl", appIcon: "@mipmap/ic_pumpcontrol",
appIconRound: "@null" appIconRound: "@null"
] ]
} }
@ -121,7 +122,7 @@ android {
resValue "string", "app_name", "NSClient" resValue "string", "app_name", "NSClient"
versionName version + "-nsclient" versionName version + "-nsclient"
manifestPlaceholders = [ manifestPlaceholders = [
appIcon: "@mipmap/yellowowl", appIcon: "@mipmap/ic_yellowowl",
appIconRound: "@null" appIconRound: "@null"
] ]
} }
@ -131,7 +132,7 @@ android {
resValue "string", "app_name", "NSClient2" resValue "string", "app_name", "NSClient2"
versionName version + "-nsclient" versionName version + "-nsclient"
manifestPlaceholders = [ manifestPlaceholders = [
appIcon: "@mipmap/yellowowl", appIcon: "@mipmap/ic_yellowowl",
appIconRound: "@null" appIconRound: "@null"
] ]
} }
@ -155,6 +156,7 @@ allprojects {
flatDir { flatDir {
dirs 'libs' dirs 'libs'
} }
maven { url 'https://jitpack.io' }
} }
} }
@ -166,10 +168,10 @@ dependencies {
wearApp project(':wear') wearApp project(':wear')
implementation fileTree(include: ['*.jar'], dir: 'libs') implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation("com.crashlytics.sdk.android:crashlytics:2.6.7@aar") { implementation("com.crashlytics.sdk.android:crashlytics:2.9.9@aar") {
transitive = true; transitive = true;
} }
implementation("com.crashlytics.sdk.android:answers:1.3.12@aar") { implementation("com.crashlytics.sdk.android:answers:1.4.7@aar") {
transitive = true; transitive = true;
} }
libs "MilosKozak:danars-support-lib:master@zip" libs "MilosKozak:danars-support-lib:master@zip"
@ -194,9 +196,10 @@ dependencies {
implementation "org.slf4j:slf4j-api:1.7.12" implementation "org.slf4j:slf4j-api:1.7.12"
implementation "com.jjoe64:graphview:4.0.1" implementation "com.jjoe64:graphview:4.0.1"
implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.1.1" implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.1.1"
implementation "com.google.android.gms:play-services-wearable:7.5.0" implementation 'com.google.android.gms:play-services-wearable:10.2.1'
implementation(name: "android-edittext-validator-v1.3.4-mod", ext: "aar") implementation(name: "android-edittext-validator-v1.3.4-mod", ext: "aar")
implementation(name: "sightparser-release", ext: "aar") implementation(name: "sightparser-release", ext: "aar")
implementation 'com.madgag.spongycastle:core:1.58.0.0'
implementation("com.google.android:flexbox:0.3.0") { implementation("com.google.android:flexbox:0.3.0") {
exclude group: "com.android.support" exclude group: "com.android.support"
@ -216,6 +219,8 @@ dependencies {
implementation "com.jakewharton:butterknife:${butterknifeVersion}" implementation "com.jakewharton:butterknife:${butterknifeVersion}"
annotationProcessor "com.jakewharton:butterknife-compiler:${butterknifeVersion}" annotationProcessor "com.jakewharton:butterknife-compiler:${butterknifeVersion}"
implementation 'com.github.DavidProdinger:weekdays-selector:1.0.4'
testImplementation "junit:junit:4.12" testImplementation "junit:junit:4.12"
testImplementation "org.json:json:20140107" testImplementation "org.json:json:20140107"
testImplementation "org.mockito:mockito-core:2.7.22" testImplementation "org.mockito:mockito-core:2.7.22"

View file

@ -12,6 +12,7 @@
<uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_MMS" /> <uses-permission android:name="android.permission.RECEIVE_MMS" />
<uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SEND_MMS" /> <uses-permission android:name="android.permission.SEND_MMS" />
<uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
@ -31,10 +32,13 @@
android:name=".MainApp" android:name=".MainApp"
android:allowBackup="true" android:allowBackup="true"
android:icon="${appIcon}" android:icon="${appIcon}"
android:roundIcon="${appIconRound}"
android:label="@string/app_name" android:label="@string/app_name"
android:roundIcon="${appIconRound}"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar"> android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="com.google.android.gms.car.application"
android:resource="@xml/automotive_app_desc" />
<activity android:name=".MainActivity"> <activity android:name=".MainActivity">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
@ -43,30 +47,30 @@
</activity> </activity>
<activity android:name=".activities.PreferencesActivity" /> <activity android:name=".activities.PreferencesActivity" />
<activity <activity
android:name=".plugins.Overview.Dialogs.BolusProgressHelperActivity" android:name=".plugins.general.overview.Dialogs.BolusProgressHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity <activity
android:name=".plugins.Overview.Dialogs.ErrorHelperActivity" android:name=".plugins.general.overview.Dialogs.ErrorHelperActivity"
android:theme="@style/Theme.AppCompat.Translucent" /> android:theme="@style/Theme.AppCompat.Translucent" />
<activity android:name=".activities.AgreementActivity" /> <activity android:name=".activities.AgreementActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRHistoryActivity" /> <activity android:name=".plugins.pump.danaR.activities.DanaRHistoryActivity" />
<activity android:name=".plugins.PumpDanaR.activities.DanaRUserOptionsActivity" /> <activity android:name=".plugins.pump.danaR.activities.DanaRUserOptionsActivity" />
<activity android:name=".activities.TDDStatsActivity" /> <activity android:name=".activities.TDDStatsActivity" />
<activity android:name=".plugins.Overview.activities.QuickWizardListActivity"> <activity android:name=".plugins.general.overview.activities.QuickWizardListActivity">
<intent-filter> <intent-filter>
<action android:name="info.nightscout.androidaps.plugins.Overview.activities.QuickWizardListActivity" /> <action android:name="info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".plugins.PumpDanaRS.activities.BLEScanActivity"> <activity android:name=".plugins.pump.danaRS.activities.BLEScanActivity">
<intent-filter> <intent-filter>
<action android:name="info.nightscout.androidaps.plugins.PumpDanaRS.activities.BLEScanActivity" /> <action android:name="info.nightscout.androidaps.plugins.PumpDanaRS.activities.BLEScanActivity" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
</intent-filter> </intent-filter>
</activity> </activity>
<activity android:name=".plugins.PumpDanaRS.activities.PairingHelperActivity" /> <activity android:name=".plugins.pump.danaRS.activities.PairingHelperActivity" />
<activity android:name=".activities.HistoryBrowseActivity" /> <activity android:name=".activities.HistoryBrowseActivity" />
<receiver <receiver
@ -85,8 +89,12 @@
<action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" /> <action android:name="it.ct.glicemia.ACTION_GLUCOSE_MEASURED" />
<!-- Receiver from DexcomG5 --> <!-- Receiver from DexcomG5 -->
<action android:name="com.dexcom.cgm.DATA" /> <action android:name="com.dexcom.cgm.DATA" />
<action android:name="com.dexcom.cgm.AndroidAPSEVGCallback.BROADCAST" />
<action android:name="com.dexcom.cgm.g5.AndroidAPSEVGCallback.BROADCAST" />
<!-- Receiver from Poctech --> <!-- Receiver from Poctech -->
<action android:name="com.china.poctech.data" /> <action android:name="com.china.poctech.data" />
<!-- Receiver from Tomato -->
<action android:name="com.fanqies.tomatofn.BgEstimate" />
</intent-filter> </intent-filter>
</receiver> </receiver>
<!-- Receiver keepalive, scheduled every 30 min --> <!-- Receiver keepalive, scheduled every 30 min -->
@ -94,7 +102,7 @@
<!-- Auto start --> <!-- Auto start -->
<receiver <receiver
android:name=".plugins.NSClientInternal.receivers.AutoStartReceiver" android:name=".plugins.general.nsclient.receivers.AutoStartReceiver"
android:enabled="true" android:enabled="true"
android:exported="true"> android:exported="true">
<intent-filter> <intent-filter>
@ -104,7 +112,7 @@
<!-- NSClient --> <!-- NSClient -->
<receiver <receiver
android:name=".plugins.NSClientInternal.receivers.RestartReceiver" android:name=".plugins.general.nsclient.receivers.RestartReceiver"
android:enabled="true" android:enabled="true"
android:exported="true"> android:exported="true">
<intent-filter> <intent-filter>
@ -112,7 +120,7 @@
</intent-filter> </intent-filter>
</receiver> </receiver>
<receiver <receiver
android:name=".plugins.NSClientInternal.receivers.DBAccessReceiver" android:name=".plugins.general.nsclient.receivers.DBAccessReceiver"
android:enabled="true" android:enabled="true"
android:exported="true"> android:exported="true">
<intent-filter> <intent-filter>
@ -150,26 +158,82 @@
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<service <service
android:name=".plugins.PumpDanaRKorean.services.DanaRKoreanExecutionService" android:name=".plugins.pump.danaRKorean.services.DanaRKoreanExecutionService"
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<service <service
android:name=".plugins.PumpDanaRv2.services.DanaRv2ExecutionService" android:name=".plugins.pump.danaRv2.services.DanaRv2ExecutionService"
android:enabled="true" android:enabled="true"
android:exported="false" /> android:exported="false" />
<service <service
android:name=".plugins.PumpDanaRS.services.DanaRSService" android:name=".plugins.pump.danaRS.services.DanaRSService"
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
android:name=".plugins.Wear.wearintegration.WatchUpdaterService" android:name=".plugins.general.wear.wearintegration.WatchUpdaterService"
android:exported="true"> android:exported="true">
<intent-filter> <intent-filter>
<action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> <!-- <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> -->
<!-- listeners receive events that match the action and data filters -->
<action android:name="com.google.android.gms.wearable.CAPABILITY_CHANGED" />
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_data" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_data_resend" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_cancel_bolus" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_confirmactionstring" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_initiateactionstring" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/openwearsettings" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/sendstatustowear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/sendpreferencestowear" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_basal" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_bolusprogress" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_actionconfirmationrequest" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_changeconfirmationrequest" />
<data
android:scheme="wear"
android:host="*"
android:pathPrefix="/nightscout_watch_cancelnotificationrequest" />
</intent-filter> </intent-filter>
</service> </service>
<service <service
android:name=".plugins.NSClientInternal.services.NSClientService" android:name=".plugins.general.nsclient.services.NSClientService"
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
@ -177,10 +241,12 @@
android:enabled="true" android:enabled="true"
android:exported="true" /> android:exported="true" />
<service <service
android:name=".plugins.Overview.notifications.DismissNotificationService" android:name=".plugins.general.overview.notifications.DismissNotificationService"
android:exported="false" /> android:exported="false" />
<service android:name=".plugins.Persistentnotification.DummyService" /> <service android:name=".plugins.general.persistentNotification.DummyService" />
<service android:name=".plugins.pump.insight.connection_service.InsightConnectionService" />
<service android:name=".plugins.pump.insight.InsightAlertService" />
<meta-data <meta-data
android:name="io.fabric.ApiKey" android:name="io.fabric.ApiKey"
@ -189,12 +255,25 @@
<activity <activity
android:name=".setupwizard.SetupWizardActivity" android:name=".setupwizard.SetupWizardActivity"
android:configChanges="orientation|keyboardHidden|screenSize" android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="@style/AppTheme.NoActionBar" android:label="@string/title_activity_setup_wizard"
android:label="@string/title_activity_setup_wizard" /> android:theme="@style/AppTheme.NoActionBar" />
<activity android:name=".activities.SingleFragmentActivity" <activity
android:name=".activities.SingleFragmentActivity"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity android:name=".plugins.Maintenance.activities.LogSettingActivity"></activity> <activity android:name=".plugins.general.maintenance.activities.LogSettingActivity"></activity>
<activity
android:name=".plugins.pump.insight.activities.InsightPairingActivity"
android:theme="@style/AppTheme"
android:label="@string/insight_pairing" />
<activity
android:name=".plugins.pump.insight.activities.InsightAlertActivity"
android:label="@string/pump_alert"
android:theme="@style/InsightAlertDialog" />
<activity
android:name=".plugins.pump.insight.activities.InsightPairingInformationActivity"
android:theme="@style/AppTheme"
android:label="@string/pairing_information" />
</application> </application>
</manifest> </manifest>

View file

@ -9,33 +9,32 @@ var tempBasalFunctions = {};
tempBasalFunctions.getMaxSafeBasal = function getMaxSafeBasal(profile) { tempBasalFunctions.getMaxSafeBasal = function getMaxSafeBasal(profile) {
var max_daily_safety_multiplier = (isNaN(profile.max_daily_safety_multiplier) || profile.max_daily_safety_multiplier == null) ? 3 : profile.max_daily_safety_multiplier; var max_daily_safety_multiplier = (isNaN(profile.max_daily_safety_multiplier) || profile.max_daily_safety_multiplier == null) ? 3 : profile.max_daily_safety_multiplier;
var current_basal_safety_multiplier = (isNaN(profile.current_basal_safety_multiplier) || profile.current_basal_safety_multiplier == null) ? 4 : profile.current_basal_safety_multiplier; var current_basal_safety_multiplier = (isNaN(profile.current_basal_safety_multiplier) || profile.current_basal_safety_multiplier == null) ? 4 : profile.current_basal_safety_multiplier;
return Math.min(profile.max_basal, max_daily_safety_multiplier * profile.max_daily_basal, current_basal_safety_multiplier * profile.current_basal); return Math.min(profile.max_basal, max_daily_safety_multiplier * profile.max_daily_basal, current_basal_safety_multiplier * profile.current_basal);
}; };
tempBasalFunctions.setTempBasal = function setTempBasal(rate, duration, profile, rT, currenttemp) { tempBasalFunctions.setTempBasal = function setTempBasal(rate, duration, profile, rT, currenttemp) {
//var maxSafeBasal = Math.min(profile.max_basal, 3 * profile.max_daily_basal, 4 * profile.current_basal); //var maxSafeBasal = Math.min(profile.max_basal, 3 * profile.max_daily_basal, 4 * profile.current_basal);
var maxSafeBasal = tempBasalFunctions.getMaxSafeBasal(profile); var maxSafeBasal = tempBasalFunctions.getMaxSafeBasal(profile);
var round_basal = require('./round-basal'); var round_basal = require('./round-basal');
if (rate < 0) { if (rate < 0) {
rate = 0; rate = 0;
} // if >30m @ 0 required, zero temp will be extended to 30m instead } else if (rate > maxSafeBasal) {
else if (rate > maxSafeBasal) {
rate = maxSafeBasal; rate = maxSafeBasal;
} }
var suggestedRate = round_basal(rate, profile); var suggestedRate = round_basal(rate, profile);
if (typeof(currenttemp) !== 'undefined' && typeof(currenttemp.duration) !== 'undefined' && typeof(currenttemp.rate) !== 'undefined' && currenttemp.duration > (duration-10) && currenttemp.duration <= 120 && suggestedRate <= currenttemp.rate * 1.2 && suggestedRate >= currenttemp.rate * 0.8) { if (typeof(currenttemp) !== 'undefined' && typeof(currenttemp.duration) !== 'undefined' && typeof(currenttemp.rate) !== 'undefined' && currenttemp.duration > (duration-10) && currenttemp.duration <= 120 && suggestedRate <= currenttemp.rate * 1.2 && suggestedRate >= currenttemp.rate * 0.8 && duration > 0 ) {
rT.reason += " "+currenttemp.duration+"m left and " + currenttemp.rate + " ~ req " + suggestedRate + "U/hr: no temp required"; rT.reason += " "+currenttemp.duration+"m left and " + currenttemp.rate + " ~ req " + suggestedRate + "U/hr: no temp required";
return rT; return rT;
} }
if (suggestedRate === profile.current_basal) { if (suggestedRate === profile.current_basal) {
if (profile.skip_neutral_temps) { if (profile.skip_neutral_temps === true) {
if (typeof(currenttemp) !== 'undefined' && typeof(currenttemp.duration) !== 'undefined' && currenttemp.duration > 0) { if (typeof(currenttemp) !== 'undefined' && typeof(currenttemp.duration) !== 'undefined' && currenttemp.duration > 0) {
reason(rT, 'Suggested rate is same as profile rate, a temp basal is active, canceling current temp'); reason(rT, 'Suggested rate is same as profile rate, a temp basal is active, canceling current temp');
rT.duration = 0; rT.duration = 0;

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps; package info.nightscout.androidaps;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
/** /**
* Created by mike on 07.06.2016. * Created by mike on 07.06.2016.
@ -68,4 +68,7 @@ public class Constants {
//SMS Communicator //SMS Communicator
public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs(); public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs();
//Storage [MB]
public static final long MINIMUM_FREE_SPACE = 200;
} }

View file

@ -49,16 +49,16 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus; import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
import info.nightscout.androidaps.setupwizard.SetupWizardActivity; import info.nightscout.androidaps.setupwizard.SetupWizardActivity;
import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.androidaps.tabs.TabPageAdapter;
import info.nightscout.utils.AndroidPermission; import info.nightscout.androidaps.utils.AndroidPermission;
import info.nightscout.utils.LocaleHelper; import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.utils.OKDialog; import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.utils.PasswordProtection; import info.nightscout.androidaps.utils.PasswordProtection;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.utils.VersionChecker; import info.nightscout.androidaps.utils.VersionChecker;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(L.CORE); private static Logger log = LoggerFactory.getLogger(L.CORE);
@ -182,7 +182,7 @@ public class MainActivity extends AppCompatActivity {
@Subscribe @Subscribe
public void onStatusEvent(final EventRefreshGui ev) { public void onStatusEvent(final EventRefreshGui ev) {
String lang = SP.getString("language", "en"); String lang = SP.getString(R.string.key_language, "en");
LocaleHelper.setLocale(getApplicationContext(), lang); LocaleHelper.setLocale(getApplicationContext(), lang);
runOnUiThread(() -> { runOnUiThread(() -> {
if (ev.recreate) { if (ev.recreate) {
@ -326,6 +326,7 @@ public class MainActivity extends AppCompatActivity {
case AndroidPermission.CASE_LOCATION: case AndroidPermission.CASE_LOCATION:
case AndroidPermission.CASE_SMS: case AndroidPermission.CASE_SMS:
case AndroidPermission.CASE_BATTERY: case AndroidPermission.CASE_BATTERY:
case AndroidPermission.CASE_PHONESTATE:
break; break;
} }
} }
@ -377,10 +378,7 @@ public class MainActivity extends AppCompatActivity {
case R.id.nav_about: case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this); AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION); builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION);
if (Config.NSCLIENT) builder.setIcon(MainApp.getIcon());
builder.setIcon(R.mipmap.yellowowl);
else
builder.setIcon(R.mipmap.blueowl);
String message = "Build: " + BuildConfig.BUILDVERSION + "\n"; String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n"; message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName; message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName;

View file

@ -29,59 +29,64 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Actions.ActionsFragment; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Food.FoodPlugin; import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin; import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.general.actions.ActionsFragment;
import info.nightscout.androidaps.plugins.Maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.NSClientInternal.receivers.DBAccessReceiver;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Persistentnotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
import info.nightscout.androidaps.plugins.ProfileSimple.SimpleProfilePlugin;
import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.Source.SourcePoctechPlugin;
import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Wear.WearPlugin;
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin; import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.general.food.FoodPlugin;
import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils;
import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.receivers.AckAlarmReceiver;
import info.nightscout.androidaps.plugins.general.nsclient.receivers.DBAccessReceiver;
import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin;
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
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.insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
import info.nightscout.androidaps.plugins.profile.simple.SimpleProfilePlugin;
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.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomG6Plugin;
import info.nightscout.androidaps.plugins.source.SourceEversensePlugin;
import info.nightscout.androidaps.plugins.source.SourceGlimpPlugin;
import info.nightscout.androidaps.plugins.source.SourceMM640gPlugin;
import info.nightscout.androidaps.plugins.source.SourceNSClientPlugin;
import info.nightscout.androidaps.plugins.source.SourcePoctechPlugin;
import info.nightscout.androidaps.plugins.source.SourceTomatoPlugin;
import info.nightscout.androidaps.plugins.source.SourceXdripPlugin;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.receivers.DataReceiver; import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver; import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver; import info.nightscout.androidaps.receivers.NSAlarmReceiver;
import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.services.Intents;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.plugins.Maintenance.LoggerUtils;
import io.fabric.sdk.android.Fabric; import io.fabric.sdk.android.Fabric;
@ -158,9 +163,8 @@ public class MainApp extends Application {
if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin());
pluginsList.add(CareportalPlugin.getPlugin()); pluginsList.add(CareportalPlugin.getPlugin());
if (Config.PUMPDRIVERS && engineeringMode)
pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here
if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin());
if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin()); if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin()); pluginsList.add(VirtualPumpPlugin.getPlugin());
@ -173,13 +177,17 @@ public class MainApp extends Application {
if (Config.OTHERPROFILES) pluginsList.add(LocalProfilePlugin.getPlugin()); if (Config.OTHERPROFILES) pluginsList.add(LocalProfilePlugin.getPlugin());
pluginsList.add(TreatmentsPlugin.getPlugin()); pluginsList.add(TreatmentsPlugin.getPlugin());
if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin()); if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
if (Config.SAFETY) pluginsList.add(StorageConstraintPlugin.getPlugin());
if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin()); if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin());
pluginsList.add(SourceXdripPlugin.getPlugin()); pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin()); pluginsList.add(SourceNSClientPlugin.getPlugin());
pluginsList.add(SourceMM640gPlugin.getPlugin()); pluginsList.add(SourceMM640gPlugin.getPlugin());
pluginsList.add(SourceGlimpPlugin.getPlugin()); pluginsList.add(SourceGlimpPlugin.getPlugin());
pluginsList.add(SourceDexcomG5Plugin.getPlugin()); pluginsList.add(SourceDexcomG5Plugin.getPlugin());
pluginsList.add(SourceDexcomG6Plugin.getPlugin());
pluginsList.add(SourcePoctechPlugin.getPlugin()); pluginsList.add(SourcePoctechPlugin.getPlugin());
pluginsList.add(SourceTomatoPlugin.getPlugin());
pluginsList.add(SourceEversensePlugin.getPlugin());
if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(FoodPlugin.getPlugin());
@ -192,6 +200,9 @@ public class MainApp extends Application {
pluginsList.add(ConfigBuilderPlugin.getPlugin()); pluginsList.add(ConfigBuilderPlugin.getPlugin());
pluginsList.add(DstHelperPlugin.getPlugin());
ConfigBuilderPlugin.getPlugin().initialize(); ConfigBuilderPlugin.getPlugin().initialize();
} }
@ -387,6 +398,24 @@ public class MainApp extends Application {
return devBranch; return devBranch;
} }
public static int getIcon() {
if (Config.NSCLIENT)
return R.mipmap.ic_yellowowl;
else if (Config.PUMPCONTROL)
return R.mipmap.ic_pumpcontrol;
else
return R.mipmap.ic_launcher;
}
public static int getNotificationIcon() {
if (Config.NSCLIENT)
return R.drawable.ic_notif_nsclient;
else if (Config.PUMPCONTROL)
return R.drawable.ic_notif_pumpcontrol;
else
return R.drawable.ic_notif_aaps;
}
@Override @Override
public void onTerminate() { public void onTerminate() {
if (L.isEnabled(L.CORE)) if (L.isEnabled(L.CORE))
@ -397,4 +426,9 @@ public class MainApp extends Application {
sDatabaseHelper = null; sDatabaseHelper = null;
} }
} }
public static int dpToPx(int dp) {
float scale = sResources.getDisplayMetrics().density;
return (int) (dp*scale + 0.5f);
}
} }

View file

@ -2,16 +2,14 @@ package info.nightscout.androidaps.activities;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View; import android.view.View;
import android.widget.Button; import android.widget.Button;
import android.widget.CheckBox; import android.widget.CheckBox;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
public class AgreementActivity extends Activity { public class AgreementActivity extends Activity {
boolean IUnderstand; boolean IUnderstand;

View file

@ -34,16 +34,16 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished; import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphData.GraphData; import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
public class HistoryBrowseActivity extends AppCompatActivity { public class HistoryBrowseActivity extends AppCompatActivity {
private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class);

View file

@ -9,6 +9,7 @@ import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment; import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup; import android.preference.PreferenceGroup;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.text.TextUtils; import android.text.TextUtils;
import info.nightscout.androidaps.Config; import info.nightscout.androidaps.Config;
@ -18,33 +19,33 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshGui; import info.nightscout.androidaps.events.EventRefreshGui;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin; import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin; import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin; import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin; import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin; import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin; import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin; import info.nightscout.androidaps.plugins.source.SourceDexcomG5Plugin;
import info.nightscout.androidaps.plugins.Wear.WearPlugin; import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin; import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
import info.nightscout.utils.LocaleHelper;
import info.nightscout.utils.OKDialog;
import info.nightscout.utils.SP;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener { public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
MyPreferenceFragment myPreferenceFragment; MyPreferenceFragment myPreferenceFragment;
@ -164,7 +165,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(InsightPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP); addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP);
if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE) if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)
@ -192,6 +193,17 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL); addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL);
} }
if (Config.NSCLIENT) {
PreferenceScreen scrnAdvancedSettings = (PreferenceScreen)findPreference(getString(R.string.key_advancedsettings));
if (scrnAdvancedSettings != null) {
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_warning)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_critical)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_warning)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_critical)));
scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights)));
}
}
initSummary(getPreferenceScreen()); initSummary(getPreferenceScreen());
} }

View file

@ -10,9 +10,8 @@ import android.view.MenuItem;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.utils.PasswordProtection; import info.nightscout.androidaps.utils.PasswordProtection;
public class SingleFragmentActivity extends AppCompatActivity { public class SingleFragmentActivity extends AppCompatActivity {

View file

@ -39,18 +39,18 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin; import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin; import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin; import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin; import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.androidaps.utils.SafeParse;
public class TDDStatsActivity extends Activity { public class TDDStatsActivity extends Activity {
private static Logger log = LoggerFactory.getLogger(TDDStatsActivity.class); private static Logger log = LoggerFactory.getLogger(TDDStatsActivity.class);
@ -550,7 +550,7 @@ public class TDDStatsActivity extends Activity {
PumpInterface danaRS = MainApp.getSpecificPlugin(DanaRSPlugin.class); PumpInterface danaRS = MainApp.getSpecificPlugin(DanaRSPlugin.class);
PumpInterface danaV2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class); PumpInterface danaV2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
PumpInterface danaKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class); PumpInterface danaKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
PumpInterface insight = MainApp.getSpecificPlugin(InsightPlugin.class); PumpInterface insight = MainApp.getSpecificPlugin(LocalInsightPlugin.class);
boolean startsYesterday = activePump == dana || activePump == danaRS || activePump == danaV2 || activePump == danaKorean || activePump == insight; boolean startsYesterday = activePump == dana || activePump == danaRS || activePump == danaV2 || activePump == danaKorean || activePump == insight;

View file

@ -42,10 +42,18 @@ public class ConstraintChecker implements ConstraintsInterface {
return isSMBModeEnabled(new Constraint<>(true)); return isSMBModeEnabled(new Constraint<>(true));
} }
public Constraint<Boolean> isUAMEnabled() {
return isUAMEnabled(new Constraint<>(true));
}
public Constraint<Boolean> isAdvancedFilteringEnabled() { public Constraint<Boolean> isAdvancedFilteringEnabled() {
return isAdvancedFilteringEnabled(new Constraint<>(true)); return isAdvancedFilteringEnabled(new Constraint<>(true));
} }
public Constraint<Boolean> isSuperBolusEnabled() {
return isSuperBolusEnabled(new Constraint<>(true));
}
public Constraint<Double> getMaxBasalAllowed(Profile profile) { public Constraint<Double> getMaxBasalAllowed(Profile profile) {
return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile); return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile);
} }
@ -130,6 +138,18 @@ public class ConstraintChecker implements ConstraintsInterface {
return value; return value;
} }
@Override
public Constraint<Boolean> isUAMEnabled(Constraint<Boolean> value) {
ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
constraint.isUAMEnabled(value);
}
return value;
}
@Override @Override
public Constraint<Boolean> isAdvancedFilteringEnabled(Constraint<Boolean> value) { public Constraint<Boolean> isAdvancedFilteringEnabled(Constraint<Boolean> value) {
ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
@ -141,6 +161,17 @@ public class ConstraintChecker implements ConstraintsInterface {
return value; return value;
} }
@Override
public Constraint<Boolean> isSuperBolusEnabled(Constraint<Boolean> value) {
ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
constraint.isSuperBolusEnabled(value);
}
return value;
}
@Override @Override
public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, Profile profile) { public Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, Profile profile) {
ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class); ArrayList<PluginBase> constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);

View file

@ -2,15 +2,12 @@ package info.nightscout.androidaps.data;
import android.content.Context; import android.content.Context;
import com.rits.cloning.Cloner;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.Date; import java.util.Date;
import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
/** /**
* Created by mike on 29.05.2017. * Created by mike on 29.05.2017.

View file

@ -1,29 +1,20 @@
package info.nightscout.androidaps.data; package info.nightscout.androidaps.data;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.text.Html;
import android.text.Spanned;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.Round;
/** /**
* Created by mike on 04.01.2017. * Created by mike on 04.01.2017.
@ -60,23 +51,29 @@ public class GlucoseStatus {
} }
@Nullable @Nullable
public static GlucoseStatus getGlucoseStatusData(){ public static GlucoseStatus getGlucoseStatusData() {
return getGlucoseStatusData(false); return getGlucoseStatusData(false);
} }
@Nullable @Nullable
public static GlucoseStatus getGlucoseStatusData(boolean allowOldData) { public static GlucoseStatus getGlucoseStatusData(boolean allowOldData) {
// load 45min // load 45min
long fromtime = DateUtil.now() - 60 * 1000L * 45; //long fromtime = DateUtil.now() - 60 * 1000L * 45;
List<BgReading> data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false); //List<BgReading> data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false);
List<BgReading> data = IobCobCalculatorPlugin.getPlugin().getBgReadings();
if (data == null)
return null;
int sizeRecords = data.size(); int sizeRecords = data.size();
if (sizeRecords == 0) { if (sizeRecords == 0) {
return null; return null;
} }
sizeRecords = Math.min(sizeRecords, 9);
if (data.get(0).date < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) { if (data.get(0).date < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) {
return null; return null;
} }
@ -100,7 +97,7 @@ public class GlucoseStatus {
ArrayList<Double> short_deltas = new ArrayList<Double>(); ArrayList<Double> short_deltas = new ArrayList<Double>();
ArrayList<Double> long_deltas = new ArrayList<Double>(); ArrayList<Double> long_deltas = new ArrayList<Double>();
for (int i = 1; i < data.size(); i++) { for (int i = 1; i < sizeRecords; i++) {
if (data.get(i).value > 38) { if (data.get(i).value > 38) {
BgReading then = data.get(i); BgReading then = data.get(i);
long then_date = then.date; long then_date = then.date;

View file

@ -9,8 +9,8 @@ import org.slf4j.LoggerFactory;
import java.util.Date; import java.util.Date;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.Round;
public class IobTotal { public class IobTotal {
private static Logger log = LoggerFactory.getLogger(IobTotal.class); private static Logger log = LoggerFactory.getLogger(IobTotal.class);

View file

@ -9,7 +9,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.TimeZone; import java.util.TimeZone;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
@ -17,12 +16,13 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.MidnightTime;
public class Profile { public class Profile {
private static Logger log = LoggerFactory.getLogger(Profile.class); private static Logger log = LoggerFactory.getLogger(Profile.class);
@ -381,7 +381,7 @@ public class Profile {
} }
public double getIsf() { public double getIsf() {
return getIsfTimeFromMidnight(secondsFromMidnight(System.currentTimeMillis())); return getIsfTimeFromMidnight(secondsFromMidnight());
} }
public double getIsf(long time) { public double getIsf(long time) {
@ -397,11 +397,11 @@ public class Profile {
public String getIsfList() { public String getIsfList() {
if (isf_v == null) if (isf_v == null)
isf_v = convertToSparseArray(isf); isf_v = convertToSparseArray(isf);
return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + "/U"); return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + MainApp.gs(R.string.profile_per_unit));
} }
public double getIc() { public double getIc() {
return getIcTimeFromMidnight(secondsFromMidnight(System.currentTimeMillis())); return getIcTimeFromMidnight(secondsFromMidnight());
} }
public double getIc(long time) { public double getIc(long time) {
@ -417,11 +417,11 @@ public class Profile {
public String getIcList() { public String getIcList() {
if (ic_v == null) if (ic_v == null)
ic_v = convertToSparseArray(ic); ic_v = convertToSparseArray(ic);
return getValuesList(ic_v, null, new DecimalFormat("0.0"), "g/U"); return getValuesList(ic_v, null, new DecimalFormat("0.0"), MainApp.gs(R.string.profile_carbs_per_unit));
} }
public double getBasal() { public double getBasal() {
return getBasalTimeFromMidnight(secondsFromMidnight(System.currentTimeMillis())); return getBasalTimeFromMidnight(secondsFromMidnight());
} }
public double getBasal(long time) { public double getBasal(long time) {
@ -438,7 +438,7 @@ public class Profile {
public String getBasalList() { public String getBasalList() {
if (basal_v == null) if (basal_v == null)
basal_v = convertToSparseArray(basal); basal_v = convertToSparseArray(basal);
return getValuesList(basal_v, null, new DecimalFormat("0.00"), "U/h"); return getValuesList(basal_v, null, new DecimalFormat("0.00"), MainApp.gs(R.string.profile_ins_units_per_hout));
} }
public class BasalValue { public class BasalValue {
@ -465,7 +465,7 @@ public class Profile {
} }
public double getTarget() { public double getTarget() {
return getTarget(secondsFromMidnight(System.currentTimeMillis())); return getTarget(secondsFromMidnight());
} }
protected double getTarget(int timeAsSeconds) { protected double getTarget(int timeAsSeconds) {
@ -473,7 +473,7 @@ public class Profile {
} }
public double getTargetLow() { public double getTargetLow() {
return getTargetLowTimeFromMidnight(secondsFromMidnight(System.currentTimeMillis())); return getTargetLowTimeFromMidnight(secondsFromMidnight());
} }
public double getTargetLow(long time) { public double getTargetLow(long time) {
@ -487,7 +487,7 @@ public class Profile {
} }
public double getTargetHigh() { public double getTargetHigh() {
return getTargetHighTimeFromMidnight(secondsFromMidnight(System.currentTimeMillis())); return getTargetHighTimeFromMidnight(secondsFromMidnight());
} }
public double getTargetHigh(long time) { public double getTargetHigh(long time) {
@ -518,24 +518,13 @@ public class Profile {
} }
public static int secondsFromMidnight() { public static int secondsFromMidnight() {
Calendar c = Calendar.getInstance(); long passed = DateUtil.now() - MidnightTime.calc();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
return (int) (passed / 1000); return (int) (passed / 1000);
} }
public static int secondsFromMidnight(long date) { public static int secondsFromMidnight(long date) {
Calendar c = Calendar.getInstance(); long midnight = MidnightTime.calc(date);
c.setTimeInMillis(date); long passed = date - midnight;
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = date - c.getTimeInMillis();
return (int) (passed / 1000); return (int) (passed / 1000);
} }

View file

@ -10,7 +10,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.utils.DateUtil;
/** /**
* Created by mike on 09.05.2017. * Created by mike on 09.05.2017.

View file

@ -1,8 +1,5 @@
package info.nightscout.androidaps.data; package info.nightscout.androidaps.data;
import android.text.Html;
import android.text.Spanned;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -11,8 +8,8 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.Round;
public class PumpEnactResult { public class PumpEnactResult {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,16 +1,12 @@
package info.nightscout.androidaps.data; package info.nightscout.androidaps.data;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.utils.SP;
import info.nightscout.utils.SP;
/** /**
* Created by mike on 12.10.2016. * Created by mike on 12.10.2016.

View file

@ -11,13 +11,13 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.BolusWizard; import info.nightscout.androidaps.utils.BolusWizard;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
* Created by mike on 25.12.2017. * Created by mike on 25.12.2017.

View file

@ -1,7 +1,5 @@
package info.nightscout.androidaps.db; package info.nightscout.androidaps.db;
import android.content.res.Resources;
import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTable;
@ -14,15 +12,13 @@ import java.util.Objects;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv; import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv;
import info.nightscout.androidaps.plugins.Overview.OverviewPlugin; import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.SP;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)
public class BgReading implements DataPointWithLabelInterface { public class BgReading implements DataPointWithLabelInterface {
@ -220,14 +216,8 @@ public class BgReading implements DataPointWithLabelInterface {
@Override @Override
public int getColor() { public int getColor() {
String units = ProfileFunctions.getInstance().getProfileUnits(); String units = ProfileFunctions.getInstance().getProfileUnits();
Double lowLine = SP.getDouble("low_mark", 0d); Double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
Double highLine = SP.getDouble("high_mark", 0d); Double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
if (lowLine < 1) {
lowLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units);
}
if (highLine < 1) {
highLine = Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units);
}
int color = MainApp.gc(R.color.inrange); int color = MainApp.gc(R.color.inrange);
if (isPrediction()) if (isPrediction())
return getPredectionColor(); return getPredectionColor();

View file

@ -13,7 +13,6 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Date;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
@ -26,14 +25,14 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg; import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
import info.nightscout.androidaps.plugins.Overview.OverviewFragment; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.utils.Translator; import info.nightscout.androidaps.utils.Translator;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
public class CareportalEvent implements DataPointWithLabelInterface, Interval { public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@ -90,8 +89,8 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return System.currentTimeMillis() - date; return System.currentTimeMillis() - date;
} }
public long getHoursFromStart() { public double getHoursFromStart() {
return (System.currentTimeMillis() - date) / (60 * 60 * 1000); return (System.currentTimeMillis() - date) / (60 * 60 * 1000.0);
} }
public String age() { public String age() {

View file

@ -44,16 +44,19 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync; import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync;
import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID;
import info.nightscout.utils.JsonHelper; import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset;
import info.nightscout.utils.PercentageSplitter; import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID;
import info.nightscout.utils.ToastUtils; 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.ToastUtils;
/** /**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling * This Helper contains all resource to provide a central DB management functionality. Only methods handling
@ -76,8 +79,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents"; public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches"; public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs"; public static final String DATABASE_TDDS = "TDDs";
public static final String DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets";
public static final String DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs";
public static final String DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs";
private static final int DATABASE_VERSION = 9; private static final int DATABASE_VERSION = 10;
public static Long earliestDataChange = null; public static Long earliestDataChange = null;
@ -122,6 +128,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class); TableUtils.createTableIfNotExists(connectionSource, TDD.class);
TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
} catch (SQLException e) { } catch (SQLException e) {
log.error("Can't create database", e); log.error("Can't create database", e);
throw new RuntimeException(e); throw new RuntimeException(e);
@ -138,6 +147,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
log.debug("Upgrading database from v7 to v8"); log.debug("Upgrading database from v7 to v8");
} else if (oldVersion == 8 && newVersion == 9) { } else if (oldVersion == 8 && newVersion == 9) {
log.debug("Upgrading database from v8 to v9"); log.debug("Upgrading database from v8 to v9");
} else if (oldVersion == 9 && newVersion == 10) {
TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
} else { } else {
log.info(DatabaseHelper.class.getName(), "onUpgrade"); log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.dropTable(connectionSource, TempTarget.class, true);
@ -156,6 +169,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} }
} }
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
log.info("Do nothing for downgrading...");
log.debug("oldVersion: {}, newVersion: {}", oldVersion, newVersion);
}
public int getOldVersion() { public int getOldVersion() {
return oldVersion; return oldVersion;
} }
@ -321,6 +340,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(ProfileSwitch.class); return getDao(ProfileSwitch.class);
} }
private Dao<InsightPumpID, Long> getDaoInsightPumpID() throws SQLException {
return getDao(InsightPumpID.class);
}
private Dao<InsightBolusID, Long> getDaoInsightBolusID() throws SQLException {
return getDao(InsightBolusID.class);
}
private Dao<InsightHistoryOffset, String> getDaoInsightHistoryOffset() throws SQLException {
return getDao(InsightHistoryOffset.class);
}
public static long roundDateToSec(long date) { public static long roundDateToSec(long date) {
long rounded = date - date % 1000; long rounded = date - date % 1000;
if (rounded != date) if (rounded != date)
@ -390,24 +421,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
*/ */
@Nullable @Nullable
public static BgReading lastBg() { public static BgReading lastBg() {
List<BgReading> bgList = null; List<BgReading> bgList = IobCobCalculatorPlugin.getPlugin().getBgReadings();
try { if (bgList == null)
Dao<BgReading, Long> daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
QueryBuilder<BgReading, Long> queryBuilder = daoBgReadings.queryBuilder();
queryBuilder.orderBy("date", false);
queryBuilder.limit(1L);
queryBuilder.where().gt("value", 38).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgList = daoBgReadings.query(preparedQuery);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
if (bgList != null && bgList.size() > 0)
return bgList.get(0);
else
return null; return null;
for (int i = 0; i < bgList.size(); i++)
if (bgList.get(i).value > 39)
return bgList.get(i);
return null;
} }
/* /*
@ -435,14 +457,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder(); QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending); queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where(); Where where = queryBuilder.where();
where.ge("date", mills).and().gt("value", 38).and().eq("isValid", true); where.ge("date", mills).and().ge("value", 39).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare(); PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery); bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings; return bgReadings;
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
return new ArrayList<BgReading>(); return new ArrayList<>();
} }
public List<BgReading> getBgreadingsDataFromTime(long start, long end, boolean ascending) { public List<BgReading> getBgreadingsDataFromTime(long start, long end, boolean ascending) {
@ -452,14 +474,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder(); QueryBuilder<BgReading, Long> queryBuilder = daoBgreadings.queryBuilder();
queryBuilder.orderBy("date", ascending); queryBuilder.orderBy("date", ascending);
Where where = queryBuilder.where(); Where where = queryBuilder.where();
where.between("date", start, end).and().gt("value", 38).and().eq("isValid", true); where.between("date", start, end).and().ge("value", 39).and().eq("isValid", true);
PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare(); PreparedQuery<BgReading> preparedQuery = queryBuilder.prepare();
bgReadings = daoBgreadings.query(preparedQuery); bgReadings = daoBgreadings.query(preparedQuery);
return bgReadings; return bgReadings;
} catch (SQLException e) { } catch (SQLException e) {
log.error("Unhandled exception", e); log.error("Unhandled exception", e);
} }
return new ArrayList<BgReading>(); return new ArrayList<>();
} }
public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) { public List<BgReading> getAllBgreadingsDataFromTime(long mills, boolean ascending) {
@ -1143,6 +1165,17 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return false; return false;
} }
public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
try {
return getDaoExtendedBolus().queryBuilder()
.where().eq("pumpId", pumpId)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void delete(ExtendedBolus extendedBolus) { public void delete(ExtendedBolus extendedBolus) {
try { try {
getDaoExtendedBolus().delete(extendedBolus); getDaoExtendedBolus().delete(extendedBolus);
@ -1650,5 +1683,67 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null; return null;
} }
// ---------------- Insight history handling ---------------
public void createOrUpdate(InsightHistoryOffset offset) {
try {
getDaoInsightHistoryOffset().createOrUpdate(offset);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) {
try {
return getDaoInsightHistoryOffset().queryForId(pumpSerial);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightBolusID bolusID) {
try {
getDaoInsightBolusID().createOrUpdate(bolusID);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) {
try {
return getDaoInsightBolusID().queryBuilder()
.where().eq("pumpSerial", pumpSerial)
.and().eq("bolusID", bolusID)
.and().between("timestamp", timestamp - 259200000, timestamp + 259200000)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
public void createOrUpdate(InsightPumpID pumpID) {
try {
getDaoInsightPumpID().createOrUpdate(pumpID);
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
}
public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) {
try {
return getDaoInsightPumpID().queryBuilder()
.orderBy("timestamp", false)
.where().eq("pumpSerial", pumpSerial)
.and().in("eventType", "PumpStopped", "PumpPaused")
.and().lt("timestamp", before)
.queryForFirst();
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
return null;
}
// ---------------- Food handling --------------- // ---------------- Food handling ---------------
} }

View file

@ -9,7 +9,6 @@ import android.graphics.Color;
import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -22,14 +21,14 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.JsonHelper; import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.Round;
/** /**
* Created by mike on 21.05.2017. * Created by mike on 21.05.2017.

View file

@ -6,7 +6,6 @@ import android.support.annotation.Nullable;
import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.DatabaseTable;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -19,14 +18,14 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries; import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin; import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES) @DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface { public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@ -101,6 +100,11 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
return profile; return profile;
} }
/**
* Note: the name returned here is used as the PS name when uploading to NS. When such a PS is retrieved
* again from NS, the added parts must be removed again, see
* {@link info.nightscout.androidaps.utils.PercentageSplitter#pureName}
*/
public String getCustomizedName() { public String getCustomizedName() {
String name = profileName; String name = profileName;
if(LocalProfilePlugin.LOCAL_PROFILE.equals(name)){ if(LocalProfilePlugin.LOCAL_PROFILE.equals(name)){

View file

@ -6,14 +6,13 @@ import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS) @DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS)
public class TempTarget implements Interval { public class TempTarget implements Interval {

View file

@ -8,7 +8,6 @@ import org.slf4j.LoggerFactory;
import java.util.Objects; import java.util.Objects;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.IobTotal;
@ -16,12 +15,12 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval; import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
* Created by mike on 21.05.2017. * Created by mike on 21.05.2017.

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.events; package info.nightscout.androidaps.events;
import info.nightscout.utils.StringUtils; import info.nightscout.androidaps.utils.StringUtils;
public class EventNetworkChange extends Event { public class EventNetworkChange extends Event {

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.events;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
/** /**
* Created by mike on 04.06.2016. * Created by mike on 04.06.2016.

View file

@ -1,6 +1,6 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
/** /**
* Created by mike on 10.06.2016. * Created by mike on 10.06.2016.

View file

@ -27,10 +27,18 @@ public interface ConstraintsInterface {
return value; return value;
} }
default Constraint<Boolean> isUAMEnabled(Constraint<Boolean> value) {
return value;
}
default Constraint<Boolean> isAdvancedFilteringEnabled(Constraint<Boolean> value) { default Constraint<Boolean> isAdvancedFilteringEnabled(Constraint<Boolean> value) {
return value; return value;
} }
default Constraint<Boolean> isSuperBolusEnabled(Constraint<Boolean> value) {
return value;
}
default Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, Profile profile) { default Constraint<Double> applyBasalConstraints(Constraint<Double> absoluteRate, Profile profile) {
return absoluteRate; return absoluteRate;
} }

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
/** /**
* Created by mike on 17.04.2017. * Created by mike on 17.04.2017.

View file

@ -8,8 +8,8 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.queue.CommandQueue; import info.nightscout.androidaps.queue.CommandQueue;
/** /**
@ -93,6 +93,8 @@ public abstract class PluginBase {
return state == State.ENABLED && specialEnableCondition(); return state == State.ENABLED && specialEnableCondition();
if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP)) if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP))
return true; return true;
if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.APS && isEnabled(PluginType.APS))
return true;
if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP) if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP)
return isProfileInterfaceEnabled; return isProfileInterfaceEnabled;
return false; return false;

View file

@ -1,8 +1,8 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpCapability; import info.nightscout.androidaps.plugins.pump.common.defs.PumpCapability;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpTempBasalType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpTempBasalType;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
/** /**
* Created by mike on 08.12.2016. * Created by mike on 08.12.2016.

View file

@ -2,9 +2,13 @@ package info.nightscout.androidaps.interfaces;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
/** /**
* Created by mike on 04.06.2016. * Created by mike on 04.06.2016.
@ -33,6 +37,10 @@ public interface PumpInterface {
double getBaseBasalRate(); // base basal rate, not temp basal double getBaseBasalRate(); // base basal rate, not temp basal
double getReservoirLevel();
int getBatteryLevel(); // in percent as integer
PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo); PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo);
void stopBolusDelivering(); void stopBolusDelivering();
PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew); PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew);
@ -57,4 +65,9 @@ public interface PumpInterface {
PumpEnactResult loadTDDs(); PumpEnactResult loadTDDs();
List<CustomAction> getCustomActions();
void executeCustomAction(CustomActionType customActionType);
} }

View file

@ -1,7 +1,7 @@
package info.nightscout.androidaps.interfaces; package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
/** /**
* Created by mike on 24.06.2017. * Created by mike on 24.06.2017.

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.plugins.Treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.data.Intervals; import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.ProfileIntervals; import info.nightscout.androidaps.data.ProfileIntervals;

View file

@ -3,7 +3,7 @@ package info.nightscout.androidaps.logging;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
public class L { public class L {
@ -96,17 +96,18 @@ public class L {
public static final String CONFIGBUILDER = "CONFIGBUILDER"; public static final String CONFIGBUILDER = "CONFIGBUILDER";
public static final String UI = "UI"; public static final String UI = "UI";
public static final String LOCATION = "LOCATION"; public static final String LOCATION = "LOCATION";
public static final String SMS = "SMS";
private static void initialize() { private static void initialize() {
logElements = new ArrayList<>(); logElements = new ArrayList<>();
logElements.add(new LogElement(APS, true)); logElements.add(new LogElement(APS, true));
logElements.add(new LogElement(AUTOSENS, true)); logElements.add(new LogElement(AUTOSENS, false));
logElements.add(new LogElement(BGSOURCE, true)); logElements.add(new LogElement(BGSOURCE, true));
logElements.add(new LogElement(CONFIGBUILDER, true)); logElements.add(new LogElement(CONFIGBUILDER, false));
logElements.add(new LogElement(CONSTRAINTS, true)); logElements.add(new LogElement(CONSTRAINTS, true));
logElements.add(new LogElement(CORE, true)); logElements.add(new LogElement(CORE, true));
logElements.add(new LogElement(DATABASE, true)); logElements.add(new LogElement(DATABASE, true));
logElements.add(new LogElement(DATAFOOD, true)); logElements.add(new LogElement(DATAFOOD, false));
logElements.add(new LogElement(DATASERVICE, true)); logElements.add(new LogElement(DATASERVICE, true));
logElements.add(new LogElement(DATATREATMENTS, true)); logElements.add(new LogElement(DATATREATMENTS, true));
logElements.add(new LogElement(EVENTS, false, true)); logElements.add(new LogElement(EVENTS, false, true));
@ -119,6 +120,7 @@ public class L {
logElements.add(new LogElement(PUMPBTCOMM, false)); logElements.add(new LogElement(PUMPBTCOMM, false));
logElements.add(new LogElement(PUMPCOMM, true)); logElements.add(new LogElement(PUMPCOMM, true));
logElements.add(new LogElement(PUMPQUEUE, true)); logElements.add(new LogElement(PUMPQUEUE, true));
logElements.add(new LogElement(SMS, true));
logElements.add(new LogElement(UI, true)); logElements.add(new LogElement(UI, true));
} }

View file

@ -1,114 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
import info.nightscout.androidaps.plugins.PumpInsight.utils.ui.StatusItemViewAdapter;
import info.nightscout.utils.FabricPrivacy;
public class InsightFragment extends SubscriberFragment {
private static final Logger log = LoggerFactory.getLogger(L.PUMP);
private static final Handler sLoopHandler = new Handler();
private static volatile boolean refresh = false;
private static volatile boolean pending = false;
StatusItemViewAdapter viewAdapter;
LinearLayout holder;
private final Runnable sRefreshLoop = new Runnable() {
@Override
public void run() {
pending = false;
updateGUI();
if (refresh) {
scheduleRefresh();
}
}
};
private synchronized void scheduleRefresh() {
if (!pending) {
pending = true;
sLoopHandler.postDelayed(sRefreshLoop, 30 * 1000L);
}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
final View view = inflater.inflate(R.layout.insightpump_fragment, container, false);
holder = (LinearLayout) view.findViewById(R.id.insightholder);
viewAdapter = new StatusItemViewAdapter(getActivity(), holder);
return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
}
return null;
}
@Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
if (visible) {
refresh = true;
pending = false;
updateGUI();
scheduleRefresh();
} else {
refresh = false;
//sLoopHandler.removeCallbacksAndMessages(null);
}
}
@Subscribe
public void onStatusEvent(final EventInsightUpdateGui ev) {
updateGUI();
}
@Override
protected void updateGUI() {
final Activity activity = getActivity();
if (activity != null && holder != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
final InsightPlugin insightPlugin = InsightPlugin.getPlugin();
final List<StatusItem> l = insightPlugin.getStatusItems(refresh);
holder.removeAllViews();
for (StatusItem row : l) {
viewAdapter.inflateStatus(row);
}
}
});
}
}

View file

@ -1,935 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight;
import android.content.DialogInterface;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
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.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
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.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
import info.nightscout.androidaps.plugins.PumpInsight.connector.CancelBolusSilentlyTaskRunner;
import info.nightscout.androidaps.plugins.PumpInsight.connector.CancelTBRSilentlyTaskRunner;
import info.nightscout.androidaps.plugins.PumpInsight.connector.Connector;
import info.nightscout.androidaps.plugins.PumpInsight.connector.SetTBRTaskRunner;
import info.nightscout.androidaps.plugins.PumpInsight.connector.StatusTaskRunner;
import info.nightscout.androidaps.plugins.PumpInsight.connector.WriteBasalProfileTaskRunner;
import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightCallback;
import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver;
import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory;
import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers;
import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
import info.nightscout.androidaps.plugins.Treatments.Treatment;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.SP;
import sugar.free.sightparser.applayer.descriptors.ActiveBolus;
import sugar.free.sightparser.applayer.descriptors.ActiveBolusType;
import sugar.free.sightparser.applayer.descriptors.MessagePriority;
import sugar.free.sightparser.applayer.descriptors.PumpStatus;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.remote_control.BolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.CancelBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.ExtendedBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.StandardBolusMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
import sugar.free.sightparser.handling.SingleMessageTaskRunner;
import sugar.free.sightparser.handling.TaskRunner;
import sugar.free.sightparser.pipeline.Status;
import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache.getRecordUniqueID;
/**
* Created by jamorham on 23/01/2018.
* <p>
* Connects to SightRemote app service using SightParser library
* <p>
* SightRemote and SightParser created by Tebbe Ubben
* <p>
* Original proof of concept SightProxy by jamorham
*/
@SuppressWarnings("AccessStaticViaInstance")
public class InsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface {
private Logger log = LoggerFactory.getLogger(L.PUMP);
private static volatile InsightPlugin plugin;
public static InsightPlugin getPlugin() {
if (plugin == null) {
plugin = new InsightPlugin();
}
return plugin;
}
private static final long BUSY_WAIT_TIME = 20000;
private static Integer batteryPercent = 0;
private static Integer reservoirInUnits = 0;
private static boolean initialized = false;
private static volatile boolean update_pending = false;
private StatusTaskRunner.Result statusResult;
private long statusResultTime = -1;
private long lastDataTime = 0;
private boolean fauxTBRcancel = true;
private PumpDescription pumpDescription = new PumpDescription();
private double basalRate = 0;
private Connector connector;
private volatile boolean connector_enabled = false;
private List<BRProfileBlock.ProfileBlock> profileBlocks;
private InsightPlugin() {
super(new PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(InsightFragment.class.getName())
.pluginName(R.string.insightpump)
.shortName(R.string.insightpump_shortname)
.preferencesId(R.xml.pref_insightpump)
.description(R.string.description_pump_insight)
);
if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin instantiated");
pumpDescription.setPumpDescription(PumpType.AccuChekInsight);
}
private static void updateGui() {
update_pending = false;
MainApp.bus().post(new EventInsightUpdateGui());
}
private static void pushCallbackEvent(EventInsightCallback e) {
MainApp.bus().post(e);
}
@Override
protected void onStart() {
if (!connector_enabled) {
synchronized (this) {
if (!connector_enabled) {
if (L.isEnabled(L.PUMP))
log.debug("Instantiating connector");
connector_enabled = true;
this.connector = Connector.get();
this.connector.init();
}
}
}
super.onStart();
}
protected void onStop() {
if (connector_enabled) {
synchronized (this) {
if (connector_enabled) {
if (L.isEnabled(L.PUMP))
log.debug("Shutting down connector");
Connector.get().shutdown();
connector_enabled = false;
}
}
}
}
@Override
public boolean isFakingTempsByExtendedBoluses() {
return true;
}
@Override
public PumpEnactResult loadTDDs() {
PumpEnactResult result = new PumpEnactResult();
result.success = true;
return result;
}
@Override
public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) {
boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);
if (allowHardwarePump || context == null) {
pluginSwitcher.invoke();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.allow_hardware_pump_text)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
pluginSwitcher.invoke();
SP.putBoolean("allow_hardware_pump", true);
log.debug("First time HW pump allowed!");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
pluginSwitcher.cancel();
log.debug("User does not allow switching to HW pump!");
}
});
builder.create().show();
}
}
@Override
public boolean isInitialized() {
return initialized;
}
@Override
public boolean isSuspended() {
return !isPumpRunning();
}
@Override
public boolean isBusy() {
return false;
}
@Override
public boolean isConnected() {
return Connector.get().isPumpConnected();
}
@Override
public boolean isConnecting() {
return Connector.get().isPumpConnecting();
}
@Override
public boolean isHandshakeInProgress() {
return false;
}
@Override
public void finishHandshaking() {
}
@Override
public void connect(String reason) {
if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin::connect()");
try {
if (!connector.isPumpConnected()) {
if (Helpers.ratelimit("insight-connect-timer", 40)) {
if (L.isEnabled(L.PUMP))
log.debug("Actually requesting a connect");
connector.connectToPump();
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("Already connected");
}
} catch (NullPointerException e) {
log.error("Could not sconnect - null pointer: " + e);
}
// TODO review
if (!Config.NSCLIENT)
NSUpload.uploadDeviceStatus();
}
@Override
public void disconnect(String reason) {
if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin::disconnect()");
try {
if (!SP.getBoolean("insight_always_connected", false)) {
if (L.isEnabled(L.PUMP))
log.debug("Requesting disconnect");
connector.disconnectFromPump();
} else {
if (L.isEnabled(L.PUMP))
log.debug("Not disconnecting due to preference");
}
} catch (NullPointerException e) {
log.error("Could not disconnect - null pointer: " + e);
}
}
@Override
public void stopConnecting() {
if (L.isEnabled(L.PUMP))
log.debug("InsightPlugin::stopConnecting()");
try {
if (isConnecting()) {
if (!SP.getBoolean("insight_always_connected", false)) {
if (L.isEnabled(L.PUMP))
log.debug("Requesting disconnect");
connector.disconnectFromPump();
} else {
if (L.isEnabled(L.PUMP))
log.debug("Not disconnecting due to preference");
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("Not currently trying to connect so not stopping connection");
}
} catch (NullPointerException e) {
log.error("Could not stop connecting - null pointer: " + e);
}
}
@Override
public void getPumpStatus() {
if (L.isEnabled(L.PUMP))
log.debug("getPumpStatus");
if (Connector.get().isPumpConnected()) {
if (L.isEnabled(L.PUMP))
log.debug("is connected.. requesting status");
try {
setStatusResult(fetchTaskRunner(new StatusTaskRunner(connector.getServiceConnector()), StatusTaskRunner.Result.class));
if (L.isEnabled(L.PUMP))
log.debug("GOT STATUS RESULT!!! PARTY WOOHOO!!!");
statusResultTime = Helpers.tsl();
processStatusResult();
updateGui();
connector.requestHistoryReSync();
connector.requestHistorySync();
} catch (Exception e) {
log.error("StatusTaskRunner wasn't successful.");
if (connector.getServiceConnector().isConnectedToService() && connector.getServiceConnector().getStatus() != Status.CONNECTED) {
if (Helpers.ratelimit("insight-reconnect", 2)) {
Connector.connectToPump();
updateGui();
}
}
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("not connected.. not requesting status");
}
}
public void setStatusResult(StatusTaskRunner.Result result) {
this.statusResult = result;
this.pumpDescription.basalMinimumRate = result.minimumBasalAmount;
this.pumpDescription.basalMaximumRate = result.maximumBasalAmount;
}
@Override
public PumpEnactResult setNewBasalProfile(Profile profile) {
PumpEnactResult result = new PumpEnactResult();
if (!isInitialized()) {
log.error("setNewBasalProfile not initialized");
Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
return result;
}
MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
List<BRProfileBlock.ProfileBlock> profileBlocks = new ArrayList<>();
for (int i = 0; i < profile.getBasalValues().length; i++) {
Profile.BasalValue basalValue = profile.getBasalValues()[i];
Profile.BasalValue nextValue = null;
if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1];
profileBlocks.add(new BRProfileBlock.ProfileBlock((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60), Helpers.roundDouble(basalValue.value, 2)));
if (L.isEnabled(L.PUMP))
log.debug("setNewBasalProfile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
}
try {
fetchTaskRunner(new WriteBasalProfileTaskRunner(connector.getServiceConnector(), profileBlocks));
MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
MainApp.bus().post(new EventNewNotification(notification));
result.success = true;
result.enacted = true;
result.comment = "OK";
this.profileBlocks = profileBlocks;
} catch (Exception e) {
Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
MainApp.bus().post(new EventNewNotification(notification));
result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
}
return result;
}
@Override
public boolean isThisProfileSet(Profile profile) {
if (!isInitialized() || profileBlocks == null) return true;
if (profile.getBasalValues().length != profileBlocks.size()) return false;
for (int i = 0; i < profileBlocks.size(); i++) {
BRProfileBlock.ProfileBlock profileBlock = profileBlocks.get(i);
Profile.BasalValue basalValue = profile.getBasalValues()[i];
Profile.BasalValue nextValue = null;
if (profile.getBasalValues().length > i + 1)
nextValue = profile.getBasalValues()[i + 1];
if (L.isEnabled(L.PUMP))
log.debug("isThisProfileSet - Comparing block: Pump: " + profileBlock.getAmount() + " for " + profileBlock.getDuration()
+ " Profile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds)
return false;
//Allow a little imprecision due to rounding errors
if (Math.abs(profileBlock.getAmount() - Helpers.roundDouble(basalValue.value, 2)) >= 0.01D)
return false;
}
return true;
}
@Override
public long lastDataTime() {
return lastDataTime;
}
@Override
public double getBaseBasalRate() {
return basalRate;
}
public String getBaseBasalRateString() {
final DecimalFormat df = new DecimalFormat("#.##");
return df.format(basalRate);
}
@Override
public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
final PumpEnactResult result = new PumpEnactResult();
result.bolusDelivered = detailedBolusInfo.insulin;
result.carbsDelivered = detailedBolusInfo.carbs;
result.enacted = result.bolusDelivered > 0 || result.carbsDelivered > 0;
result.comment = MainApp.gs(R.string.virtualpump_resultok);
result.percent = 100;
int bolusId = 0;
// is there an insulin component to the treatment?
if (detailedBolusInfo.insulin > 0) {
try {
bolusId = deliverBolus(detailedBolusInfo.insulin);
result.success = true;
detailedBolusInfo.pumpId = getRecordUniqueID(bolusId);
} catch (Exception e) {
return pumpEnactFailure();
}
} else {
result.success = true; // always true with carb only treatments
}
if (result.success) {
if (L.isEnabled(L.PUMP))
log.debug("Success!");
Treatment t = new Treatment();
t.isSMB = detailedBolusInfo.isSMB;
final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
bolusingEvent.t = t;
bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), 0F);
bolusingEvent.bolusId = bolusId;
bolusingEvent.percent = 0;
MainApp.bus().post(bolusingEvent);
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
} else {
if (L.isEnabled(L.PUMP))
log.debug("Failure to deliver treatment");
}
if (L.isEnabled(L.PUMP))
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
updateGui();
connector.tryToGetPumpStatusAgain();
if (result.success) while (true) {
try {
Thread.sleep(500);
final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
ActiveBolusesMessage activeBolusesMessage = fetchSingleMessage(new ActiveBolusesMessage(), ActiveBolusesMessage.class);
ActiveBolus activeBolus = null;
if (activeBolusesMessage.getBolus1() != null && activeBolusesMessage.getBolus1().getBolusID() == bolusingEvent.bolusId)
activeBolus = activeBolusesMessage.getBolus1();
else if (activeBolusesMessage.getBolus2() != null && activeBolusesMessage.getBolus2().getBolusID() == bolusingEvent.bolusId)
activeBolus = activeBolusesMessage.getBolus2();
else if (activeBolusesMessage.getBolus3() != null && activeBolusesMessage.getBolus3().getBolusID() == bolusingEvent.bolusId)
activeBolus = activeBolusesMessage.getBolus3();
if (activeBolus == null) break;
else {
int percentBefore = bolusingEvent.percent;
bolusingEvent.percent = (int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount()));
bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount());
if (percentBefore != bolusingEvent.percent) MainApp.bus().post(bolusingEvent);
}
} catch (Exception e) {
break;
}
}
connector.requestHistorySync(2000);
return result;
}
@Override
public void stopBolusDelivering() {
CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
cancelBolusMessage.setMessagePriority(MessagePriority.HIGHEST);
cancelBolusMessage.setBolusId(EventOverviewBolusProgress.getInstance().bolusId);
try {
fetchSingleMessage(cancelBolusMessage);
} catch (Exception e) {
}
}
// Temporary Basals
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
if (L.isEnabled(L.PUMP))
log.debug("Set TBR absolute: " + absoluteRate);
if (getBaseBasalRate() == 0) {
if (L.isEnabled(L.PUMP))
log.debug("Base basal rate appears to be zero!");
return pumpEnactFailure();
}
double percent = 100D / getBaseBasalRate() * absoluteRate;
if (L.isEnabled(L.PUMP))
log.debug("Calculated requested rate: " + absoluteRate + " base rate: " + getBaseBasalRate() + " percentage: " + percent + "%");
try {
if (percent > 250) {
if (L.isEnabled(L.PUMP))
log.debug("Calculated rate is above 250%, switching to emulation using extended boluses");
cancelTempBasal(true);
if (!setExtendedBolus((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes).success) {
//Fallback to TBR if setting an extended bolus didn't work
if (L.isEnabled(L.PUMP))
log.debug("Setting an extended bolus didn't work, falling back to normal TBR");
return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
}
return new PumpEnactResult().success(true).enacted(true).absolute(absoluteRate).duration(durationInMinutes);
} else {
if (L.isEnabled(L.PUMP))
log.debug("Calculated rate is below or equal to 250%, using normal TBRs");
cancelExtendedBolus();
return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
}
} catch (Exception e) {
return pumpEnactFailure();
}
}
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
if (L.isEnabled(L.PUMP))
log.debug("Set TBR %");
percent = (int) Math.round(((double) percent) / 10d) * 10;
if (percent == 100) {
// This would cause a cancel if a tbr is in progress so treat as a cancel
return cancelTempBasal(false);
} else if (percent > 250) percent = 250;
try {
fetchTaskRunner(new SetTBRTaskRunner(connector.getServiceConnector(), percent, durationInMinutes));
final TemporaryBasal tempBasal = new TemporaryBasal()
.date(System.currentTimeMillis())
.percent(percent)
.duration(durationInMinutes)
.source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
updateGui();
if (L.isEnabled(L.PUMP))
log.debug("Set temp basal " + percent + "% for " + durationInMinutes + "m");
connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain();
return new PumpEnactResult().success(true).enacted(true).percent(percent);
} catch (Exception e) {
return pumpEnactFailure();
}
}
@Override
public PumpEnactResult cancelTempBasal(boolean enforceNew) {
if (L.isEnabled(L.PUMP))
log.debug("Cancel TBR called");
try {
cancelExtendedBolus();
SystemClock.sleep(1100); // to be sure db records are at least 1 sec off (for NS)
realTBRCancel();
SystemClock.sleep(1100); // to be sure db records are at least 1 sec off (for NS)
updateGui();
connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain();
return new PumpEnactResult().success(true).enacted(true).isTempCancel(true);
} catch (Exception e) {
return pumpEnactFailure();
}
}
private void realTBRCancel() throws Exception {
if (fetchTaskRunner(new CancelTBRSilentlyTaskRunner(connector.getServiceConnector()), Boolean.class) && TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
TemporaryBasal tempStop = new TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop);
}
}
// Extended Boluses
@Override
public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
if (L.isEnabled(L.PUMP))
log.debug("Set Extended bolus " + insulin + " " + durationInMinutes);
try {
ExtendedBolusMessage extendedBolusMessage = new ExtendedBolusMessage();
extendedBolusMessage.setAmount(insulin);
extendedBolusMessage.setDuration(durationInMinutes);
BolusMessage bolusMessage = fetchSingleMessage(extendedBolusMessage, BolusMessage.class);
final ExtendedBolus extendedBolus = new ExtendedBolus()
.date(System.currentTimeMillis())
.insulin(insulin)
.durationInMinutes(durationInMinutes)
.source(Source.USER)
.pumpId(getRecordUniqueID(bolusMessage.getBolusId()));
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
updateGui();
connector.requestHistorySync(30000);
connector.tryToGetPumpStatusAgain();
return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin);
} catch (Exception e) {
return pumpEnactFailure();
}
}
@Override
public PumpEnactResult cancelExtendedBolus() {
if (L.isEnabled(L.PUMP))
log.debug("Cancel Extended bolus called");
Integer bolusId = null;
try {
bolusId = fetchTaskRunner(new CancelBolusSilentlyTaskRunner(connector.getServiceConnector(), ActiveBolusType.EXTENDED), Integer.class);
if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
ExtendedBolus exStop = new ExtendedBolus(System.currentTimeMillis());
exStop.source = Source.USER;
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop);
}
if (bolusId != null) connector.requestHistorySync(5000);
connector.tryToGetPumpStatusAgain();
updateGui();
return new PumpEnactResult().success(true).enacted(bolusId != null);
} catch (Exception e) {
return pumpEnactFailure();
}
}
private int deliverBolus(double bolusValue) throws Exception {
if (L.isEnabled(L.PUMP))
log.debug("DeliverBolus: " + bolusValue);
final StandardBolusMessage message = new StandardBolusMessage();
message.setAmount(bolusValue);
return fetchSingleMessage(message, BolusMessage.class).getBolusId();
}
@Override
public JSONObject getJSONStatus(Profile profile, String profileName) {
long now = System.currentTimeMillis();
if (Helpers.msSince(connector.getLastContactTime()) > (60 * 60 * 1000)) {
if (L.isEnabled(L.PUMP))
log.debug("getJSONStatus not returning as data likely stale");
return null;
}
final JSONObject pump = new JSONObject();
final JSONObject battery = new JSONObject();
final JSONObject status = new JSONObject();
final JSONObject extended = new JSONObject();
try {
battery.put("percent", batteryPercent);
status.put("status", isSuspended() ? "suspended" : "normal");
status.put("timestamp", DateUtil.toISOString(connector.getLastContactTime()));
extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
try {
extended.put("ActiveProfile", ProfileFunctions.getInstance().getProfileName());
} catch (Exception e) {
}
TemporaryBasal tb = TreatmentsPlugin.getPlugin().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.getPlugin().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());
status.put("timestamp", DateUtil.toISOString(now));
pump.put("battery", battery);
pump.put("status", status);
pump.put("extended", extended);
pump.put("reservoir", reservoirInUnits);
pump.put("clock", DateUtil.toISOString(now));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
return pump;
}
@Override
public String deviceID() {
return "InsightPump";
}
@Override
public PumpDescription getPumpDescription() {
return pumpDescription;
}
@Override
public String shortStatus(boolean veryShort) {
String msg = gs(R.string.insightpump_shortname) + " Batt: " + batteryPercent + " Reserv: " + reservoirInUnits + " Basal: " + basalRate;
if (LiveHistory.getStatus().length() > 0) {
msg += LiveHistory.getStatus();
}
return msg;
}
private void processStatusResult() {
if (statusResult != null) {
batteryPercent = statusResult.battery;
reservoirInUnits = (int) statusResult.cartridge;
basalRate = statusResult.baseBasalRate;
profileBlocks = statusResult.basalProfile;
initialized = true; // basic communication test
}
}
private String gs(int id) {
return MainApp.gs(id);
}
private boolean isPumpRunning() {
if (statusResult == null) return true; // assume running if we have no information
return statusResult.pumpStatus == PumpStatus.STARTED;
}
List<StatusItem> getStatusItems(boolean refresh) {
final List<StatusItem> l = new ArrayList<>();
// Todo last contact time
l.add(new StatusItem(gs(R.string.status_no_colon), connector.getLastStatusMessage()));
l.add(new StatusItem(gs(R.string.changed), connector.getNiceLastStatusTime()));
boolean pumpRunning;
// also check time since received
if (statusResult != null) {
pumpRunning = isPumpRunning();
if (pumpRunning) {
l.add(new StatusItem(gs(R.string.pump_basebasalrate_label), getBaseBasalRateString() + "U"));
} else {
l.add(new StatusItem(gs(R.string.combo_warning), gs(R.string.pump_stopped_uppercase), StatusItem.Highlight.CRITICAL));
}
}
final long offset_ms = Helpers.msSince(statusResultTime);
final long offset_minutes = offset_ms / 60000;
if (statusResult != null) {
l.add(new StatusItem(gs(R.string.status_updated), Helpers.niceTimeScalar(Helpers.msSince(statusResultTime)) + " " + gs(R.string.ago)));
l.add(new StatusItem(gs(R.string.pump_battery_label), batteryPercent + "%", batteryPercent < 100 ?
(batteryPercent < 90 ?
(batteryPercent < 70 ?
(StatusItem.Highlight.BAD) : StatusItem.Highlight.NOTICE) : StatusItem.Highlight.NORMAL) : StatusItem.Highlight.GOOD));
l.add(new StatusItem(gs(R.string.pump_reservoir_label), reservoirInUnits + "U"));
try {
if (statusResult.tbrAmount != 100) {
l.add(new StatusItem(gs(R.string.insight_active_tbr), statusResult.tbrAmount + "% " + gs(R.string.with) + " "
+ Helpers.qs(statusResult.tbrLeftoverDuration - offset_minutes, 0)
+ " " + gs(R.string.insight_min_left), StatusItem.Highlight.NOTICE));
}
} catch (NullPointerException e) {
// currentTBRMessage may be null
}
}
if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
try {
l.add(new StatusItem(gs(R.string.pump_tempbasal_label), TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()).toStringFull()));
} catch (NullPointerException e) {
//
}
}
if (statusResult != null) {
try {
statusActiveBolus(statusResult.activeBolus1, offset_minutes, l);
statusActiveBolus(statusResult.activeBolus2, offset_minutes, l);
statusActiveBolus(statusResult.activeBolus3, offset_minutes, l);
} catch (NullPointerException e) {
// getActiveBolusesMessage() may be null
}
}
if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
try {
l.add(new StatusItem(gs(R.string.virtualpump_extendedbolus_label), TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()).toString()));
} catch (NullPointerException e) {
//
}
}
l.add(new StatusItem(gs(R.string.log_book), HistoryReceiver.getStatusString()));
if (LiveHistory.getStatus().length() > 0) {
l.add(new StatusItem(gs(R.string.insight_last_completed_action), LiveHistory.getStatus()));
}
final String keep_alive_status = Connector.getKeepAliveString();
if (keep_alive_status != null) {
l.add(new StatusItem(gs(R.string.insight_keep_alive_status), keep_alive_status));
}
final List<StatusItem> status_statistics = connector.getStatusStatistics();
if (status_statistics.size() > 0) {
l.addAll(status_statistics);
}
if (Helpers.ratelimit("insight-status-ui-refresh", 10)) {
connector.tryToGetPumpStatusAgain();
}
connector.requestHistorySync();
if (refresh) scheduleGUIUpdate();
return l;
}
private synchronized void scheduleGUIUpdate() {
if (!update_pending && connector.uiFresh()) {
update_pending = true;
Helpers.runOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
updateGui();
}
}, 1000);
}
}
private void statusActiveBolus(ActiveBolus activeBolus, long offset_mins, List<StatusItem> l) {
if (activeBolus == null) return;
switch (activeBolus.getBolusType()) {
case STANDARD:
l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U", StatusItem.Highlight.NOTICE));
break;
case EXTENDED:
l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U " + gs(R.string.insight_total_with) + " "
+ activeBolus.getLeftoverAmount() + "U " + gs(R.string.insight_remaining_over) + " " + (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min), StatusItem.Highlight.NOTICE));
break;
case MULTIWAVE:
l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U " + gs(R.string.insight_upfront_with) + " "
+ activeBolus.getLeftoverAmount() + "U " + gs(R.string.insight_remaining_over) + " " + (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min), StatusItem.Highlight.NOTICE));
break;
default:
log.error("ERROR: unknown bolus type! " + activeBolus.getBolusType());
}
}
private void fetchTaskRunner(TaskRunner taskRunner) throws Exception {
fetchTaskRunner(taskRunner, Object.class);
}
private void fetchSingleMessage(AppLayerMessage message) throws Exception {
fetchSingleMessage(message, AppLayerMessage.class);
}
private <T> T fetchTaskRunner(TaskRunner taskRunner, Class<T> resultType) throws Exception {
try {
T result = (T) taskRunner.fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
lastDataTime = System.currentTimeMillis();
return result;
} catch (Exception e) {
log.error("Error while fetching " + taskRunner.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
throw e;
}
}
private <T extends AppLayerMessage> T fetchSingleMessage(AppLayerMessage message, Class<T> resultType) throws Exception {
try {
T result = (T) new SingleMessageTaskRunner(connector.getServiceConnector(), message).fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
lastDataTime = System.currentTimeMillis();
return result;
} catch (Exception e) {
log.error("Error while fetching " + message.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
throw e;
}
}
private PumpEnactResult pumpEnactFailure() {
return new PumpEnactResult().success(false).enacted(false);
}
// Constraints
@Override
public Constraint<Integer> applyBasalPercentConstraints(Constraint<Integer> percentRate, Profile profile) {
percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this);
percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this);
return percentRate;
}
@Override
public Constraint<Double> applyBolusConstraints(Constraint<Double> insulin) {
if (statusResult != null) {
insulin.setIfSmaller(statusResult.maximumBolusAmount, String.format(MainApp.gs(R.string.limitingbolus), statusResult.maximumBolusAmount, MainApp.gs(R.string.pumplimit)), this);
if (insulin.value() < statusResult.minimumBolusAmount) {
//TODO: Add function to Constraints or use different approach
// This only works if the interface of the InsightPlugin is called last.
// If not, another contraint could theoretically set the value between 0 and minimumBolusAmount
insulin.set(0d, String.format(MainApp.gs(R.string.limitingbolus), statusResult.minimumBolusAmount, MainApp.gs(R.string.pumplimit)), this);
}
}
return insulin;
}
}

View file

@ -1,66 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.connector;
import sugar.free.sightparser.applayer.descriptors.ActiveBolusType;
import sugar.free.sightparser.applayer.descriptors.MessagePriority;
import sugar.free.sightparser.applayer.descriptors.alerts.Warning38BolusCancelled;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.remote_control.CancelBolusMessage;
import sugar.free.sightparser.applayer.messages.remote_control.DismissAlertMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveAlertMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
import sugar.free.sightparser.handling.SightServiceConnector;
import sugar.free.sightparser.handling.TaskRunner;
// by Tebbe Ubben
public class CancelBolusSilentlyTaskRunner extends TaskRunner {
private ActiveBolusType bolusType;
private long cancelledAt;
private int bolusId;
public CancelBolusSilentlyTaskRunner(SightServiceConnector serviceConnector, ActiveBolusType bolusType) {
super(serviceConnector);
this.bolusType = bolusType;
}
@Override
protected AppLayerMessage run(AppLayerMessage message) throws Exception {
if (message == null) return new ActiveBolusesMessage();
else if (message instanceof ActiveBolusesMessage) {
ActiveBolusesMessage bolusesMessage = (ActiveBolusesMessage) message;
CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
if (bolusesMessage.getBolus1().getBolusType() == bolusType)
bolusId = bolusesMessage.getBolus1().getBolusID();
else if (bolusesMessage.getBolus2().getBolusType() == bolusType)
bolusId = bolusesMessage.getBolus2().getBolusID();
else if (bolusesMessage.getBolus3().getBolusType() == bolusType)
bolusId = bolusesMessage.getBolus3().getBolusID();
else finish(null);
cancelBolusMessage.setBolusId(bolusId);
return cancelBolusMessage;
} else if (message instanceof CancelBolusMessage) {
cancelledAt = System.currentTimeMillis();
ActiveAlertMessage activeAlertMessage = new ActiveAlertMessage();
activeAlertMessage.setMessagePriority(MessagePriority.HIGHER);
return activeAlertMessage;
} else if (message instanceof ActiveAlertMessage) {
ActiveAlertMessage activeAlertMessage = (ActiveAlertMessage) message;
if (activeAlertMessage.getAlert() == null) {
if (System.currentTimeMillis() - cancelledAt >= 10000) finish(bolusId);
else {
ActiveAlertMessage activeAlertMessage2 = new ActiveAlertMessage();
activeAlertMessage2.setMessagePriority(MessagePriority.HIGHER);
return activeAlertMessage2;
}
} else if (!(activeAlertMessage.getAlert() instanceof Warning38BolusCancelled)) finish(bolusId);
else {
DismissAlertMessage dismissAlertMessage = new DismissAlertMessage();
dismissAlertMessage.setAlertID(activeAlertMessage.getAlertID());
dismissAlertMessage.setMessagePriority(MessagePriority.HIGHER);
return dismissAlertMessage;
}
} else if (message instanceof DismissAlertMessage) finish(bolusId);
return null;
}
}

View file

@ -1,50 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.connector;
import sugar.free.sightparser.applayer.descriptors.MessagePriority;
import sugar.free.sightparser.applayer.descriptors.alerts.Warning36TBRCancelled;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.remote_control.CancelTBRMessage;
import sugar.free.sightparser.applayer.messages.remote_control.DismissAlertMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveAlertMessage;
import sugar.free.sightparser.applayer.messages.status.CurrentTBRMessage;
import sugar.free.sightparser.handling.SightServiceConnector;
import sugar.free.sightparser.handling.TaskRunner;
public class CancelTBRSilentlyTaskRunner extends TaskRunner {
private long cancelledAt;
public CancelTBRSilentlyTaskRunner(SightServiceConnector serviceConnector) {
super(serviceConnector);
}
@Override
protected AppLayerMessage run(AppLayerMessage message) throws Exception {
if (message == null) return new CurrentTBRMessage();
else if (message instanceof CurrentTBRMessage) {
if (((CurrentTBRMessage) message).getPercentage() == 100) finish(false);
else return new CancelTBRMessage();
} else if (message instanceof CancelTBRMessage) {
ActiveAlertMessage activeAlertMessage = new ActiveAlertMessage();
activeAlertMessage.setMessagePriority(MessagePriority.HIGHER);
return activeAlertMessage;
} else if (message instanceof ActiveAlertMessage) {
ActiveAlertMessage activeAlertMessage = (ActiveAlertMessage) message;
if (activeAlertMessage.getAlert() == null) {
if (System.currentTimeMillis() - cancelledAt >= 10000) finish(true);
else {
ActiveAlertMessage activeAlertMessage2 = new ActiveAlertMessage();
activeAlertMessage2.setMessagePriority(MessagePriority.HIGHER);
return activeAlertMessage2;
}
} else if (!(activeAlertMessage.getAlert() instanceof Warning36TBRCancelled)) finish(true);
else {
DismissAlertMessage dismissAlertMessage = new DismissAlertMessage();
dismissAlertMessage.setAlertID(activeAlertMessage.getAlertID());
dismissAlertMessage.setMessagePriority(MessagePriority.HIGHER);
return dismissAlertMessage;
}
} else if (message instanceof DismissAlertMessage) finish(true);
return null;
}
}

View file

@ -1,574 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.connector;
import android.content.Intent;
import android.os.PowerManager;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventFeatureRunning;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver;
import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory;
import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers;
import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
import info.nightscout.utils.SP;
import sugar.free.sightparser.handling.ServiceConnectionCallback;
import sugar.free.sightparser.handling.SightServiceConnector;
import sugar.free.sightparser.handling.StatusCallback;
import sugar.free.sightparser.pipeline.Status;
import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_RESYNC;
import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_SYNC;
import static sugar.free.sightparser.handling.SightService.COMPATIBILITY_VERSION;
/**
* Created by jamorham on 23/01/2018.
* <p>
* Connects to SightRemote app service using SightParser library
* <p>
* SightRemote and SightParser created by Tebbe Ubben
* <p>
* Original proof of concept SightProxy by jamorham
*/
public class Connector {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
// TODO connection statistics
private static final String TAG = "InsightConnector";
private static final String COMPANION_APP_PACKAGE = "sugar.free.sightremote";
private final static long FRESH_MS = 70000;
private static final Map<Status, Long> statistics = new HashMap<>();
private static volatile Connector instance;
private static volatile HistoryReceiver historyReceiver;
private static volatile long stayConnectedTill = -1;
private static volatile long stayConnectedTime = 0;
private static volatile boolean disconnect_thread_running = false;
private volatile SightServiceConnector serviceConnector;
private volatile Status lastStatus = null;
private String compatabilityMessage = null;
private volatile long lastStatusTime = -1;
private volatile long lastContactTime = -1;
private boolean companionAppInstalled = false;
private int serviceReconnects = 0;
private StatusCallback statusCallback = new StatusCallback() {
@Override
public synchronized void onStatusChange(Status status, long statusTime, long waitTime) {
if ((status != lastStatus) || (Helpers.msSince(lastStatusTime) > 2000)) {
if (L.isEnabled(L.PUMP))
log.debug("Status change: " + status);
updateStatusStatistics(lastStatus, lastStatusTime);
lastStatus = status;
lastStatusTime = Helpers.tsl();
if (status == Status.CONNECTED) {
lastContactTime = lastStatusTime;
extendKeepAliveIfActive();
}
MainApp.bus().post(new EventInsightUpdateGui());
} else {
if (L.isEnabled(L.PUMP))
log.debug("Same status as before: " + status);
}
}
};
private ServiceConnectionCallback connectionCallback = new ServiceConnectionCallback() {
@Override
public synchronized void onServiceConnected() {
if (L.isEnabled(L.PUMP))
log.debug("On service connected");
try {
final String remoteVersion = serviceConnector.getRemoteVersion();
if (remoteVersion.equals(COMPATIBILITY_VERSION)) {
serviceConnector.connect();
} else {
log.error("PROTOCOL VERSION MISMATCH! local: " + COMPATIBILITY_VERSION + " remote: " + remoteVersion);
statusCallback.onStatusChange(Status.INCOMPATIBLE, 0, 0);
compatabilityMessage = MainApp.gs(R.string.insight_incompatible_compantion_app_we_need_version) + " " + getLocalVersion();
serviceConnector.disconnectFromService();
}
} catch (NullPointerException e) {
log.error("ERROR: null pointer when trying to connect to pump");
}
statusCallback.onStatusChange(safeGetStatus(), 0, 0);
}
@Override
public synchronized void onServiceDisconnected() {
if (L.isEnabled(L.PUMP))
log.debug("Disconnected from service");
if (Helpers.ratelimit("insight-automatic-reconnect", 30)) {
if (L.isEnabled(L.PUMP))
log.debug("Scheduling automatic service reconnection");
Helpers.runOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
init();
}
}, 20000);
}
}
};
private Connector() {
initializeHistoryReceiver();
MainApp.bus().register(this);
}
public static Connector get() {
if (instance == null) {
init_instance();
}
return instance;
}
private synchronized static void init_instance() {
if (instance == null) {
instance = new Connector();
}
}
private static boolean isCompanionAppInstalled() {
return Helpers.checkPackageExists(MainApp.instance(), TAG, COMPANION_APP_PACKAGE);
}
public static void connectToPump() {
connectToPump(0);
}
public synchronized static void connectToPump(long keep_alive) {
if (L.isEnabled(L.PUMP))
log.debug("Attempting to connect to pump.");
if (keep_alive > 0 && Helpers.tsl() + keep_alive > stayConnectedTill) {
stayConnectedTime = keep_alive;
stayConnectedTill = Helpers.tsl() + keep_alive;
if (L.isEnabled(L.PUMP))
log.debug("Staying connected till: " + Helpers.dateTimeText(stayConnectedTill));
delayedDisconnectionThread();
}
get().getServiceConnector().connect();
}
public static void disconnectFromPump() {
if (Helpers.tsl() >= stayConnectedTill) {
if (L.isEnabled(L.PUMP))
log.debug("Requesting real pump disconnect");
get().getServiceConnector().disconnect();
} else {
if (L.isEnabled(L.PUMP))
log.debug("Cannot disconnect as due to keep alive till: " + Helpers.dateTimeText(stayConnectedTill));
// TODO set a disconnection timer?
}
}
static String getLocalVersion() {
return COMPATIBILITY_VERSION;
}
private static String statusToString(Status status) {
switch (status) {
case EXCHANGING_KEYS:
return MainApp.gs(R.string.connecting).toUpperCase();
case WAITING_FOR_CODE_CONFIRMATION:
return MainApp.gs(R.string.insight_waiting_for_code).toUpperCase();
case CODE_REJECTED:
return MainApp.gs(R.string.insight_code_rejected).toUpperCase();
case APP_BINDING:
return MainApp.gs(R.string.insight_app_binding).toUpperCase();
case CONNECTING:
return MainApp.gs(R.string.connecting).toUpperCase();
case CONNECTED:
return MainApp.gs(R.string.connected).toUpperCase();
case DISCONNECTED:
return MainApp.gs(R.string.disconnected).toUpperCase();
case NOT_AUTHORIZED:
return MainApp.gs(R.string.insight_not_authorized).toUpperCase();
case INCOMPATIBLE:
return MainApp.gs(R.string.insight_incompatible).toUpperCase();
default:
return status.toString();
}
}
private static synchronized void extendKeepAliveIfActive() {
if (keepAliveActive()) {
if (Helpers.ratelimit("extend-insight-keepalive", 10)) {
stayConnectedTill = Helpers.tsl() + stayConnectedTime;
if (L.isEnabled(L.PUMP))
log.debug("Keep-alive extended until: " + Helpers.dateTimeText(stayConnectedTill));
}
}
}
private static boolean keepAliveActive() {
return Helpers.tsl() <= stayConnectedTill;
}
public static String getKeepAliveString() {
if (keepAliveActive()) {
return MainApp.gs(R.string.insight_keepalive_format_string,
stayConnectedTime / 1000, Helpers.hourMinuteSecondString(stayConnectedTill));
} else {
return null;
}
}
private static synchronized void delayedDisconnectionThread() {
if (keepAliveActive()) {
if (!disconnect_thread_running) {
disconnect_thread_running = true;
new Thread(new Runnable() {
@Override
public void run() {
final PowerManager.WakeLock wl = Helpers.getWakeLock("insight-disconnection-timer", 600000);
try {
while (disconnect_thread_running && keepAliveActive()) {
if (Helpers.ratelimit("insight-expiry-notice", 5)) {
if (L.isEnabled(L.PUMP))
log.debug("Staying connected thread expires: " + Helpers.dateTimeText(stayConnectedTill));
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//
}
}
if (disconnect_thread_running) {
if (L.isEnabled(L.PUMP))
log.debug("Sending the real delayed disconnect");
get().getServiceConnector().disconnect();
} else {
if (L.isEnabled(L.PUMP))
log.debug("Disconnect thread already terminating");
}
} finally {
Helpers.releaseWakeLock(wl);
disconnect_thread_running = false;
}
}
}).start();
} else {
if (L.isEnabled(L.PUMP))
log.debug("Disconnect thread already running");
}
}
}
private static long percentage(long t, long total) {
return (long) (Helpers.roundDouble(((double) t * 100) / total, 0));
}
public synchronized void shutdown() {
if (instance != null) {
if (L.isEnabled(L.PUMP))
log.debug("Attempting to shut down connector");
try {
disconnect_thread_running = false;
try {
instance.serviceConnector.setConnectionCallback(null);
} catch (Exception e) {
//
}
try {
instance.serviceConnector.removeStatusCallback(statusCallback);
} catch (Exception e) {
//
}
try {
instance.serviceConnector.disconnect();
} catch (Exception e) {
log.error("Exception disconnecting: " + e);
}
try {
instance.serviceConnector.disconnectFromService();
} catch (Exception e) {
log.error("Excpetion disconnecting service: " + e);
}
instance.serviceConnector = null;
instance = null;
} catch (Exception e) {
log.error("Exception shutting down: " + e);
}
}
}
@SuppressWarnings("AccessStaticViaInstance")
private synchronized void initializeHistoryReceiver() {
if (historyReceiver == null) {
historyReceiver = new HistoryReceiver();
}
historyReceiver.registerHistoryReceiver();
}
public synchronized void init() {
if (L.isEnabled(L.PUMP))
log.debug("Connector::init()");
if (serviceConnector == null) {
companionAppInstalled = isCompanionAppInstalled();
if (companionAppInstalled) {
serviceConnector = new SightServiceConnector(MainApp.instance());
serviceConnector.removeStatusCallback(statusCallback);
serviceConnector.addStatusCallback(statusCallback);
serviceConnector.setConnectionCallback(connectionCallback);
serviceConnector.connectToService();
if (L.isEnabled(L.PUMP))
log.debug("Trying to connect");
} else {
if (L.isEnabled(L.PUMP))
log.debug("Not trying init due to missing companion app");
}
} else {
if (!serviceConnector.isConnectedToService()) {
if (serviceReconnects > 0) {
serviceConnector = null;
init();
} else {
if (L.isEnabled(L.PUMP))
log.debug("Trying to reconnect to service (" + serviceReconnects + ")");
serviceConnector.connectToService();
serviceReconnects++;
}
} else {
serviceReconnects = 0; // everything ok
}
}
}
public SightServiceConnector getServiceConnector() {
init();
return serviceConnector;
}
public String getCurrent() {
init();
return safeGetStatus().toString();
}
public Status safeGetStatus() {
try {
if (isConnected()) return serviceConnector.getStatus();
return Status.DISCONNECTED;
} catch (IllegalArgumentException e) {
return Status.INCOMPATIBLE;
}
}
public Status getLastStatus() {
return lastStatus;
}
public boolean isConnected() {
return serviceConnector != null && serviceConnector.isConnectedToService();
}
public boolean isPumpConnected() {
return isConnected() && getLastStatus() == Status.CONNECTED;
}
public boolean isPumpConnecting() {
return isConnected() && getLastStatus() == Status.CONNECTING;
}
public long getLastContactTime() {
return lastContactTime;
}
public String getLastStatusMessage() {
if (!companionAppInstalled) {
return MainApp.gs(R.string.insight_companion_app_not_installed);
}
if (!isConnected()) {
if (L.isEnabled(L.PUMP))
log.debug("Not connected to companion");
if (Helpers.ratelimit("insight-app-not-connected", 5)) {
init();
}
if ((lastStatus == null) || (lastStatus != Status.INCOMPATIBLE)) {
if (compatabilityMessage != null) {
// if disconnected but previous state was incompatible
return compatabilityMessage;
} else {
return MainApp.gs(R.string.insight_not_connected_to_companion_app);
}
}
}
if (lastStatus == null) {
return MainApp.gs(R.string.unknown);
}
switch (lastStatus) {
case CONNECTED:
if (Helpers.msSince(lastStatusTime) > (60 * 10 * 1000)) {
tryToGetPumpStatusAgain();
}
break;
case INCOMPATIBLE:
return statusToString(lastStatus) + " " + MainApp.gs(R.string.insight_needs) + " " + getLocalVersion();
}
return statusToString(lastStatus);
}
public String getNiceLastStatusTime() {
if (lastStatusTime < 1) {
return MainApp.gs(R.string.insight_startup_uppercase);
} else {
return Helpers.niceTimeScalar(Helpers.msSince(lastStatusTime)) + " " + MainApp.gs(R.string.ago);
}
}
public boolean uiFresh() {
// todo check other changes
if (Helpers.msSince(lastStatusTime) < FRESH_MS) {
return true;
}
if (Helpers.msSince(LiveHistory.getStatusTime()) < FRESH_MS) {
return true;
}
return false;
}
@SuppressWarnings("AccessStaticViaInstance")
public void tryToGetPumpStatusAgain() {
if (Helpers.ratelimit("insight-retry-status-request", 5)) {
try {
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Insight. Status missing", null);
} catch (NullPointerException e) {
//
}
}
}
public void requestHistorySync() {
requestHistorySync(0);
}
public void requestHistoryReSync() {
requestHistoryReSync(0);
}
public void requestHistorySync(long delay) {
if (Helpers.ratelimit("insight-history-sync-request", 10)) {
final Intent intent = new Intent(ACTION_START_SYNC);
sendBroadcastToCompanion(intent, delay);
}
}
public void requestHistoryReSync(long delay) {
if (Helpers.ratelimit("insight-history-resync-request", 300)) {
final Intent intent = new Intent(ACTION_START_RESYNC);
sendBroadcastToCompanion(intent, delay);
}
}
private void sendBroadcastToCompanion(final Intent intent, final long delay) {
new Thread(new Runnable() {
@Override
public void run() {
final PowerManager.WakeLock wl = Helpers.getWakeLock("insight-companion-delay", 60000);
intent.setPackage(COMPANION_APP_PACKAGE);
intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
try {
if (delay > 0) {
Thread.sleep(delay);
}
} catch (InterruptedException e) {
//
} finally {
Helpers.releaseWakeLock(wl);
}
MainApp.instance().sendBroadcast(intent);
}
}).start();
}
public boolean lastStatusRecent() {
return true; // TODO evaluate whether current
}
private void updateStatusStatistics(Status last, long since) {
if ((last != null) && (since > 0)) {
Long total = statistics.get(last);
if (total == null) total = 0L;
statistics.put(last, total + Helpers.msSince(since));
if (L.isEnabled(L.PUMP))
log.debug("Updated statistics for: " + last + " total: " + Helpers.niceTimeScalar(statistics.get(last)));
// TODO persist data
}
}
public List<StatusItem> getStatusStatistics() {
final List<StatusItem> l = new ArrayList<>();
long total = 0;
for (Map.Entry entry : statistics.entrySet()) {
total += getEntryTime(entry);
}
for (Map.Entry entry : statistics.entrySet()) {
if ((long) entry.getValue() > 1000) {
l.add(new StatusItem(MainApp.gs(R.string.statistics) + " " + Helpers.capitalize(entry.getKey().toString()),
new Formatter().format("%4s %12s",
percentage(getEntryTime(entry), total) + "%",
Helpers.niceTimeScalar(getEntryTime(entry))).toString()));
}
}
return l;
}
private long getEntryTime(Map.Entry entry) {
return (long) entry.getValue() + (entry.getKey().equals(lastStatus) ? Helpers.msSince(lastStatusTime) : 0);
}
@Subscribe
public void onStatusEvent(final EventFeatureRunning ev) {
new Thread(new Runnable() {
@Override
public void run() {
if (isConnected()) {
if (SP.getBoolean("insight_preemptive_connect", true)) {
switch (ev.getFeature()) {
case WIZARD:
if (L.isEnabled(L.PUMP))
log.debug("Wizard feature detected, preconnecting to pump");
connectToPump(120 * 1000);
break;
case MAIN:
if (L.isEnabled(L.PUMP))
log.debug("Main feature detected, preconnecting to pump");
connectToPump(30 * 1000);
break;
}
}
}
}
}).start();
}
}

View file

@ -1,41 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.connector;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.remote_control.ChangeTBRMessage;
import sugar.free.sightparser.applayer.messages.remote_control.SetTBRMessage;
import sugar.free.sightparser.applayer.messages.status.CurrentTBRMessage;
import sugar.free.sightparser.handling.SightServiceConnector;
import sugar.free.sightparser.handling.TaskRunner;
// from Tebbe - note this uses 1 minute duration to silently cancel existing TBR
public class SetTBRTaskRunner extends TaskRunner {
private int amount;
private int duration;
public SetTBRTaskRunner(SightServiceConnector serviceConnector, int amount, int duration) {
super(serviceConnector);
this.amount = amount;
this.duration = duration;
}
@Override
protected AppLayerMessage run(AppLayerMessage message) throws Exception {
if (message == null) return new CurrentTBRMessage();
else if (message instanceof CurrentTBRMessage) {
if (((CurrentTBRMessage) message).getPercentage() == 100) {
SetTBRMessage setTBRMessage = new SetTBRMessage();
setTBRMessage.setDuration(duration);
setTBRMessage.setAmount(amount);
return setTBRMessage;
} else {
ChangeTBRMessage changeTBRMessage = new ChangeTBRMessage();
changeTBRMessage.setDuration(duration);
changeTBRMessage.setAmount(amount);
return changeTBRMessage;
}
} else if (message instanceof SetTBRMessage) finish(amount);
return null;
}
}

View file

@ -1,140 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.connector;
import java.util.List;
import sugar.free.sightparser.applayer.descriptors.ActiveBolus;
import sugar.free.sightparser.applayer.descriptors.PumpStatus;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ActiveProfileBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile1Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile2Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile3Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile4Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile5Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ConfigurationBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.FactoryMinBRAmountBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.FactoryMinBolusAmountBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.MaxBRAmountBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.MaxBolusAmountBlock;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.configuration.ReadConfigurationBlockMessage;
import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
import sugar.free.sightparser.applayer.messages.status.BatteryAmountMessage;
import sugar.free.sightparser.applayer.messages.status.CartridgeAmountMessage;
import sugar.free.sightparser.applayer.messages.status.CurrentBasalMessage;
import sugar.free.sightparser.applayer.messages.status.CurrentTBRMessage;
import sugar.free.sightparser.applayer.messages.status.PumpStatusMessage;
import sugar.free.sightparser.handling.SightServiceConnector;
import sugar.free.sightparser.handling.TaskRunner;
/**
* Created by Tebbe Ubben on 12.03.2018.
*/
public class StatusTaskRunner extends TaskRunner {
private Result result = new Result();
public StatusTaskRunner(SightServiceConnector serviceConnector) {
super(serviceConnector);
}
@Override
protected AppLayerMessage run(AppLayerMessage message) throws Exception {
if (message == null) return new PumpStatusMessage();
else if (message instanceof PumpStatusMessage) {
result.pumpStatus = ((PumpStatusMessage) message).getPumpStatus();
if (result.pumpStatus == PumpStatus.STOPPED) return new BatteryAmountMessage();
else return new CurrentTBRMessage();
} else if (message instanceof CurrentTBRMessage) {
CurrentTBRMessage currentTBRMessage = (CurrentTBRMessage) message;
result.tbrAmount = currentTBRMessage.getPercentage();
result.tbrInitialDuration = currentTBRMessage.getInitialTime();
result.tbrLeftoverDuration = currentTBRMessage.getLeftoverTime();
return new ActiveBolusesMessage();
} else if (message instanceof ActiveBolusesMessage) {
ActiveBolusesMessage activeBolusesMessage = (ActiveBolusesMessage) message;
result.activeBolus1 = activeBolusesMessage.getBolus1();
result.activeBolus2 = activeBolusesMessage.getBolus2();
result.activeBolus3 = activeBolusesMessage.getBolus3();
return new CurrentBasalMessage();
} else if (message instanceof CurrentBasalMessage) {
result.baseBasalRate = ((CurrentBasalMessage) message).getCurrentBasalAmount();
return new BatteryAmountMessage();
} else if (message instanceof BatteryAmountMessage) {
result.battery = ((BatteryAmountMessage) message).getBatteryAmount();
return new CartridgeAmountMessage();
} else if (message instanceof CartridgeAmountMessage) {
result.cartridge = ((CartridgeAmountMessage) message).getCartridgeAmount();
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
readMessage.setConfigurationBlockID(ActiveProfileBlock.ID);
return readMessage;
} else if (message instanceof ReadConfigurationBlockMessage) {
ConfigurationBlock configurationBlock = ((ReadConfigurationBlockMessage) message).getConfigurationBlock();
if (configurationBlock instanceof ActiveProfileBlock) {
ActiveProfileBlock activeProfileBlock = (ActiveProfileBlock) configurationBlock;
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
switch (activeProfileBlock.getActiveProfile()) {
case BR_PROFILE_1:
readMessage.setConfigurationBlockID(BRProfile1Block.ID);
break;
case BR_PROFILE_2:
readMessage.setConfigurationBlockID(BRProfile2Block.ID);
break;
case BR_PROFILE_3:
readMessage.setConfigurationBlockID(BRProfile3Block.ID);
break;
case BR_PROFILE_4:
readMessage.setConfigurationBlockID(BRProfile4Block.ID);
break;
case BR_PROFILE_5:
readMessage.setConfigurationBlockID(BRProfile5Block.ID);
break;
}
return readMessage;
} else if (configurationBlock instanceof BRProfileBlock) {
result.basalProfile = ((BRProfileBlock) configurationBlock).getProfileBlocks();
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
readMessage.setConfigurationBlockID(MaxBolusAmountBlock.ID);
return readMessage;
} else if (configurationBlock instanceof MaxBolusAmountBlock) {
result.maximumBolusAmount = ((MaxBolusAmountBlock) configurationBlock).getMaximumAmount();
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
readMessage.setConfigurationBlockID(MaxBRAmountBlock.ID);
return readMessage;
} else if (configurationBlock instanceof MaxBRAmountBlock) {
result.maximumBasalAmount = ((MaxBRAmountBlock) configurationBlock).getMaximumAmount();
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
readMessage.setConfigurationBlockID(FactoryMinBRAmountBlock.ID);
return readMessage;
} else if (configurationBlock instanceof FactoryMinBRAmountBlock) {
result.minimumBasalAmount = ((FactoryMinBRAmountBlock) configurationBlock).getMinimumAmount();
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
readMessage.setConfigurationBlockID(FactoryMinBolusAmountBlock.ID);
return readMessage;
} else if (configurationBlock instanceof FactoryMinBolusAmountBlock) {
result.minimumBolusAmount = ((FactoryMinBolusAmountBlock) configurationBlock).getMinimumAmount();
finish(result);
}
}
return null;
}
public static class Result {
public PumpStatus pumpStatus;
public double baseBasalRate;
public int battery;
public double cartridge ;
public int tbrAmount = 100;
public int tbrInitialDuration = 0;
public int tbrLeftoverDuration = 0;
public ActiveBolus activeBolus1;
public ActiveBolus activeBolus2;
public ActiveBolus activeBolus3;
public List<BRProfileBlock.ProfileBlock> basalProfile;
public double maximumBolusAmount;
public double maximumBasalAmount;
public double minimumBolusAmount;
public double minimumBasalAmount;
}
}

View file

@ -1,72 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.connector;
import java.util.List;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ActiveProfileBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile1Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile2Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile3Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile4Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile5Block;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ConfigurationBlock;
import sugar.free.sightparser.applayer.messages.AppLayerMessage;
import sugar.free.sightparser.applayer.messages.configuration.CloseWriteSessionMessage;
import sugar.free.sightparser.applayer.messages.configuration.OpenWriteSessionMessage;
import sugar.free.sightparser.applayer.messages.configuration.ReadConfigurationBlockMessage;
import sugar.free.sightparser.applayer.messages.configuration.WriteConfigurationBlockMessage;
import sugar.free.sightparser.handling.SightServiceConnector;
import sugar.free.sightparser.handling.TaskRunner;
/**
* Created by Tebbe Ubben on 10.03.2018.
*/
public class WriteBasalProfileTaskRunner extends TaskRunner {
private List<BRProfileBlock.ProfileBlock> profileBlocks;
private BRProfileBlock profileBlock;
public WriteBasalProfileTaskRunner(SightServiceConnector serviceConnector, List<BRProfileBlock.ProfileBlock> profileBlocks) {
super(serviceConnector);
this.profileBlocks = profileBlocks;
}
@Override
protected AppLayerMessage run(AppLayerMessage message) throws Exception {
if (message == null) {
ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
readMessage.setConfigurationBlockID(ActiveProfileBlock.ID);
return readMessage;
} else if (message instanceof ReadConfigurationBlockMessage) {
ConfigurationBlock configurationBlock = ((ReadConfigurationBlockMessage) message).getConfigurationBlock();
ActiveProfileBlock activeProfileBlock = (ActiveProfileBlock) configurationBlock;
switch (activeProfileBlock.getActiveProfile()) {
case BR_PROFILE_1:
profileBlock = new BRProfile1Block();
break;
case BR_PROFILE_2:
profileBlock = new BRProfile2Block();
break;
case BR_PROFILE_3:
profileBlock = new BRProfile3Block();
break;
case BR_PROFILE_4:
profileBlock = new BRProfile4Block();
break;
case BR_PROFILE_5:
profileBlock = new BRProfile5Block();
break;
}
profileBlock.setProfileBlocks(profileBlocks);
return new OpenWriteSessionMessage();
} else if (message instanceof OpenWriteSessionMessage) {
WriteConfigurationBlockMessage writeMessage = new WriteConfigurationBlockMessage();
writeMessage.setConfigurationBlock(profileBlock);
return writeMessage;
} else if (message instanceof WriteConfigurationBlockMessage) {
return new CloseWriteSessionMessage();
} else if (message instanceof CloseWriteSessionMessage) finish(null);
return null;
}
}

View file

@ -1,26 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.events;
import java.util.UUID;
import info.nightscout.androidaps.events.Event;
/**
* Created by jamorham on 23/01/2018.
*/
public class EventInsightCallback extends Event {
public UUID request_uuid;
public boolean success = false;
public String message = null;
public Object response_object = null;
public EventInsightCallback() {
request_uuid = UUID.randomUUID();
}
@Override
public String toString() {
return "Event: " + request_uuid + " success: " + success + " msg: " + message + " Object: " + response_object;
}
}

View file

@ -1,9 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.events;
import info.nightscout.androidaps.events.EventUpdateGui;
/**
* Created by jamorham on 23/01/2018.
*/
public class EventInsightUpdateGui extends EventUpdateGui {
}

View file

@ -1,243 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.history;
import android.content.Intent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.DateUtil;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SP;
import org.json.JSONException;
import org.json.JSONObject;
import sugar.free.sightparser.handling.HistoryBroadcast;
import java.util.Date;
import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache.updatePumpSerialNumber;
/**
* Created by jamorham on 27/01/2018.
* <p>
* Parse inbound logbook intents
*/
class HistoryIntentAdapter {
private Logger log = LoggerFactory.getLogger(L.PUMP);
private HistoryLogAdapter logAdapter = new HistoryLogAdapter();
private static long getDateExtra(Intent intent, String name) {
return ((Date) intent.getSerializableExtra(name)).getTime();
}
static long getRecordUniqueID(long pump_serial_number, long pump_record_id) {
updatePumpSerialNumber(pump_serial_number);
return (pump_serial_number * 10000000) + pump_record_id;
}
void processTBRIntent(Intent intent) {
final int pump_tbr_duration = intent.getIntExtra(HistoryBroadcast.EXTRA_DURATION, -1);
final int pump_tbr_percent = intent.getIntExtra(HistoryBroadcast.EXTRA_TBR_AMOUNT, -1);
long pump_record_id = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
if (pump_record_id == -1) {
pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
}
final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
final long start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
if ((pump_tbr_duration == -1) || (pump_tbr_percent == -1) || (pump_record_id == -1)) {
log.error("Invalid TBR record!!!");
return;
}
final long record_unique_id = getRecordUniqueID(pump_serial_number, pump_record_id);
if (L.isEnabled(L.PUMP))
log.debug("Creating TBR record: " + pump_tbr_percent + "% " + pump_tbr_duration + "m" + " id:" + record_unique_id);
logAdapter.createTBRrecord(start_time, pump_tbr_percent, pump_tbr_duration, record_unique_id);
}
void processDeliveredBolusIntent(Intent intent) {
final String bolus_type = intent.getStringExtra(HistoryBroadcast.EXTRA_BOLUS_TYPE);
final int bolus_id = intent.getIntExtra(HistoryBroadcast.EXTRA_BOLUS_ID, -1);
long pump_record_id = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
if (pump_record_id == -1) {
pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
}
final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
final long event_time = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
final long start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
final double immediate_amount = intent.getDoubleExtra(HistoryBroadcast.EXTRA_IMMEDIATE_AMOUNT, -1);
final double extended_insulin = intent.getDoubleExtra(HistoryBroadcast.EXTRA_EXTENDED_AMOUNT, -1);
final int extended_minutes = intent.getIntExtra(HistoryBroadcast.EXTRA_DURATION, -1);
final long record_unique_id = getRecordUniqueID(pump_serial_number, bolus_id > -1 ? bolus_id : pump_record_id);
switch (bolus_type) {
case "STANDARD":
if (immediate_amount == -1) {
log.error("ERROR Standard bolus fails sanity check");
return;
}
LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U ", event_time);
logAdapter.createStandardBolusRecord(start_time, immediate_amount, record_unique_id);
break;
case "EXTENDED":
if ((extended_insulin == -1) || (extended_minutes == -1)) {
log.error("ERROR: Extended bolus fails sanity check");
return;
}
LiveHistory.setStatus(bolus_type + " BOLUS\n" + extended_insulin + "U over " + extended_minutes + " min, ", event_time);
logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
break;
case "MULTIWAVE":
if ((immediate_amount == -1) || (extended_insulin == -1) || (extended_minutes == -1)) {
log.error("ERROR: Multiwave bolus fails sanity check");
return;
}
LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U + " + extended_insulin + "U over " + extended_minutes + " min, ", event_time);
logAdapter.createStandardBolusRecord(start_time, immediate_amount, pump_serial_number + pump_record_id);
logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
break;
default:
log.error("ERROR, UNKNWON BOLUS TYPE: " + bolus_type);
}
}
void processDailyTotalIntent(Intent intent) {
long date = getDateExtra(intent, HistoryBroadcast.EXTRA_TOTAL_DATE);
double basal = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BASAL_TOTAL, 0D);
double bolus = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BOLUS_TOTAL, 0D);
TDD tdd = new TDD(date, bolus, basal, bolus + basal);
MainApp.getDbHelper().createOrUpdateTDD(tdd);
}
void processCannulaFilledIntent(Intent intent) {
long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
uploadCareportalEvent(date, CareportalEvent.SITECHANGE);
}
void processCartridgeInsertedIntent(Intent intent) {
long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
uploadCareportalEvent(date, CareportalEvent.INSULINCHANGE);
}
void processBatteryInsertedIntent(Intent intent) {
long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
uploadCareportalEvent(date, CareportalEvent.PUMPBATTERYCHANGE);
}
private void uploadCareportalEvent(long date, String event) {
if (SP.getBoolean("insight_automatic_careportal_events", false)) {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
return;
try {
JSONObject data = new JSONObject();
String enteredBy = SP.getString("careportal_enteredby", "");
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", event);
NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
void processOccurenceOfAlertIntent(Intent intent) {
if (SP.getBoolean("insight_automatic_careportal_events", false)) {
long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
String alertType = intent.getStringExtra(HistoryBroadcast.EXTRA_ALERT_TYPE);
int alertText = getAlertText(alertType);
if (alertText == 0) return;
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
return;
logNote(date, MainApp.gs(alertText));
}
}
void processPumpStatusChangedIntent(Intent intent) {
long newStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
if (SP.getBoolean("insight_automatic_careportal_events", false)) {
String newStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_NEW_STATUS);
switch (newStatus) {
case "STARTED":
logNote(newStatusTime, MainApp.gs(R.string.pump_started));
break;
case "STOPPED":
logNote(newStatusTime, MainApp.gs(R.string.pump_stopped));
break;
case "PAUSED":
logNote(newStatusTime, MainApp.gs(R.string.pump_paused));
break;
}
}
if (intent.hasExtra(HistoryBroadcast.EXTRA_OLD_STATUS_TIME)) {
String oldStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_OLD_STATUS);
if (oldStatus.equals("STOPPED")) {
long oldStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_OLD_STATUS_TIME);
int duration = (int) ((newStatusTime - oldStatusTime) / 60000);
long serialNumber = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
long recordId = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
long uniqueRecordId = getRecordUniqueID(serialNumber, recordId);
logAdapter.createTBRrecord(oldStatusTime, 0, duration, uniqueRecordId);
}
}
}
private void logNote(long date, String note) {
try {
if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
return;
JSONObject data = new JSONObject();
String enteredBy = SP.getString("careportal_enteredby", "");
if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
data.put("created_at", DateUtil.toISOString(date));
data.put("eventType", CareportalEvent.NOTE);
data.put("notes", note);
NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
private int getAlertText(String type) {
if (type.equals("Error6MechanicalError")) return R.string.alert_e6;
if (type.equals("Error7ElectronicError")) return R.string.alert_e7;
if (type.equals("Error10RewindError")) return R.string.alert_e10;
if (type.equals("Error13LanguageError")) return R.string.alert_e13;
if (type.equals("Maintenance20CartridgeNotInserted")) return R.string.alert_m20;
if (type.equals("Maintenance21CartridgeEmpty")) return R.string.alert_m21;
if (type.equals("Maintenance22BatteryEmpty")) return R.string.alert_m22;
if (type.equals("Maintenance23AutomaticOff")) return R.string.alert_m23;
if (type.equals("Maintenance24Occlusion")) return R.string.alert_m24;
if (type.equals("Maintenance25LoantimeOver")) return R.string.alert_m25;
if (type.equals("Maintenance26CartridgeChangeNotCompleted")) return R.string.alert_m26;
if (type.equals("Maintenance27DataDownloadFailed")) return R.string.alert_m27;
if (type.equals("Maintenance28PauseModeTimeout")) return R.string.alert_m28;
if (type.equals("Maintenance29BatteryTypeNotSet")) return R.string.alert_m29;
if (type.equals("Maintenance30CartridgeTypeNotSet")) return R.string.alert_m30;
if (type.equals("Warning31CartridgeLow")) return R.string.alert_w31;
if (type.equals("Warning32BatteryLow")) return R.string.alert_w32;
if (type.equals("Warning33InvalidDateTime")) return R.string.alert_w33;
if (type.equals("Warning34EndOfWarranty")) return R.string.alert_w34;
if (type.equals("Warning36TBRCancelled")) return 0;
if (type.equals("Warning38BolusCancelled")) return 0;
if (type.equals("Warning39LoantimeWarning")) return R.string.alert_w39;
return 0;
}
}

View file

@ -1,136 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.history;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.T;
/**
* Created by jamorham on 27/01/2018.
* <p>
* Write to the History Log
*/
class HistoryLogAdapter {
private Logger log = LoggerFactory.getLogger(L.PUMP);
private static final long MAX_TIME_DIFFERENCE = T.secs(61).msecs();
void createTBRrecord(long eventDate, int percent, int duration, long record_id) {
TemporaryBasal temporaryBasal = new TemporaryBasal().date(eventDate);
final TemporaryBasal temporaryBasalFromHistory = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(eventDate);
if (temporaryBasalFromHistory == null) {
if (L.isEnabled(L.PUMP))
log.debug("Create new TBR: " + eventDate + " " + percent + " " + duration);
} else {
if (L.isEnabled(L.PUMP))
log.debug("Loaded existing TBR record: " + temporaryBasalFromHistory.toString());
if (Math.abs(eventDate - temporaryBasalFromHistory.date) < MAX_TIME_DIFFERENCE) {
if (temporaryBasalFromHistory.source != Source.PUMP) {
if (temporaryBasalFromHistory.percentRate == percent) {
if (L.isEnabled(L.PUMP))
log.debug("Things seem to match: %" + percent);
temporaryBasal = temporaryBasalFromHistory;
String _id = temporaryBasal._id;
if (NSUpload.isIdValid(_id)) {
NSUpload.removeCareportalEntryFromNS(_id);
} else {
UploadQueue.removeID("dbAdd", _id);
}
MainApp.getDbHelper().delete(temporaryBasalFromHistory);
} else {
if (L.isEnabled(L.PUMP))
log.debug("This record has different percent rates: " + temporaryBasalFromHistory.percentRate + " vs us: " + percent);
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("This record is already a pump record!");
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("Time difference too big! : " + (eventDate - temporaryBasalFromHistory.date));
}
}
temporaryBasal.source(Source.PUMP)
.pumpId(record_id)
.percent(percent)
.duration(duration);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
}
void createExtendedBolusRecord(long eventDate, double insulin, int durationInMinutes, long record_id) {
final ExtendedBolus extendedBolusFromHistory = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(eventDate);
if (extendedBolusFromHistory == null) {
if (L.isEnabled(L.PUMP))
log.debug("Create new EB: " + eventDate + " " + insulin + " " + durationInMinutes);
} else {
if (L.isEnabled(L.PUMP))
log.debug("Loaded existing EB record: " + extendedBolusFromHistory.log());
if (Math.abs(eventDate - extendedBolusFromHistory.date) < MAX_TIME_DIFFERENCE) {
if (extendedBolusFromHistory.source != Source.PUMP) {
if (L.isEnabled(L.PUMP))
log.debug("Date seem to match: " + DateUtil.dateAndTimeFullString(eventDate));
String _id = extendedBolusFromHistory._id;
if (NSUpload.isIdValid(_id)) {
NSUpload.removeCareportalEntryFromNS(_id);
} else {
UploadQueue.removeID("dbAdd", _id);
}
MainApp.getDbHelper().delete(extendedBolusFromHistory);
} else {
if (L.isEnabled(L.PUMP))
log.debug("This record is already a pump record!");
}
} else {
if (L.isEnabled(L.PUMP))
log.debug("Time difference too big! : " + (eventDate - extendedBolusFromHistory.date));
}
}
// TODO trap items below minimum period
// TODO (mike) find and remove ending record with Source.USER
ExtendedBolus extendedBolus = new ExtendedBolus()
.date(eventDate)
.insulin(insulin)
.durationInMinutes(durationInMinutes)
.source(Source.PUMP)
.pumpId(record_id);
if (ProfileFunctions.getInstance().getProfile(extendedBolus.date) != null) // actual basal rate is needed for absolute rate calculation
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
}
void createStandardBolusRecord(long eventDate, double insulin, long record_id) {
//DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(eventDate.getTime());
// TODO do we need to do the same delete + insert that we are doing for temporary basals here too?
final DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.date = eventDate;
detailedBolusInfo.source = Source.PUMP;
detailedBolusInfo.pumpId = record_id;
detailedBolusInfo.insulin = insulin;
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
}
}

View file

@ -1,134 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.history;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import static info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver.Status.BUSY;
import static info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver.Status.SYNCED;
import static info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver.Status.SYNCING;
import static sugar.free.sightparser.handling.HistoryBroadcast.*;
/**
* Created by jamorham on 27/01/2018.
*/
public class HistoryReceiver {
private static BroadcastReceiver historyReceiver;
private volatile static Status status = Status.IDLE;
private volatile HistoryIntentAdapter intentAdapter;
public HistoryReceiver() {
initializeHistoryReceiver();
}
public static synchronized void registerHistoryReceiver() {
try {
MainApp.instance().unregisterReceiver(historyReceiver);
} catch (Exception e) {
//
}
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_PUMP_STATUS_CHANGED);
filter.addAction(ACTION_BOLUS_PROGRAMMED);
filter.addAction(ACTION_BOLUS_DELIVERED);
filter.addAction(ACTION_END_OF_TBR);
filter.addAction(ACTION_DAILY_TOTAL);
filter.addAction(ACTION_SYNC_STARTED);
filter.addAction(ACTION_STILL_SYNCING);
filter.addAction(ACTION_SYNC_FINISHED);
filter.addAction(ACTION_CANNULA_FILLED);
filter.addAction(ACTION_CARTRIDGE_INSERTED);
filter.addAction(ACTION_BATTERY_INSERTED);
filter.addAction(ACTION_OCCURENCE_OF_ALERT);
filter.addAction(ACTION_PUMP_STATUS_CHANGED);
MainApp.instance().registerReceiver(historyReceiver, filter);
}
// History
public static String getStatusString() {
return status.toString();
}
private synchronized void initializeHistoryReceiver() {
historyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, final Intent intent) {
final String action = intent.getAction();
if (action == null) return;
if (intentAdapter == null) {
synchronized (this) {
if (intentAdapter == null) {
intentAdapter = new HistoryIntentAdapter();
}
}
}
switch (action) {
case ACTION_SYNC_STARTED:
status = SYNCING;
break;
case ACTION_STILL_SYNCING:
status = BUSY;
break;
case ACTION_SYNC_FINISHED:
status = SYNCED;
break;
case ACTION_BOLUS_DELIVERED:
intentAdapter.processDeliveredBolusIntent(intent);
break;
case ACTION_END_OF_TBR:
intentAdapter.processTBRIntent(intent);
break;
case ACTION_DAILY_TOTAL:
intentAdapter.processDailyTotalIntent(intent);
break;
case ACTION_CANNULA_FILLED:
intentAdapter.processCannulaFilledIntent(intent);
break;
case ACTION_CARTRIDGE_INSERTED:
intentAdapter.processCartridgeInsertedIntent(intent);
break;
case ACTION_BATTERY_INSERTED:
intentAdapter.processBatteryInsertedIntent(intent);
break;
case ACTION_OCCURENCE_OF_ALERT:
intentAdapter.processOccurenceOfAlertIntent(intent);
break;
case ACTION_PUMP_STATUS_CHANGED:
intentAdapter.processPumpStatusChangedIntent(intent);
break;
}
}
};
}
enum Status {
IDLE(R.string.insight_history_idle),
SYNCING(R.string.insight_history_syncing),
BUSY(R.string.insight_history_busy),
SYNCED(R.string.insight_history_synced);
private final int string_id;
Status(int string_id) {
this.string_id = string_id;
}
@Override
public String toString() {
return MainApp.gs(string_id);
}
}
}

View file

@ -1,33 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.history;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers;
/**
* Created by jamorham on 27/01/2018.
*
* In memory status storage class
*/
public class LiveHistory {
private static String status = "";
private static long status_time = -1;
public static String getStatus() {
if (status.equals("")) return status;
return status + " " + Helpers.niceTimeScalar(Helpers.msSince(status_time)) + " " + MainApp.gs(R.string.ago);
}
public static long getStatusTime() {
return status_time;
}
static void setStatus(String mystatus, long eventtime) {
if (eventtime > status_time) {
status_time = eventtime;
status = mystatus;
}
}
}

View file

@ -1,35 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.history;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
import info.nightscout.utils.SP;
/**
* Created by jamorham on 01/02/2018.
*/
public class PumpIdCache {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
private static final String INSIGHT_PUMP_ID_PREF = "insight-pump-id";
private static long cachedPumpSerialNumber = -1;
static void updatePumpSerialNumber(long pump_serial_number) {
if (pump_serial_number != cachedPumpSerialNumber) {
cachedPumpSerialNumber = pump_serial_number;
if (L.isEnabled(L.PUMP))
log.debug("Updating pump serial number: " + pump_serial_number);
SP.putLong(INSIGHT_PUMP_ID_PREF, cachedPumpSerialNumber);
}
}
public static long getRecordUniqueID(long record_id) {
if (cachedPumpSerialNumber == -1) {
cachedPumpSerialNumber = SP.getLong(INSIGHT_PUMP_ID_PREF, 0L);
}
return HistoryIntentAdapter.getRecordUniqueID(cachedPumpSerialNumber, record_id);
}
}

View file

@ -1,197 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.PowerManager;
import android.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
/**
* Created by jamorham on 24/01/2018.
* <p>
* Useful utility methods from xDrip+
*/
public class Helpers {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
private static final Map<String, Long> rateLimits = new HashMap<>();
// singletons to avoid repeated allocation
private static DecimalFormatSymbols dfs;
private static DecimalFormat df;
// return true if below rate limit
public static synchronized boolean ratelimit(String name, int seconds) {
// check if over limit
if ((rateLimits.containsKey(name)) && (tsl() - rateLimits.get(name) < (seconds * 1000))) {
if (L.isEnabled(L.PUMP))
log.debug(name + " rate limited: " + seconds + " seconds");
return false;
}
// not over limit
rateLimits.put(name, tsl());
return true;
}
public static long tsl() {
return System.currentTimeMillis();
}
public static long msSince(long when) {
return (tsl() - when);
}
public static long msTill(long when) {
return (when - tsl());
}
public static boolean checkPackageExists(Context context, String TAG, String packageName) {
try {
final PackageManager pm = context.getPackageManager();
final PackageInfo pi = pm.getPackageInfo(packageName, 0);
return pi.packageName.equals(packageName);
} catch (PackageManager.NameNotFoundException e) {
return false;
} catch (Exception e) {
log.error("Exception trying to determine packages! " + e);
return false;
}
}
public static boolean runOnUiThreadDelayed(Runnable theRunnable, long delay) {
return new Handler(MainApp.instance().getMainLooper()).postDelayed(theRunnable, delay);
}
public static PowerManager.WakeLock getWakeLock(final String name, int millis) {
final PowerManager pm = (PowerManager) MainApp.instance().getSystemService(Context.POWER_SERVICE);
if (pm == null) return null;
final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name);
wl.acquire(millis);
return wl;
}
public static void releaseWakeLock(PowerManager.WakeLock wl) {
if (wl == null) return;
if (wl.isHeld()) wl.release();
}
public static String niceTimeSince(long t) {
return niceTimeScalar(msSince(t));
}
public static String niceTimeTill(long t) {
return niceTimeScalar(-msSince(t));
}
public static String niceTimeScalar(long t) {
String unit = MainApp.gs(R.string.second);
t = t / 1000;
if (t > 59) {
unit = MainApp.gs(R.string.minute);
t = t / 60;
if (t > 59) {
unit = MainApp.gs(R.string.hour);
t = t / 60;
if (t > 24) {
unit = MainApp.gs(R.string.day);
t = t / 24;
if (t > 28) {
unit = MainApp.gs(R.string.week);
t = t / 7;
}
}
}
}
if (t != 1) unit = unit + MainApp.gs(R.string.time_plural);
return qs((double) t, 0) + " " + unit;
}
public static String qs(double x, int digits) {
if (digits == -1) {
digits = 0;
if (((int) x != x)) {
digits++;
if ((((int) x * 10) / 10 != x)) {
digits++;
if ((((int) x * 100) / 100 != x)) digits++;
}
}
}
if (dfs == null) {
final DecimalFormatSymbols local_dfs = new DecimalFormatSymbols();
local_dfs.setDecimalSeparator('.');
dfs = local_dfs; // avoid race condition
}
final DecimalFormat this_df;
// use singleton if on ui thread otherwise allocate new as DecimalFormat is not thread safe
if (Thread.currentThread().getId() == 1) {
if (df == null) {
final DecimalFormat local_df = new DecimalFormat("#", dfs);
local_df.setMinimumIntegerDigits(1);
df = local_df; // avoid race condition
}
this_df = df;
} else {
this_df = new DecimalFormat("#", dfs);
}
this_df.setMaximumFractionDigits(digits);
return this_df.format(x);
}
public static String niceTimeScalarRedux(long t) {
return niceTimeScalar(t).replaceFirst("^1 ", "");
}
public static String niceTimeScalarBrief(long t) {
// TODO i18n wont work for non-latin characterset
return niceTimeScalar(t).replaceFirst("([a-z])[a-z]*", "$1").replace(" ", "");
}
public static String hourMinuteString(long timestamp) {
return android.text.format.DateFormat.format("kk:mm", timestamp).toString();
}
public static String hourMinuteSecondString(long timestamp) {
return android.text.format.DateFormat.format("kk:mm:ss", timestamp).toString();
}
public static String dateTimeText(long timestamp) {
return android.text.format.DateFormat.format("yyyy-MM-dd kk:mm:ss", timestamp).toString();
}
public static String dateText(long timestamp) {
return android.text.format.DateFormat.format("yyyy-MM-dd", timestamp).toString();
}
public static String capitalize(String text) {
return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
}
public static double roundDouble(double value, int places) {
if (places < 0) throw new IllegalArgumentException("Invalid decimal places");
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}

View file

@ -1,64 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.utils;
/**
* Created by jamorham on 26/01/2018.
*
* For representing row status items
*/
public class StatusItem {
public enum Highlight {
NORMAL,
GOOD,
BAD,
NOTICE,
CRITICAL
}
public String name;
public String value;
public Highlight highlight;
public String button_name;
public Runnable runnable;
public StatusItem(String name, String value) {
this(name, value, Highlight.NORMAL);
}
public StatusItem() {
this("line-break", "", Highlight.NORMAL);
}
public StatusItem(String name, Highlight highlight) {
this("heading-break", name, highlight);
}
public StatusItem(String name, Runnable runnable) {
this("button-break", "", Highlight.NORMAL, name, runnable);
}
public StatusItem(String name, String value, Highlight highlight) {
this(name, value, highlight, null, null);
}
public StatusItem(String name, String value, Highlight highlight, String button_name, Runnable runnable) {
this.name = name;
this.value = value;
this.highlight = highlight;
this.button_name = button_name;
this.runnable = runnable;
}
public StatusItem(String name, Integer value) {
this(name, value, Highlight.NORMAL);
}
public StatusItem(String name, Integer value, Highlight highlight) {
this.name = name;
this.value = Integer.toString(value);
this.highlight = highlight;
}
}

View file

@ -1,85 +0,0 @@
package info.nightscout.androidaps.plugins.PumpInsight.utils.ui;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
/**
* Created by jamorham on 26/01/2018.
*
* Convert StatusItem to View
*/
public class StatusItemViewAdapter {
private final Activity activity;
private final ViewGroup holder;
public StatusItemViewAdapter(Activity activity, ViewGroup holder) {
this.activity = activity;
this.holder = holder;
}
public View inflateStatus(StatusItem statusItem) {
if (activity == null) return null;
final View child = activity.getLayoutInflater().inflate(R.layout.insightpump_statuselements, null);
final TextView name = (TextView) child.findViewById(R.id.insightstatuslabel);
final TextView value = (TextView)child.findViewById(R.id.insightstatusvalue);
final TextView spacer = (TextView)child.findViewById(R.id.insightstatusspacer);
final LinearLayout layout = (LinearLayout)child.findViewById(R.id.insightstatuslayout);
if (statusItem.name.equals("line-break")) {
spacer.setVisibility(View.GONE);
name.setVisibility(View.GONE);
value.setVisibility(View.GONE);
layout.setPadding(10, 10, 10, 10);
} else if (statusItem.name.equals("heading-break")) {
value.setVisibility(View.GONE);
spacer.setVisibility(View.GONE);
name.setText(statusItem.value);
name.setGravity(Gravity.CENTER_HORIZONTAL);
name.setTextColor(Color.parseColor("#fff9c4"));
} else {
name.setText(statusItem.name);
value.setText(statusItem.value);
}
final int this_color = getHighlightColor(statusItem);
name.setBackgroundColor(this_color);
value.setBackgroundColor(this_color);
spacer.setBackgroundColor(this_color);
if (this_color != Color.TRANSPARENT) {
name.setTextColor(Color.WHITE);
spacer.setTextColor(Color.WHITE);
}
if (holder != null) {
holder.addView(child);
}
return child;
}
private static int getHighlightColor(StatusItem row) {
switch (row.highlight) {
case BAD:
return Color.parseColor("#480000");
case NOTICE:
return Color.parseColor("#403000");
case GOOD:
return Color.parseColor("#003000");
case CRITICAL:
return Color.parseColor("#770000");
default:
return Color.TRANSPARENT;
}
}
}

View file

@ -1,92 +0,0 @@
package info.nightscout.androidaps.plugins.SmsCommunicator;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Comparator;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui;
import info.nightscout.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy;
/**
* A simple {@link Fragment} subclass.
*/
public class SmsCommunicatorFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(SmsCommunicatorFragment.class);
TextView logView;
public SmsCommunicatorFragment() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false);
logView = (TextView) view.findViewById(R.id.smscommunicator_log);
updateGUI();
return view;
} catch (Exception e) {
FabricPrivacy.logException(e);
}
return null;
}
@Subscribe
public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) {
updateGUI();
}
@Override
protected void updateGUI() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
class CustomComparator implements Comparator<SmsCommunicatorPlugin.Sms> {
public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) {
return (int) (object1.date - object2.date);
}
}
Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator());
int messagesToShow = 40;
int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow);
String logText = "";
for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) {
SmsCommunicatorPlugin.Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x);
if (sms.received) {
logText += DateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + (sms.processed ? "" : "") + sms.phoneNumber + " <b>" + sms.text + "</b><br>";
} else if (sms.sent) {
logText += DateUtil.timeString(sms.date) + " &gt;&gt;&gt; " + (sms.processed ? "" : "") + sms.phoneNumber + " <b>" + sms.text + "</b><br>";
}
}
logView.setText(Html.fromHtml(logText));
}
});
}
}

View file

@ -1,606 +0,0 @@
package info.nightscout.androidaps.plugins.SmsCommunicator;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.SystemClock;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
import info.nightscout.androidaps.services.Intents;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.DecimalFormatter;
import info.nightscout.utils.FabricPrivacy;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SP;
import info.nightscout.utils.SafeParse;
import info.nightscout.utils.T;
import info.nightscout.utils.XdripCalibrations;
/**
* Created by mike on 05.08.2016.
*/
public class SmsCommunicatorPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(SmsCommunicatorPlugin.class);
private static SmsCommunicatorPlugin smsCommunicatorPlugin;
public static SmsCommunicatorPlugin getPlugin() {
if (smsCommunicatorPlugin == null) {
smsCommunicatorPlugin = new SmsCommunicatorPlugin();
}
return smsCommunicatorPlugin;
}
private List<String> allowedNumbers = new ArrayList<>();
class Sms {
String phoneNumber;
String text;
long date;
boolean received = false;
boolean sent = false;
boolean processed = false;
String confirmCode;
double bolusRequested = 0d;
double tempBasal = 0d;
double calibrationRequested = 0d;
int duration = 0;
Sms(SmsMessage message) {
phoneNumber = message.getOriginatingAddress();
text = message.getMessageBody();
date = message.getTimestampMillis();
received = true;
}
Sms(String phoneNumber, String text, long date) {
this.phoneNumber = phoneNumber;
this.text = text;
this.date = date;
sent = true;
}
Sms(String phoneNumber, String text, long date, String confirmCode) {
this.phoneNumber = phoneNumber;
this.text = text;
this.date = date;
this.confirmCode = confirmCode;
sent = true;
}
public String toString() {
return "SMS from " + phoneNumber + ": " + text;
}
}
private Sms cancelTempBasalWaitingForConfirmation = null;
private Sms tempBasalWaitingForConfirmation = null;
private Sms bolusWaitingForConfirmation = null;
private Sms calibrationWaitingForConfirmation = null;
private Sms suspendWaitingForConfirmation = null;
private Date lastRemoteBolusTime = new Date(0);
ArrayList<Sms> messages = new ArrayList<>();
private SmsCommunicatorPlugin() {
super(new PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(SmsCommunicatorFragment.class.getName())
.pluginName(R.string.smscommunicator)
.shortName(R.string.smscommunicator_shortname)
.preferencesId(R.xml.pref_smscommunicator)
.description(R.string.description_sms_communicator)
);
processSettings(null);
}
@Override
protected void onStart() {
MainApp.bus().register(this);
super.onStart();
}
@Override
protected void onStop() {
MainApp.bus().unregister(this);
}
@Subscribe
public void processSettings(final EventPreferenceChange ev) {
if (ev == null || ev.isChanged(R.string.key_smscommunicator_allowednumbers)) {
String settings = SP.getString(R.string.key_smscommunicator_allowednumbers, "");
String pattern = ";";
String[] substrings = settings.split(pattern);
for (String number : substrings) {
String cleaned = number.replaceAll("\\s+", "");
allowedNumbers.add(cleaned);
log.debug("Found allowed number: " + cleaned);
}
}
}
private boolean isAllowedNumber(String number) {
for (String num : allowedNumbers) {
if (num.equals(number)) return true;
}
return false;
}
public void handleNewData(Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle == null) return;
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null) {
// For every SMS message received
for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
processSms(new Sms(message));
}
}
}
private void processSms(final Sms receivedSms) {
if (!isEnabled(PluginType.GENERAL)) {
log.debug("Ignoring SMS. Plugin disabled.");
return;
}
if (!isAllowedNumber(receivedSms.phoneNumber)) {
log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed");
return;
}
String reply = "";
messages.add(receivedSms);
log.debug(receivedSms.toString());
String[] splited = receivedSms.text.split("\\s+");
Double amount;
Double tempBasal;
int duration = 0;
String passCode;
boolean remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false);
if (splited.length > 0) {
switch (splited[0].toUpperCase()) {
case "BG":
BgReading actualBG = DatabaseHelper.actualBg();
BgReading lastBG = DatabaseHelper.lastBg();
String units = ProfileFunctions.getInstance().getProfileUnits();
if (actualBG != null) {
reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", ";
} else if (lastBG != null) {
Long agoMsec = System.currentTimeMillis() - lastBG.date;
int agoMin = (int) (agoMsec / 60d / 1000d);
reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", ";
}
GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
if (glucoseStatus != null)
reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", ";
TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round();
TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round();
reply += MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bg"));
break;
case "LOOP":
if (splited.length > 1)
switch (splited[1].toUpperCase()) {
case "DISABLE":
case "STOP":
LoopPlugin loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
if (loopPlugin != null && loopPlugin.isEnabled(PluginType.LOOP)) {
loopPlugin.setPluginEnabled(PluginType.LOOP, false);
ConfigBuilderPlugin.getPlugin().storeSettings("SMS_LOOP_STOP");
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP"));
String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
});
}
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Stop"));
break;
case "ENABLE":
case "START":
loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) {
loopPlugin.setPluginEnabled(PluginType.LOOP, true);
ConfigBuilderPlugin.getPlugin().storeSettings("SMS_LOOP_START");
reply = MainApp.gs(R.string.smscommunicator_loophasbeenenabled);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START"));
}
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Start"));
break;
case "STATUS":
loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
if (loopPlugin != null) {
if (loopPlugin.isEnabled(PluginType.LOOP)) {
if (loopPlugin.isSuspended())
reply = String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend());
else
reply = MainApp.gs(R.string.smscommunicator_loopisenabled);
} else {
reply = MainApp.gs(R.string.smscommunicator_loopisdisabled);
}
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Status"));
break;
case "RESUME":
LoopPlugin.getPlugin().suspendTo(0);
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME"));
NSUpload.uploadOpenAPSOffline(0);
reply = MainApp.gs(R.string.smscommunicator_loopresumed);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Resume"));
break;
case "SUSPEND":
if (splited.length >= 3)
duration = SafeParse.stringToInt(splited[2]);
duration = Math.max(0, duration);
duration = Math.min(180, duration);
if (duration == 0) {
reply = MainApp.gs(R.string.smscommunicator_wrongduration);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else if (remoteCommandsAllowed) {
passCode = generatePasscode();
reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode);
receivedSms.processed = true;
resetWaitingMessages();
sendSMS(suspendWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
suspendWaitingForConfirmation.duration = duration;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Suspend"));
} else {
reply = MainApp.gs(R.string.smscommunicator_remotecommandnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
break;
}
break;
case "TREATMENTS":
if (splited.length > 1)
switch (splited[1].toUpperCase()) {
case "REFRESH":
Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
TreatmentsPlugin.getPlugin().getService().resetTreatments();
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0);
reply = "TERATMENTS REFRESH " + q.size() + " receivers";
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Treatments_Refresh"));
break;
}
break;
case "NSCLIENT":
if (splited.length > 1)
switch (splited[1].toUpperCase()) {
case "RESTART":
Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
List<ResolveInfo> q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0);
reply = "NSCLIENT RESTART " + q.size() + " receivers";
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Nsclient_Restart"));
break;
}
break;
case "PUMP":
case "DANAR":
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() {
@Override
public void run() {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (result.success) {
if (pump != null) {
String reply = pump.shortStatus(true);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
} else {
String reply = MainApp.gs(R.string.readstatusfailed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
});
receivedSms.processed = true;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Pump"));
break;
case "BASAL":
if (splited.length > 1) {
if (splited[1].toUpperCase().equals("CANCEL") || splited[1].toUpperCase().equals("STOP")) {
if (remoteCommandsAllowed) {
passCode = generatePasscode();
reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode);
receivedSms.processed = true;
resetWaitingMessages();
sendSMS(cancelTempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal"));
} else {
reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
} else {
tempBasal = SafeParse.stringToDouble(splited[1]);
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) {
reply = MainApp.gs(R.string.noprofile);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else {
tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value();
if (remoteCommandsAllowed) {
passCode = generatePasscode();
reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, passCode);
receivedSms.processed = true;
resetWaitingMessages();
sendSMS(tempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
tempBasalWaitingForConfirmation.tempBasal = tempBasal;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal"));
} else {
reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
}
}
break;
case "BOLUS":
if (System.currentTimeMillis() - lastRemoteBolusTime.getTime() < Constants.remoteBolusMinDistance) {
reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended()) {
reply = MainApp.gs(R.string.pumpsuspended);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else if (splited.length > 1) {
amount = SafeParse.stringToDouble(splited[1]);
amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value();
if (amount > 0d && remoteCommandsAllowed) {
passCode = generatePasscode();
reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), amount, passCode);
receivedSms.processed = true;
resetWaitingMessages();
sendSMS(bolusWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
bolusWaitingForConfirmation.bolusRequested = amount;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bolus"));
} else {
reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
break;
case "CAL":
if (splited.length > 1) {
amount = SafeParse.stringToDouble(splited[1]);
if (amount > 0d && remoteCommandsAllowed) {
passCode = generatePasscode();
reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), amount, passCode);
receivedSms.processed = true;
resetWaitingMessages();
sendSMS(calibrationWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
calibrationWaitingForConfirmation.calibrationRequested = amount;
FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Cal"));
} else {
reply = MainApp.gs(R.string.smscommunicator_remotecalibrationnotallowed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
break;
default: // expect passCode here
if (bolusWaitingForConfirmation != null && !bolusWaitingForConfirmation.processed &&
bolusWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - bolusWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
bolusWaitingForConfirmation.processed = true;
DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
detailedBolusInfo.insulin = bolusWaitingForConfirmation.bolusRequested;
detailedBolusInfo.source = Source.USER;
ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() {
@Override
public void run() {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (result.success) {
SystemClock.sleep(T.secs(15).msecs()); // wait some time to get history
String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), result.bolusDelivered);
if (pump != null)
reply += "\n" + pump.shortStatus(true);
lastRemoteBolusTime = new Date();
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else {
SystemClock.sleep(T.secs(60).msecs()); // wait some time to get history
String reply = MainApp.gs(R.string.smscommunicator_bolusfailed);
if (pump != null)
reply += "\n" + pump.shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
});
} else if (tempBasalWaitingForConfirmation != null && !tempBasalWaitingForConfirmation.processed &&
tempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - tempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
tempBasalWaitingForConfirmation.processed = true;
Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile != null)
ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(tempBasalWaitingForConfirmation.tempBasal, 30, true, profile, new Callback() {
@Override
public void run() {
if (result.success) {
String reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration);
reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed);
reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
});
} else if (cancelTempBasalWaitingForConfirmation != null && !cancelTempBasalWaitingForConfirmation.processed &&
cancelTempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - cancelTempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
cancelTempBasalWaitingForConfirmation.processed = true;
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (result.success) {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled);
reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
});
} else if (calibrationWaitingForConfirmation != null && !calibrationWaitingForConfirmation.processed &&
calibrationWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - calibrationWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
calibrationWaitingForConfirmation.processed = true;
boolean result = XdripCalibrations.sendIntent(calibrationWaitingForConfirmation.calibrationRequested);
if (result) {
reply = MainApp.gs(R.string.smscommunicator_calibrationsent);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else {
reply = MainApp.gs(R.string.smscommunicator_calibrationfailed);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
} else if (suspendWaitingForConfirmation != null && !suspendWaitingForConfirmation.processed &&
suspendWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - suspendWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
suspendWaitingForConfirmation.processed = true;
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
@Override
public void run() {
if (result.success) {
LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + suspendWaitingForConfirmation.duration * 60L * 1000);
NSUpload.uploadOpenAPSOffline(suspendWaitingForConfirmation.duration * 60);
MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED"));
String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " +
MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
} else {
String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
}
}
});
} else {
sendSMS(new Sms(receivedSms.phoneNumber, MainApp.gs(R.string.smscommunicator_unknowncommand), System.currentTimeMillis()));
}
resetWaitingMessages();
break;
}
}
MainApp.bus().post(new EventSmsCommunicatorUpdateGui());
}
public void sendNotificationToAllNumbers(String text) {
for (int i = 0; i < allowedNumbers.size(); i++) {
Sms sms = new Sms(allowedNumbers.get(i), text, System.currentTimeMillis());
sendSMS(sms);
}
}
private void sendSMSToAllNumbers(Sms sms) {
for (String number : allowedNumbers) {
sms.phoneNumber = number;
sendSMS(sms);
}
}
private void sendSMS(Sms sms) {
SmsManager smsManager = SmsManager.getDefault();
sms.text = stripAccents(sms.text);
if (sms.text.length() > 140) sms.text = sms.text.substring(0, 139);
try {
log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text);
smsManager.sendTextMessage(sms.phoneNumber, null, sms.text, null, null);
messages.add(sms);
} catch (IllegalArgumentException e) {
Notification notification = new Notification(Notification.INVALID_PHONE_NUMBER, MainApp.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
} catch (java.lang.SecurityException e) {
Notification notification = new Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL);
MainApp.bus().post(new EventNewNotification(notification));
}
}
private String generatePasscode() {
int startChar1 = 'A'; // on iphone 1st char is uppercase :)
String passCode = Character.toString((char) (startChar1 + Math.random() * ('z' - 'a' + 1)));
int startChar2 = Math.random() > 0.5 ? 'a' : 'A';
passCode += Character.toString((char) (startChar2 + Math.random() * ('z' - 'a' + 1)));
int startChar3 = Math.random() > 0.5 ? 'a' : 'A';
passCode += Character.toString((char) (startChar3 + Math.random() * ('z' - 'a' + 1)));
return passCode;
}
private void resetWaitingMessages() {
tempBasalWaitingForConfirmation = null;
cancelTempBasalWaitingForConfirmation = null;
bolusWaitingForConfirmation = null;
calibrationWaitingForConfirmation = null;
suspendWaitingForConfirmation = null;
}
private static String stripAccents(String s) {
s = Normalizer.normalize(s, Normalizer.Form.NFD);
s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
return s;
}
}

View file

@ -1,95 +0,0 @@
package info.nightscout.androidaps.plugins.Source;
import android.content.Intent;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.interfaces.BgSourceInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
import info.nightscout.utils.SP;
/**
* Created by mike on 28.11.2017.
*/
public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterface {
private static Logger log = LoggerFactory.getLogger(L.BGSOURCE);
private static SourceDexcomG5Plugin plugin = null;
public static SourceDexcomG5Plugin getPlugin() {
if (plugin == null)
plugin = new SourceDexcomG5Plugin();
return plugin;
}
private SourceDexcomG5Plugin() {
super(new PluginDescription()
.mainType(PluginType.BGSOURCE)
.fragmentClass(BGSourceFragment.class.getName())
.pluginName(R.string.DexcomG5)
.shortName(R.string.dexcomG5_shortname)
.preferencesId(R.xml.pref_dexcomg5)
.description(R.string.description_source_dexcom_g5)
);
}
@Override
public boolean advancedFilteringSupported() {
return true;
}
@Override
public void handleNewData(Intent intent) {
// onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle
if (!isEnabled(PluginType.BGSOURCE)) return;
Bundle bundle = intent.getExtras();
if (bundle == null) return;
BgReading bgReading = new BgReading();
String data = bundle.getString("data");
if (L.isEnabled(L.BGSOURCE))
log.debug("Received Dexcom Data", data);
if (data == null) return;
try {
JSONArray jsonArray = new JSONArray(data);
if (L.isEnabled(L.BGSOURCE))
log.debug("Received Dexcom Data size:" + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
bgReading.value = json.getInt("m_value");
bgReading.direction = json.getString("m_trend");
bgReading.date = json.getLong("m_time") * 1000L;
bgReading.raw = 0;
boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5");
if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
NSUpload.uploadBg(bgReading);
}
if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
NSUpload.sendToXdrip(bgReading);
}
}
} catch (JSONException e) {
log.error("Exception: ", e);
}
}
}

View file

@ -1,52 +0,0 @@
package info.nightscout.androidaps.plugins.Wear.wearintegration;
import android.os.AsyncTask;
import android.util.Log;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.DataMap;
import com.google.android.gms.wearable.Node;
import com.google.android.gms.wearable.NodeApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.PutDataRequest;
import com.google.android.gms.wearable.Wearable;
import java.util.concurrent.TimeUnit;
/**
* Created by emmablack on 12/26/14.
*/
class SendToDataLayerThread extends AsyncTask<DataMap,Void,Void> {
private GoogleApiClient googleApiClient;
private static final String TAG = "SendDataThread";
String path;
SendToDataLayerThread(String path, GoogleApiClient pGoogleApiClient) {
this.path = path;
googleApiClient = pGoogleApiClient;
}
@Override
protected Void doInBackground(DataMap... params) {
try {
final NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(15, TimeUnit.SECONDS);
for (Node node : nodes.getNodes()) {
for (DataMap dataMap : params) {
PutDataMapRequest putDMR = PutDataMapRequest.create(path);
putDMR.getDataMap().putAll(dataMap);
PutDataRequest request = putDMR.asPutDataRequest();
DataApi.DataItemResult result = Wearable.DataApi.putDataItem(googleApiClient, request).await(15, TimeUnit.SECONDS);
if (result.getStatus().isSuccess()) {
Log.d(TAG, "DataMap: " + dataMap + " sent to: " + node.getDisplayName());
} else {
Log.d(TAG, "ERROR: failed to send DataMap");
}
}
}
} catch (Exception e) {
Log.e(TAG, "Got exception sending data to wear: " + e.toString());
}
return null;
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop; package info.nightscout.androidaps.plugins.aps.loop;
import android.text.Html; import android.text.Html;
import android.text.Spanned; import android.text.Spanned;
@ -22,11 +22,11 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.DecimalFormatter; import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
* Created by mike on 09.06.2016. * Created by mike on 09.06.2016.
@ -307,6 +307,11 @@ public class APSResult {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump(); PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
Profile profile = ProfileFunctions.getInstance().getProfile(); Profile profile = ProfileFunctions.getInstance().getProfile();
if (profile == null) {
log.error("FALSE: No Profile");
return false;
}
if (usePercent) { if (usePercent) {
if (activeTemp == null && percent == 100) { if (activeTemp == null && percent == 100) {
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop; package info.nightscout.androidaps.plugins.aps.loop;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop; package info.nightscout.androidaps.plugins.aps.loop;
import android.app.Activity; import android.app.Activity;
@ -13,19 +13,16 @@ import android.widget.TextView;
import com.crashlytics.android.answers.CustomEvent; import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import butterknife.OnClick; import butterknife.OnClick;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
public class LoopFragment extends SubscriberFragment { public class LoopFragment extends SubscriberFragment {
@BindView(R.id.loop_run) @BindView(R.id.loop_run)

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop; package info.nightscout.androidaps.plugins.aps.loop;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.app.Notification; import android.app.Notification;
@ -34,6 +34,7 @@ import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
@ -43,24 +44,24 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui;
import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui; import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.Wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.events.EventAcceptOpenLoopChange; import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
@ -175,6 +176,14 @@ public class LoopPlugin extends PluginBase {
return loopSuspendedTill; return loopSuspendedTill;
} }
@Subscribe
public void onStatusEvent(final EventTempTargetChange ev) {
new Thread(() -> invoke("EventTempTargetChange", true)).start();
FabricPrivacy.getInstance().logCustom(new CustomEvent("TT_Loop_Run"));
}
public void suspendTo(long endTime) { public void suspendTo(long endTime) {
loopSuspendedTill = endTime; loopSuspendedTill = endTime;
isSuperBolus = false; isSuperBolus = false;
@ -409,8 +418,10 @@ public class LoopPlugin extends PluginBase {
.setAutoCancel(true) .setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH) .setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_ALARM) .setCategory(Notification.CATEGORY_ALARM)
.setVisibility(Notification.VISIBILITY_PUBLIC) .setVisibility(Notification.VISIBILITY_PUBLIC);
.setLocalOnly(true); if (SP.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true);
}
// Creates an explicit intent for an Activity in your app // Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class); Intent resultIntent = new Intent(MainApp.instance().getApplicationContext(), MainActivity.class);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop; package info.nightscout.androidaps.plugins.aps.loop;
import android.content.Context; import android.content.Context;
import android.content.res.AssetManager; import android.content.res.AssetManager;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop.events; package info.nightscout.androidaps.plugins.aps.loop.events;
import info.nightscout.androidaps.events.EventUpdateGui; import info.nightscout.androidaps.events.EventUpdateGui;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop.events; package info.nightscout.androidaps.plugins.aps.loop.events;
import info.nightscout.androidaps.events.EventUpdateGui; import info.nightscout.androidaps.events.EventUpdateGui;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Loop.events; package info.nightscout.androidaps.plugins.aps.loop.events;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA; package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -26,12 +26,12 @@ import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
public class DetermineBasalAdapterAMAJS { public class DetermineBasalAdapterAMAJS {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA; package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -7,8 +7,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultAMA extends APSResult { public class DetermineBasalResultAMA extends APSResult {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA; package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
@ -19,12 +19,12 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.androidaps.utils.JSONFormatter;
public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnClickListener { public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSAMA; package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -11,27 +11,26 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.HardLimits; import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.Round;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA; package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -23,9 +23,9 @@ import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
public class DetermineBasalAdapterMAJS { public class DetermineBasalAdapterMAJS {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA; package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -7,7 +7,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
public class DetermineBasalResultMA extends APSResult { public class DetermineBasalResultMA extends APSResult {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA; package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.ScriptableObject;
import org.slf4j.Logger; import org.slf4j.Logger;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA; package info.nightscout.androidaps.plugins.aps.openAPSMA;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
@ -12,12 +12,12 @@ import com.crashlytics.android.answers.CustomEvent;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.androidaps.utils.JSONFormatter;
public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener { public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener {
Button run; Button run;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA; package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -11,27 +11,26 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.HardLimits; import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.Round;
import static info.nightscout.utils.HardLimits.checkOnlyHardLimits; import static info.nightscout.androidaps.utils.HardLimits.checkOnlyHardLimits;
import static info.nightscout.utils.HardLimits.verifyHardLimits; import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA.events; package info.nightscout.androidaps.plugins.aps.openAPSMA.events;
import info.nightscout.androidaps.events.EventUpdateGui; import info.nightscout.androidaps.events.EventUpdateGui;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSMA.events; package info.nightscout.androidaps.plugins.aps.openAPSMA.events;
import info.nightscout.androidaps.events.EventUpdateGui; import info.nightscout.androidaps.events.EventUpdateGui;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSSMB; package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -26,12 +26,12 @@ import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback; import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.utils.SafeParse; import info.nightscout.androidaps.utils.SafeParse;
public class DetermineBasalAdapterSMBJS { public class DetermineBasalAdapterSMBJS {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);
@ -211,6 +211,7 @@ public class DetermineBasalAdapterSMBJS {
double autosensDataRatio, double autosensDataRatio,
boolean tempTargetSet, boolean tempTargetSet,
boolean microBolusAllowed, boolean microBolusAllowed,
boolean uamAllowed,
boolean advancedFiltering boolean advancedFiltering
) throws JSONException { ) throws JSONException {
@ -247,14 +248,16 @@ public class DetermineBasalAdapterSMBJS {
// mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact)); // mProfile.put("min_5m_carbimpact", SP.getDouble(R.string.key_openapsama_min_5m_carbimpact, SMBDefaults.min_5m_carbimpact));
//} //}
mProfile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap); mProfile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap);
mProfile.put("enableUAM", SP.getBoolean(R.string.key_use_uam, false)); mProfile.put("enableUAM", uamAllowed);
mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable); mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable);
mProfile.put("enableSMB_with_COB", SP.getBoolean(R.string.key_enableSMB_with_COB, false));
mProfile.put("enableSMB_with_temptarget", SP.getBoolean(R.string.key_enableSMB_with_temptarget, false)); boolean smbEnabled = SP.getBoolean(MainApp.gs(R.string.key_use_smb), false);
mProfile.put("allowSMB_with_high_temptarget", SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false)); mProfile.put("enableSMB_with_COB", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_COB, false));
mProfile.put("enableSMB_always", SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering); mProfile.put("enableSMB_with_temptarget", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_temptarget, false));
mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering); mProfile.put("allowSMB_with_high_temptarget", smbEnabled && SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false));
mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes)); mProfile.put("enableSMB_always", smbEnabled && SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering);
mProfile.put("enableSMB_after_carbs", smbEnabled && SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering);
mProfile.put("maxSMBBasalMinutes", SP.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes));
mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold); mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold);
mProfile.put("current_basal", basalrate); mProfile.put("current_basal", basalrate);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSSMB; package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@ -6,8 +6,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultSMB extends APSResult { public class DetermineBasalResultSMB extends APSResult {
private static final Logger log = LoggerFactory.getLogger(L.APS); private static final Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSSMB; package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
@ -22,12 +22,12 @@ import butterknife.OnClick;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.utils.JSONFormatter; import info.nightscout.androidaps.utils.JSONFormatter;
public class OpenAPSSMBFragment extends SubscriberFragment { public class OpenAPSSMBFragment extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);

View file

@ -1,11 +1,9 @@
package info.nightscout.androidaps.plugins.OpenAPSSMB; package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException; import org.json.JSONException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.GlucoseStatus; import info.nightscout.androidaps.data.GlucoseStatus;
@ -13,35 +11,35 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.Loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.Loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.HardLimits; import info.nightscout.androidaps.utils.HardLimits;
import info.nightscout.utils.Profiler; import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.utils.Round; import info.nightscout.androidaps.utils.Round;
import info.nightscout.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.
*/ */
public class OpenAPSSMBPlugin extends PluginBase implements APSInterface { public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(L.APS); private static Logger log = LoggerFactory.getLogger(L.APS);
private static OpenAPSSMBPlugin openAPSSMBPlugin; private static OpenAPSSMBPlugin openAPSSMBPlugin;
@ -150,7 +148,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "getMealData()", startPart); Profiler.log(log, "getMealData()", startPart);
double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value(); Constraint<Double> maxIOBAllowedConstraint = MainApp.getConstraintChecker().getMaxIOBAllowed();
inputConstraints.copyReasons(maxIOBAllowedConstraint);
double maxIob = maxIOBAllowedConstraint.value();
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]); minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]); maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
@ -198,6 +198,10 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering); MainApp.getConstraintChecker().isAdvancedFilteringEnabled(advancedFiltering);
inputConstraints.copyReasons(advancedFiltering); inputConstraints.copyReasons(advancedFiltering);
Constraint<Boolean> uam = new Constraint<>(true);
MainApp.getConstraintChecker().isUAMEnabled(uam);
inputConstraints.copyReasons(uam);
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart); Profiler.log(log, "detectSensitivityandCarbAbsorption()", startPart);
if (L.isEnabled(L.APS)) if (L.isEnabled(L.APS))
@ -209,6 +213,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
lastAutosensResult.ratio, //autosensDataRatio lastAutosensResult.ratio, //autosensDataRatio
isTempTarget, isTempTarget,
smbAllowed.value(), smbAllowed.value(),
uam.value(),
advancedFiltering.value() advancedFiltering.value()
); );
} catch (JSONException e) { } catch (JSONException e) {
@ -264,4 +269,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
return newvalue; return newvalue;
} }
public Constraint<Boolean> isSuperBolusEnabled(Constraint<Boolean> value) {
value.set(false);
return value;
}
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.OpenAPSSMB; package info.nightscout.androidaps.plugins.aps.openAPSSMB;
/** /**
* Created by mike on 10.12.2017. * Created by mike on 10.12.2017.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.Common; package info.nightscout.androidaps.plugins.common;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConfigBuilder; package info.nightscout.androidaps.plugins.configBuilder;
import android.content.Intent; import android.content.Intent;
@ -39,13 +39,14 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.utils.PasswordProtection; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.PasswordProtection;
public class ConfigBuilderFragment extends SubscriberFragment { public class ConfigBuilderFragment extends SubscriberFragment {

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConfigBuilder; package info.nightscout.androidaps.plugins.configBuilder;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
@ -20,11 +20,11 @@ import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.queue.CommandQueue; import info.nightscout.androidaps.queue.CommandQueue;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConfigBuilder; package info.nightscout.androidaps.plugins.configBuilder;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConfigBuilder; package info.nightscout.androidaps.plugins.configBuilder;
import android.content.Intent; import android.content.Intent;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
@ -16,15 +16,16 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventProfileSwitchChange; import info.nightscout.androidaps.events.EventProfileSwitchChange;
import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.general.overview.Dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.Callback;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
public class ProfileFunctions { public class ProfileFunctions {
private static Logger log = LoggerFactory.getLogger(L.PROFILE); private static Logger log = LoggerFactory.getLogger(L.PROFILE);
@ -139,4 +140,44 @@ public class ProfileFunctions {
return null; return null;
} }
public static ProfileSwitch prepareProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift, long date) {
ProfileSwitch profileSwitch = new ProfileSwitch();
profileSwitch.date = date;
profileSwitch.source = Source.USER;
profileSwitch.profileName = profileName;
profileSwitch.profileJson = profileStore.getSpecificProfile(profileName).getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage;
return profileSwitch;
}
public static void doProfileSwitch(final ProfileStore profileStore, final String profileName, final int duration, final int percentage, final int timeshift) {
ProfileSwitch profileSwitch = prepareProfileSwitch(profileStore, profileName, duration, percentage, timeshift, System.currentTimeMillis());
TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch);
FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
}
public static void doProfileSwitch(final int duration, final int percentage, final int timeshift) {
ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis());
if (profileSwitch != null) {
profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER;
profileSwitch.profileName = getInstance().getProfileName(System.currentTimeMillis(), false);
profileSwitch.profileJson = getInstance().getProfile().getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
profileSwitch.isCPP = percentage != 100 || timeshift != 0;
profileSwitch.timeshift = timeshift;
profileSwitch.percentage = percentage;
TreatmentsPlugin.getPlugin().addToHistoryProfileSwitch(profileSwitch);
FabricPrivacy.getInstance().logCustom(new CustomEvent("ProfileSwitch"));
} else {
log.error("No profile switch existing");
}
}
} }

View file

@ -0,0 +1,125 @@
package info.nightscout.androidaps.plugins.constraints.dstHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.utils.T;
/**
* Created by Rumen on 31.10.2018.
*/
public class DstHelperPlugin extends PluginBase implements ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
private int minutesToChange = 0;
static DstHelperPlugin plugin = null;
public static DstHelperPlugin getPlugin() {
if (plugin == null)
plugin = new DstHelperPlugin();
return plugin;
}
public DstHelperPlugin() {
super(new PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.neverVisible(true)
.alwaysEnabled(true)
.showInList(false)
.pluginName(R.string.dst_plugin_name)
);
}
public int dstTest(Calendar c) throws Exception {
// c = Calendar.getInstance(TimeZone.getDefault());
// c = Calendar.getInstance(TimeZone.getTimeZone("Australia/Lord_Howe"));
// c.setTimeInMillis(DateUtil.fromISODateString("2018-10-07T01:00:00Z").getTime());
long zoneOffset = c.get(Calendar.ZONE_OFFSET);
long d1 = c.getTimeInMillis() - zoneOffset;
c.setTimeInMillis(d1);
int offset1 = c.get(Calendar.DST_OFFSET);
c.add(Calendar.DATE, 1);
long d2 = c.getTimeInMillis();
int diffInHours = (int) ((d1 - d2) / -T.hours(1).msecs());
long offsetDetectedTime = 0;
// comparing millis because change can be < 1 hour
// log.debug("Starting from: "+startTimeString + " to "+endTimeString);
// log.debug("start "+offset1+" end "+c.get(Calendar.DST_OFFSET));
if (offset1 != c.get(Calendar.DST_OFFSET)) {
//we have a time change in next 24 hours, but when exactly
// log.debug("Daylight saving time detected between " + startTimeString + " and " + endTimeString);
// log.debug("Diff in hours is: "+diffInHours);
c.setTimeInMillis(d1 - zoneOffset);
offset1 = c.get(Calendar.DST_OFFSET);
for (int i = 0; i <= diffInHours * 4; i++) {
if (offset1 != c.get(Calendar.DST_OFFSET)) {
log.debug("Detected offset in " + ((i / 4) - zoneOffset / T.hours(1).msecs()) + " hours value is " + (offset1 - c.get(Calendar.DST_OFFSET)) / T.mins(1).msecs() + " minutes");
offsetDetectedTime = c.getTimeInMillis() - d1;
break;
}
c.add(Calendar.MINUTE, 15);
}
}
int minutesLeft = (int) ((offsetDetectedTime / T.mins(1).msecs()));
/*log.debug("zoneoffset(minutes):"+zoneOffset/T.mins(1).msecs());
log.debug("Start offset: "+offset1/T.mins(1).msecs());
log.debug("End offset :" + c.get(Calendar.DST_OFFSET)/T.mins(1).msecs());
log.debug("Now is:"+startTimeString);
log.debug("Detected in(min): "+(offsetDetectedTime/T.mins(1).msecs()));
log.debug("Returning value of: " + minutesLeft); */
minutesToChange = minutesLeft;
return minutesLeft;
}
//Return false if time to DST change is less than 91 and positive
@Override
public Constraint<Boolean> isLoopInvocationAllowed(Constraint<Boolean> value) {
try {
this.dstTest(Calendar.getInstance());
} catch (Exception e) {
e.printStackTrace();
}
if (this.minutesToChange <= 90 && minutesToChange > 0 && value.value()) {
try {
LoopPlugin loopPlugin = LoopPlugin.getPlugin();
if (loopPlugin.suspendedTo() == 0L) {
// loopPlugin.suspendTo(System.currentTimeMillis() + minutesToChange * T.mins(1).msecs());
warnUser(Notification.DST_LOOP_DISABLED, MainApp.gs(R.string.dst_loop_disabled_warning));
} else
log.debug("Loop already suspended");
} catch (Exception e) {
e.printStackTrace();
}
value.set(false, "DST in 90 minutes or less", this);
} else if (minutesToChange <= 24 * T.hours(1).mins() && minutesToChange > 0) {
warnUser(Notification.DST_IN_24H, MainApp.gs(R.string.dst_in_24h_warning));
}
return value;
}
// display warning
void warnUser(int id, String warningText) {
Notification notification = new Notification(id, warningText, Notification.LOW);
MainApp.bus().post(new EventNewNotification(notification));
}
}

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives; package info.nightscout.androidaps.plugins.constraints.objectives;
import android.app.Activity; import android.app.Activity;
import android.os.Bundle; import android.os.Bundle;
@ -22,9 +22,9 @@ import java.util.Date;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment; import info.nightscout.androidaps.plugins.common.SubscriberFragment;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective;
import info.nightscout.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
public class ObjectivesFragment extends SubscriberFragment { public class ObjectivesFragment extends SubscriberFragment {
RecyclerView recyclerView; RecyclerView recyclerView;
@ -120,6 +120,7 @@ public class ObjectivesFragment extends SubscriberFragment {
public void onBindViewHolder(@NonNull ViewHolder holder, int position) { public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(position); Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(position);
holder.title.setText(MainApp.gs(R.string.nth_objective, position + 1)); holder.title.setText(MainApp.gs(R.string.nth_objective, position + 1));
holder.revert.setVisibility(View.INVISIBLE);
if (objective.getObjective() != 0) { if (objective.getObjective() != 0) {
holder.objective.setVisibility(View.VISIBLE); holder.objective.setVisibility(View.VISIBLE);
holder.objective.setText(MainApp.gs(objective.getObjective())); holder.objective.setText(MainApp.gs(objective.getObjective()));
@ -145,6 +146,9 @@ public class ObjectivesFragment extends SubscriberFragment {
holder.verify.setVisibility(View.VISIBLE); holder.verify.setVisibility(View.VISIBLE);
holder.verify.setEnabled(objective.isCompleted() || enableFake.isChecked()); holder.verify.setEnabled(objective.isCompleted() || enableFake.isChecked());
holder.start.setVisibility(View.GONE); holder.start.setVisibility(View.GONE);
if(objective.isRevertable()) {
holder.revert.setVisibility(View.VISIBLE);
}
holder.progress.setVisibility(View.VISIBLE); holder.progress.setVisibility(View.VISIBLE);
holder.progress.removeAllViews(); holder.progress.removeAllViews();
for (Objective.Task task : objective.getTasks()) { for (Objective.Task task : objective.getTasks()) {
@ -169,8 +173,20 @@ public class ObjectivesFragment extends SubscriberFragment {
scrollToCurrentObjective(); scrollToCurrentObjective();
startUpdateTimer(); startUpdateTimer();
}); });
holder.revert.setOnClickListener((view) -> {
objective.setAccomplishedOn(null);
objective.setStartedOn(null);
if (position > 0) {
Objective prevObj = ObjectivesPlugin.getPlugin().getObjectives().get(position - 1);
prevObj.setAccomplishedOn(null);
}
notifyDataSetChanged();
scrollToCurrentObjective();
});
} }
@Override @Override
public int getItemCount() { public int getItemCount() {
return ObjectivesPlugin.getPlugin().getObjectives().size(); return ObjectivesPlugin.getPlugin().getObjectives().size();
@ -185,6 +201,7 @@ public class ObjectivesFragment extends SubscriberFragment {
public LinearLayout progress; public LinearLayout progress;
public Button verify; public Button verify;
public Button start; public Button start;
public Button revert;
public ViewHolder(View itemView) { public ViewHolder(View itemView) {
super(itemView); super(itemView);
@ -195,6 +212,7 @@ public class ObjectivesFragment extends SubscriberFragment {
progress = itemView.findViewById(R.id.objective_progress); progress = itemView.findViewById(R.id.objective_progress);
verify = itemView.findViewById(R.id.objective_verify); verify = itemView.findViewById(R.id.objective_verify);
start = itemView.findViewById(R.id.objective_start); start = itemView.findViewById(R.id.objective_start);
revert = itemView.findViewById(R.id.objective_back);
} }
} }
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives; package info.nightscout.androidaps.plugins.constraints.objectives;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -16,18 +16,18 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved; import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesSaved;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective1; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective1;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective2; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective2;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective3; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective3;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective4; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective4;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective5; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective5;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective6; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective6;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective7; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective7;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective8; import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective8;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
/** /**
* Created by mike on 05.08.2016. * Created by mike on 05.08.2016.

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives.events; package info.nightscout.androidaps.plugins.constraints.objectives.events;
import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.Event;

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives; package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import android.support.annotation.StringRes; import android.support.annotation.StringRes;
@ -8,8 +8,8 @@ import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
public abstract class Objective { public abstract class Objective {
@ -42,6 +42,10 @@ public abstract class Objective {
return true; return true;
} }
public boolean isRevertable() {
return false;
}
public boolean isAccomplished() { public boolean isAccomplished() {
return accomplishedOn != null; return accomplishedOn != null;
} }

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives; package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List; import java.util.List;
@ -7,14 +7,14 @@ import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.Loop.LoopPlugin; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.utils.SP; import info.nightscout.androidaps.utils.SP;
public class Objective1 extends Objective { public class Objective1 extends Objective {

View file

@ -1,11 +1,11 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives; package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
public class Objective2 extends Objective { public class Objective2 extends Objective {

View file

@ -1,4 +1,4 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives; package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;

View file

@ -1,11 +1,11 @@
package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives; package info.nightscout.androidaps.plugins.constraints.objectives.objectives;
import java.util.List; import java.util.List;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin; import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.utils.T; import info.nightscout.androidaps.utils.T;
public class Objective4 extends Objective { public class Objective4 extends Objective {
@ -25,4 +25,9 @@ public class Objective4 extends Objective {
} }
}); });
} }
@Override
public boolean isRevertable() {
return true;
}
} }

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